1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.6.22.  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
21#define SQLITE_ENABLE_UNLOCK_NOTIFY
22
23#define SQLITE_CORE 1
24#define SQLITE_AMALGAMATION 1
25#ifndef SQLITE_PRIVATE
26# define SQLITE_PRIVATE static
27#endif
28#ifndef SQLITE_API
29# define SQLITE_API
30#endif
31/************** Begin file sqliteInt.h ***************************************/
32/*
33** 2001 September 15
34**
35** The author disclaims copyright to this source code.  In place of
36** a legal notice, here is a blessing:
37**
38**    May you do good and not evil.
39**    May you find forgiveness for yourself and forgive others.
40**    May you share freely, never taking more than you give.
41**
42*************************************************************************
43** Internal interface definitions for SQLite.
44**
45*/
46#ifndef _SQLITEINT_H_
47#define _SQLITEINT_H_
48
49/*
50** These #defines should enable >2GB file support on POSIX if the
51** underlying operating system supports it.  If the OS lacks
52** large file support, or if the OS is windows, these should be no-ops.
53**
54** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
55** system #includes.  Hence, this block of code must be the very first
56** code in all source files.
57**
58** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
59** on the compiler command line.  This is necessary if you are compiling
60** on a recent machine (ex: Red Hat 7.2) but you want your code to work
61** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
62** without this option, LFS is enable.  But LFS does not exist in the kernel
63** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
64** portability you should omit LFS.
65**
66** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
67*/
68#ifndef SQLITE_DISABLE_LFS
69# define _LARGE_FILE       1
70# ifndef _FILE_OFFSET_BITS
71#   define _FILE_OFFSET_BITS 64
72# endif
73# define _LARGEFILE_SOURCE 1
74#endif
75
76/*
77** Include the configuration header output by 'configure' if we're using the
78** autoconf-based build
79*/
80#ifdef _HAVE_SQLITE_CONFIG_H
81#include "config.h"
82#endif
83
84/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
85/************** Begin file sqliteLimit.h *************************************/
86/*
87** 2007 May 7
88**
89** The author disclaims copyright to this source code.  In place of
90** a legal notice, here is a blessing:
91**
92**    May you do good and not evil.
93**    May you find forgiveness for yourself and forgive others.
94**    May you share freely, never taking more than you give.
95**
96*************************************************************************
97**
98** This file defines various limits of what SQLite can process.
99*/
100
101/*
102** The maximum length of a TEXT or BLOB in bytes.   This also
103** limits the size of a row in a table or index.
104**
105** The hard limit is the ability of a 32-bit signed integer
106** to count the size: 2^31-1 or 2147483647.
107*/
108#ifndef SQLITE_MAX_LENGTH
109# define SQLITE_MAX_LENGTH 1000000000
110#endif
111
112/*
113** This is the maximum number of
114**
115**    * Columns in a table
116**    * Columns in an index
117**    * Columns in a view
118**    * Terms in the SET clause of an UPDATE statement
119**    * Terms in the result set of a SELECT statement
120**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
121**    * Terms in the VALUES clause of an INSERT statement
122**
123** The hard upper limit here is 32676.  Most database people will
124** tell you that in a well-normalized database, you usually should
125** not have more than a dozen or so columns in any table.  And if
126** that is the case, there is no point in having more than a few
127** dozen values in any of the other situations described above.
128*/
129#ifndef SQLITE_MAX_COLUMN
130# define SQLITE_MAX_COLUMN 2000
131#endif
132
133/*
134** The maximum length of a single SQL statement in bytes.
135**
136** It used to be the case that setting this value to zero would
137** turn the limit off.  That is no longer true.  It is not possible
138** to turn this limit off.
139*/
140#ifndef SQLITE_MAX_SQL_LENGTH
141# define SQLITE_MAX_SQL_LENGTH 1000000000
142#endif
143
144/*
145** The maximum depth of an expression tree. This is limited to
146** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
147** want to place more severe limits on the complexity of an
148** expression.
149**
150** A value of 0 used to mean that the limit was not enforced.
151** But that is no longer true.  The limit is now strictly enforced
152** at all times.
153*/
154#ifndef SQLITE_MAX_EXPR_DEPTH
155# define SQLITE_MAX_EXPR_DEPTH 1000
156#endif
157
158/*
159** The maximum number of terms in a compound SELECT statement.
160** The code generator for compound SELECT statements does one
161** level of recursion for each term.  A stack overflow can result
162** if the number of terms is too large.  In practice, most SQL
163** never has more than 3 or 4 terms.  Use a value of 0 to disable
164** any limit on the number of terms in a compount SELECT.
165*/
166#ifndef SQLITE_MAX_COMPOUND_SELECT
167# define SQLITE_MAX_COMPOUND_SELECT 500
168#endif
169
170/*
171** The maximum number of opcodes in a VDBE program.
172** Not currently enforced.
173*/
174#ifndef SQLITE_MAX_VDBE_OP
175# define SQLITE_MAX_VDBE_OP 25000
176#endif
177
178/*
179** The maximum number of arguments to an SQL function.
180*/
181#ifndef SQLITE_MAX_FUNCTION_ARG
182# define SQLITE_MAX_FUNCTION_ARG 127
183#endif
184
185/*
186** The maximum number of in-memory pages to use for the main database
187** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
188*/
189#ifndef SQLITE_DEFAULT_CACHE_SIZE
190# define SQLITE_DEFAULT_CACHE_SIZE  2000
191#endif
192#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
193# define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
194#endif
195
196/*
197** The maximum number of attached databases.  This must be between 0
198** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
199** is used internally to track attached databases.
200*/
201#ifndef SQLITE_MAX_ATTACHED
202# define SQLITE_MAX_ATTACHED 10
203#endif
204
205
206/*
207** The maximum value of a ?nnn wildcard that the parser will accept.
208*/
209#ifndef SQLITE_MAX_VARIABLE_NUMBER
210# define SQLITE_MAX_VARIABLE_NUMBER 999
211#endif
212
213/* Maximum page size.  The upper bound on this value is 32768.  This a limit
214** imposed by the necessity of storing the value in a 2-byte unsigned integer
215** and the fact that the page size must be a power of 2.
216**
217** If this limit is changed, then the compiled library is technically
218** incompatible with an SQLite library compiled with a different limit. If
219** a process operating on a database with a page-size of 65536 bytes
220** crashes, then an instance of SQLite compiled with the default page-size
221** limit will not be able to rollback the aborted transaction. This could
222** lead to database corruption.
223*/
224#ifndef SQLITE_MAX_PAGE_SIZE
225# define SQLITE_MAX_PAGE_SIZE 32768
226#endif
227
228
229/*
230** The default size of a database page.
231*/
232#ifndef SQLITE_DEFAULT_PAGE_SIZE
233# define SQLITE_DEFAULT_PAGE_SIZE 1024
234#endif
235#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
236# undef SQLITE_DEFAULT_PAGE_SIZE
237# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
238#endif
239
240/*
241** Ordinarily, if no value is explicitly provided, SQLite creates databases
242** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
243** device characteristics (sector-size and atomic write() support),
244** SQLite may choose a larger value. This constant is the maximum value
245** SQLite will choose on its own.
246*/
247#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
248# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
249#endif
250#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
251# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
252# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
253#endif
254
255
256/*
257** Maximum number of pages in one database file.
258**
259** This is really just the default value for the max_page_count pragma.
260** This value can be lowered (or raised) at run-time using that the
261** max_page_count macro.
262*/
263#ifndef SQLITE_MAX_PAGE_COUNT
264# define SQLITE_MAX_PAGE_COUNT 1073741823
265#endif
266
267/*
268** Maximum length (in bytes) of the pattern in a LIKE or GLOB
269** operator.
270*/
271#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
272# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
273#endif
274
275/*
276** Maximum depth of recursion for triggers.
277**
278** A value of 1 means that a trigger program will not be able to itself
279** fire any triggers. A value of 0 means that no trigger programs at all
280** may be executed.
281*/
282#ifndef SQLITE_MAX_TRIGGER_DEPTH
283# define SQLITE_MAX_TRIGGER_DEPTH 1000
284#endif
285
286/************** End of sqliteLimit.h *****************************************/
287/************** Continuing where we left off in sqliteInt.h ******************/
288
289/* Disable nuisance warnings on Borland compilers */
290#if defined(__BORLANDC__)
291#pragma warn -rch /* unreachable code */
292#pragma warn -ccc /* Condition is always true or false */
293#pragma warn -aus /* Assigned value is never used */
294#pragma warn -csu /* Comparing signed and unsigned */
295#pragma warn -spa /* Suspicious pointer arithmetic */
296#endif
297
298/* Needed for various definitions... */
299#ifndef _GNU_SOURCE
300# define _GNU_SOURCE
301#endif
302
303/*
304** Include standard header files as necessary
305*/
306#ifdef HAVE_STDINT_H
307#include <stdint.h>
308#endif
309#ifdef HAVE_INTTYPES_H
310#include <inttypes.h>
311#endif
312
313#define SQLITE_INDEX_SAMPLES 10
314
315/*
316** This macro is used to "hide" some ugliness in casting an int
317** value to a ptr value under the MSVC 64-bit compiler.   Casting
318** non 64-bit values to ptr types results in a "hard" error with
319** the MSVC 64-bit compiler which this attempts to avoid.
320**
321** A simple compiler pragma or casting sequence could not be found
322** to correct this in all situations, so this macro was introduced.
323**
324** It could be argued that the intptr_t type could be used in this
325** case, but that type is not available on all compilers, or
326** requires the #include of specific headers which differs between
327** platforms.
328**
329** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
330** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
331** So we have to define the macros in different ways depending on the
332** compiler.
333*/
334#if defined(__GNUC__)
335# if defined(HAVE_STDINT_H)
336#   define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
337#   define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
338# else
339#   define SQLITE_INT_TO_PTR(X)  ((void*)(X))
340#   define SQLITE_PTR_TO_INT(X)  ((int)(X))
341# endif
342#else
343# define SQLITE_INT_TO_PTR(X)   ((void*)&((char*)0)[X])
344# define SQLITE_PTR_TO_INT(X)   ((int)(((char*)X)-(char*)0))
345#endif
346
347
348/*
349** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
350** Older versions of SQLite used an optional THREADSAFE macro.
351** We support that for legacy
352*/
353#if !defined(SQLITE_THREADSAFE)
354#if defined(THREADSAFE)
355# define SQLITE_THREADSAFE THREADSAFE
356#else
357# define SQLITE_THREADSAFE 1
358#endif
359#endif
360
361/*
362** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
363** It determines whether or not the features related to
364** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
365** be overridden at runtime using the sqlite3_config() API.
366*/
367#if !defined(SQLITE_DEFAULT_MEMSTATUS)
368# define SQLITE_DEFAULT_MEMSTATUS 1
369#endif
370
371/*
372** Exactly one of the following macros must be defined in order to
373** specify which memory allocation subsystem to use.
374**
375**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
376**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
377**     SQLITE_MEMORY_SIZE            // internal allocator #1
378**     SQLITE_MMAP_HEAP_SIZE         // internal mmap() allocator
379**     SQLITE_POW2_MEMORY_SIZE       // internal power-of-two allocator
380**
381** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
382** the default.
383*/
384#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
385    defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
386    defined(SQLITE_POW2_MEMORY_SIZE)>1
387# error "At most one of the following compile-time configuration options\
388 is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\
389 SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE"
390#endif
391#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\
392    defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\
393    defined(SQLITE_POW2_MEMORY_SIZE)==0
394# define SQLITE_SYSTEM_MALLOC 1
395#endif
396
397/*
398** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
399** sizes of memory allocations below this value where possible.
400*/
401#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
402# define SQLITE_MALLOC_SOFT_LIMIT 1024
403#endif
404
405/*
406** We need to define _XOPEN_SOURCE as follows in order to enable
407** recursive mutexes on most Unix systems.  But Mac OS X is different.
408** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
409** so it is omitted there.  See ticket #2673.
410**
411** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
412** implemented on some systems.  So we avoid defining it at all
413** if it is already defined or if it is unneeded because we are
414** not doing a threadsafe build.  Ticket #2681.
415**
416** See also ticket #2741.
417*/
418#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
419#  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
420#endif
421
422/*
423** The TCL headers are only needed when compiling the TCL bindings.
424*/
425#if defined(SQLITE_TCL) || defined(TCLSH)
426# include <tcl.h>
427#endif
428
429/*
430** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
431** Setting NDEBUG makes the code smaller and run faster.  So the following
432** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
433** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
434** feature.
435*/
436#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
437# define NDEBUG 1
438#endif
439
440/*
441** The testcase() macro is used to aid in coverage testing.  When
442** doing coverage testing, the condition inside the argument to
443** testcase() must be evaluated both true and false in order to
444** get full branch coverage.  The testcase() macro is inserted
445** to help ensure adequate test coverage in places where simple
446** condition/decision coverage is inadequate.  For example, testcase()
447** can be used to make sure boundary values are tested.  For
448** bitmask tests, testcase() can be used to make sure each bit
449** is significant and used at least once.  On switch statements
450** where multiple cases go to the same block of code, testcase()
451** can insure that all cases are evaluated.
452**
453*/
454#ifdef SQLITE_COVERAGE_TEST
455SQLITE_PRIVATE   void sqlite3Coverage(int);
456# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
457#else
458# define testcase(X)
459#endif
460
461/*
462** The TESTONLY macro is used to enclose variable declarations or
463** other bits of code that are needed to support the arguments
464** within testcase() and assert() macros.
465*/
466#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
467# define TESTONLY(X)  X
468#else
469# define TESTONLY(X)
470#endif
471
472/*
473** Sometimes we need a small amount of code such as a variable initialization
474** to setup for a later assert() statement.  We do not want this code to
475** appear when assert() is disabled.  The following macro is therefore
476** used to contain that setup code.  The "VVA" acronym stands for
477** "Verification, Validation, and Accreditation".  In other words, the
478** code within VVA_ONLY() will only run during verification processes.
479*/
480#ifndef NDEBUG
481# define VVA_ONLY(X)  X
482#else
483# define VVA_ONLY(X)
484#endif
485
486/*
487** The ALWAYS and NEVER macros surround boolean expressions which
488** are intended to always be true or false, respectively.  Such
489** expressions could be omitted from the code completely.  But they
490** are included in a few cases in order to enhance the resilience
491** of SQLite to unexpected behavior - to make the code "self-healing"
492** or "ductile" rather than being "brittle" and crashing at the first
493** hint of unplanned behavior.
494**
495** In other words, ALWAYS and NEVER are added for defensive code.
496**
497** When doing coverage testing ALWAYS and NEVER are hard-coded to
498** be true and false so that the unreachable code then specify will
499** not be counted as untested code.
500*/
501#if defined(SQLITE_COVERAGE_TEST)
502# define ALWAYS(X)      (1)
503# define NEVER(X)       (0)
504#elif !defined(NDEBUG)
505# define ALWAYS(X)      ((X)?1:(assert(0),0))
506# define NEVER(X)       ((X)?(assert(0),1):0)
507#else
508# define ALWAYS(X)      (X)
509# define NEVER(X)       (X)
510#endif
511
512/*
513** The macro unlikely() is a hint that surrounds a boolean
514** expression that is usually false.  Macro likely() surrounds
515** a boolean expression that is usually true.  GCC is able to
516** use these hints to generate better code, sometimes.
517*/
518#if defined(__GNUC__) && 0
519# define likely(X)    __builtin_expect((X),1)
520# define unlikely(X)  __builtin_expect((X),0)
521#else
522# define likely(X)    !!(X)
523# define unlikely(X)  !!(X)
524#endif
525
526/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
527/************** Begin file sqlite3.h *****************************************/
528/*
529** 2001 September 15
530**
531** The author disclaims copyright to this source code.  In place of
532** a legal notice, here is a blessing:
533**
534**    May you do good and not evil.
535**    May you find forgiveness for yourself and forgive others.
536**    May you share freely, never taking more than you give.
537**
538*************************************************************************
539** This header file defines the interface that the SQLite library
540** presents to client programs.  If a C-function, structure, datatype,
541** or constant definition does not appear in this file, then it is
542** not a published API of SQLite, is subject to change without
543** notice, and should not be referenced by programs that use SQLite.
544**
545** Some of the definitions that are in this file are marked as
546** "experimental".  Experimental interfaces are normally new
547** features recently added to SQLite.  We do not anticipate changes
548** to experimental interfaces but reserve the right to make minor changes
549** if experience from use "in the wild" suggest such changes are prudent.
550**
551** The official C-language API documentation for SQLite is derived
552** from comments in this file.  This file is the authoritative source
553** on how SQLite interfaces are suppose to operate.
554**
555** The name of this file under configuration management is "sqlite.h.in".
556** The makefile makes some minor changes to this file (such as inserting
557** the version number) and changes its name to "sqlite3.h" as
558** part of the build process.
559*/
560#ifndef _SQLITE3_H_
561#define _SQLITE3_H_
562#include <stdarg.h>     /* Needed for the definition of va_list */
563
564/*
565** Make sure we can call this stuff from C++.
566*/
567#if 0
568extern "C" {
569#endif
570
571
572/*
573** Add the ability to override 'extern'
574*/
575#ifndef SQLITE_EXTERN
576# define SQLITE_EXTERN extern
577#endif
578
579#ifndef SQLITE_API
580# define SQLITE_API
581#endif
582
583
584/*
585** These no-op macros are used in front of interfaces to mark those
586** interfaces as either deprecated or experimental.  New applications
587** should not use deprecated interfaces - they are support for backwards
588** compatibility only.  Application writers should be aware that
589** experimental interfaces are subject to change in point releases.
590**
591** These macros used to resolve to various kinds of compiler magic that
592** would generate warning messages when they were used.  But that
593** compiler magic ended up generating such a flurry of bug reports
594** that we have taken it all out and gone back to using simple
595** noop macros.
596*/
597#define SQLITE_DEPRECATED
598#define SQLITE_EXPERIMENTAL
599
600/*
601** Ensure these symbols were not defined by some previous header file.
602*/
603#ifdef SQLITE_VERSION
604# undef SQLITE_VERSION
605#endif
606#ifdef SQLITE_VERSION_NUMBER
607# undef SQLITE_VERSION_NUMBER
608#endif
609
610/*
611** CAPI3REF: Compile-Time Library Version Numbers
612**
613** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
614** evaluates to a string literal that is the SQLite version in the
615** format "X.Y.Z" where X is the major version number (always 3 for
616** SQLite3) and Y is the minor version number and Z is the release number.)^
617** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
618** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
619** numbers used in [SQLITE_VERSION].)^
620** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
621** be larger than the release from which it is derived.  Either Y will
622** be held constant and Z will be incremented or else Y will be incremented
623** and Z will be reset to zero.
624**
625** Since version 3.6.18, SQLite source code has been stored in the
626** <a href="http://www.fossil-scm.org/">Fossil configuration management
627** system</a>.  ^The SQLITE_SOURCE_ID macro evalutes to
628** a string which identifies a particular check-in of SQLite
629** within its configuration management system.  ^The SQLITE_SOURCE_ID
630** string contains the date and time of the check-in (UTC) and an SHA1
631** hash of the entire source tree.
632**
633** See also: [sqlite3_libversion()],
634** [sqlite3_libversion_number()], [sqlite3_sourceid()],
635** [sqlite_version()] and [sqlite_source_id()].
636*/
637#define SQLITE_VERSION        "3.6.22"
638#define SQLITE_VERSION_NUMBER 3006022
639#define SQLITE_SOURCE_ID      "2010-01-05 15:30:36 28d0d7710761114a44a1a3a425a6883c661f06e7"
640
641/*
642** CAPI3REF: Run-Time Library Version Numbers
643** KEYWORDS: sqlite3_version
644**
645** These interfaces provide the same information as the [SQLITE_VERSION],
646** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
647** but are associated with the library instead of the header file.  ^(Cautious
648** programmers might include assert() statements in their application to
649** verify that values returned by these interfaces match the macros in
650** the header, and thus insure that the application is
651** compiled with matching library and header files.
652**
653** <blockquote><pre>
654** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
655** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
656** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
657** </pre></blockquote>)^
658**
659** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
660** macro.  ^The sqlite3_libversion() function returns a pointer to the
661** to the sqlite3_version[] string constant.  The sqlite3_libversion()
662** function is provided for use in DLLs since DLL users usually do not have
663** direct access to string constants within the DLL.  ^The
664** sqlite3_libversion_number() function returns an integer equal to
665** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function a pointer
666** to a string constant whose value is the same as the [SQLITE_SOURCE_ID]
667** C preprocessor macro.
668**
669** See also: [sqlite_version()] and [sqlite_source_id()].
670*/
671SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
672SQLITE_API const char *sqlite3_libversion(void);
673SQLITE_API const char *sqlite3_sourceid(void);
674SQLITE_API int sqlite3_libversion_number(void);
675
676/*
677** CAPI3REF: Test To See If The Library Is Threadsafe
678**
679** ^The sqlite3_threadsafe() function returns zero if and only if
680** SQLite was compiled mutexing code omitted due to the
681** [SQLITE_THREADSAFE] compile-time option being set to 0.
682**
683** SQLite can be compiled with or without mutexes.  When
684** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
685** are enabled and SQLite is threadsafe.  When the
686** [SQLITE_THREADSAFE] macro is 0,
687** the mutexes are omitted.  Without the mutexes, it is not safe
688** to use SQLite concurrently from more than one thread.
689**
690** Enabling mutexes incurs a measurable performance penalty.
691** So if speed is of utmost importance, it makes sense to disable
692** the mutexes.  But for maximum safety, mutexes should be enabled.
693** ^The default behavior is for mutexes to be enabled.
694**
695** This interface can be used by an application to make sure that the
696** version of SQLite that it is linking against was compiled with
697** the desired setting of the [SQLITE_THREADSAFE] macro.
698**
699** This interface only reports on the compile-time mutex setting
700** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
701** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
702** can be fully or partially disabled using a call to [sqlite3_config()]
703** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
704** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
705** sqlite3_threadsafe() function shows only the compile-time setting of
706** thread safety, not any run-time changes to that setting made by
707** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
708** is unchanged by calls to sqlite3_config().)^
709**
710** See the [threading mode] documentation for additional information.
711*/
712SQLITE_API int sqlite3_threadsafe(void);
713
714/*
715** CAPI3REF: Database Connection Handle
716** KEYWORDS: {database connection} {database connections}
717**
718** Each open SQLite database is represented by a pointer to an instance of
719** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
720** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
721** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
722** is its destructor.  There are many other interfaces (such as
723** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
724** [sqlite3_busy_timeout()] to name but three) that are methods on an
725** sqlite3 object.
726*/
727typedef struct sqlite3 sqlite3;
728
729/*
730** CAPI3REF: 64-Bit Integer Types
731** KEYWORDS: sqlite_int64 sqlite_uint64
732**
733** Because there is no cross-platform way to specify 64-bit integer types
734** SQLite includes typedefs for 64-bit signed and unsigned integers.
735**
736** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
737** The sqlite_int64 and sqlite_uint64 types are supported for backwards
738** compatibility only.
739**
740** ^The sqlite3_int64 and sqlite_int64 types can store integer values
741** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
742** sqlite3_uint64 and sqlite_uint64 types can store integer values
743** between 0 and +18446744073709551615 inclusive.
744*/
745#ifdef SQLITE_INT64_TYPE
746  typedef SQLITE_INT64_TYPE sqlite_int64;
747  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
748#elif defined(_MSC_VER) || defined(__BORLANDC__)
749  typedef __int64 sqlite_int64;
750  typedef unsigned __int64 sqlite_uint64;
751#else
752  typedef long long int sqlite_int64;
753  typedef unsigned long long int sqlite_uint64;
754#endif
755typedef sqlite_int64 sqlite3_int64;
756typedef sqlite_uint64 sqlite3_uint64;
757
758/*
759** If compiling for a processor that lacks floating point support,
760** substitute integer for floating-point.
761*/
762#ifdef SQLITE_OMIT_FLOATING_POINT
763# define double sqlite3_int64
764#endif
765
766/*
767** CAPI3REF: Closing A Database Connection
768**
769** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
770** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
771** successfullly destroyed and all associated resources are deallocated.
772**
773** Applications must [sqlite3_finalize | finalize] all [prepared statements]
774** and [sqlite3_blob_close | close] all [BLOB handles] associated with
775** the [sqlite3] object prior to attempting to close the object.  ^If
776** sqlite3_close() is called on a [database connection] that still has
777** outstanding [prepared statements] or [BLOB handles], then it returns
778** SQLITE_BUSY.
779**
780** ^If [sqlite3_close()] is invoked while a transaction is open,
781** the transaction is automatically rolled back.
782**
783** The C parameter to [sqlite3_close(C)] must be either a NULL
784** pointer or an [sqlite3] object pointer obtained
785** from [sqlite3_open()], [sqlite3_open16()], or
786** [sqlite3_open_v2()], and not previously closed.
787** ^Calling sqlite3_close() with a NULL pointer argument is a
788** harmless no-op.
789*/
790SQLITE_API int sqlite3_close(sqlite3 *);
791
792/*
793** The type for a callback function.
794** This is legacy and deprecated.  It is included for historical
795** compatibility and is not documented.
796*/
797typedef int (*sqlite3_callback)(void*,int,char**, char**);
798
799/*
800** CAPI3REF: One-Step Query Execution Interface
801**
802** The sqlite3_exec() interface is a convenience wrapper around
803** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
804** that allows an application to run multiple statements of SQL
805** without having to use a lot of C code.
806**
807** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
808** semicolon-separate SQL statements passed into its 2nd argument,
809** in the context of the [database connection] passed in as its 1st
810** argument.  ^If the callback function of the 3rd argument to
811** sqlite3_exec() is not NULL, then it is invoked for each result row
812** coming out of the evaluated SQL statements.  ^The 4th argument to
813** to sqlite3_exec() is relayed through to the 1st argument of each
814** callback invocation.  ^If the callback pointer to sqlite3_exec()
815** is NULL, then no callback is ever invoked and result rows are
816** ignored.
817**
818** ^If an error occurs while evaluating the SQL statements passed into
819** sqlite3_exec(), then execution of the current statement stops and
820** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
821** is not NULL then any error message is written into memory obtained
822** from [sqlite3_malloc()] and passed back through the 5th parameter.
823** To avoid memory leaks, the application should invoke [sqlite3_free()]
824** on error message strings returned through the 5th parameter of
825** of sqlite3_exec() after the error message string is no longer needed.
826** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
827** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
828** NULL before returning.
829**
830** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
831** routine returns SQLITE_ABORT without invoking the callback again and
832** without running any subsequent SQL statements.
833**
834** ^The 2nd argument to the sqlite3_exec() callback function is the
835** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
836** callback is an array of pointers to strings obtained as if from
837** [sqlite3_column_text()], one for each column.  ^If an element of a
838** result row is NULL then the corresponding string pointer for the
839** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
840** sqlite3_exec() callback is an array of pointers to strings where each
841** entry represents the name of corresponding result column as obtained
842** from [sqlite3_column_name()].
843**
844** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
845** to an empty string, or a pointer that contains only whitespace and/or
846** SQL comments, then no SQL statements are evaluated and the database
847** is not changed.
848**
849** Restrictions:
850**
851** <ul>
852** <li> The application must insure that the 1st parameter to sqlite3_exec()
853**      is a valid and open [database connection].
854** <li> The application must not close [database connection] specified by
855**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
856** <li> The application must not modify the SQL statement text passed into
857**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
858** </ul>
859*/
860SQLITE_API int sqlite3_exec(
861  sqlite3*,                                  /* An open database */
862  const char *sql,                           /* SQL to be evaluated */
863  int (*callback)(void*,int,char**,char**),  /* Callback function */
864  void *,                                    /* 1st argument to callback */
865  char **errmsg                              /* Error msg written here */
866);
867
868/*
869** CAPI3REF: Result Codes
870** KEYWORDS: SQLITE_OK {error code} {error codes}
871** KEYWORDS: {result code} {result codes}
872**
873** Many SQLite functions return an integer result code from the set shown
874** here in order to indicates success or failure.
875**
876** New error codes may be added in future versions of SQLite.
877**
878** See also: [SQLITE_IOERR_READ | extended result codes]
879*/
880#define SQLITE_OK           0   /* Successful result */
881/* beginning-of-error-codes */
882#define SQLITE_ERROR        1   /* SQL error or missing database */
883#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
884#define SQLITE_PERM         3   /* Access permission denied */
885#define SQLITE_ABORT        4   /* Callback routine requested an abort */
886#define SQLITE_BUSY         5   /* The database file is locked */
887#define SQLITE_LOCKED       6   /* A table in the database is locked */
888#define SQLITE_NOMEM        7   /* A malloc() failed */
889#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
890#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
891#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
892#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
893#define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
894#define SQLITE_FULL        13   /* Insertion failed because database is full */
895#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
896#define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
897#define SQLITE_EMPTY       16   /* Database is empty */
898#define SQLITE_SCHEMA      17   /* The database schema changed */
899#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
900#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
901#define SQLITE_MISMATCH    20   /* Data type mismatch */
902#define SQLITE_MISUSE      21   /* Library used incorrectly */
903#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
904#define SQLITE_AUTH        23   /* Authorization denied */
905#define SQLITE_FORMAT      24   /* Auxiliary database format error */
906#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
907#define SQLITE_NOTADB      26   /* File opened that is not a database file */
908#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
909#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
910/* end-of-error-codes */
911
912/*
913** CAPI3REF: Extended Result Codes
914** KEYWORDS: {extended error code} {extended error codes}
915** KEYWORDS: {extended result code} {extended result codes}
916**
917** In its default configuration, SQLite API routines return one of 26 integer
918** [SQLITE_OK | result codes].  However, experience has shown that many of
919** these result codes are too coarse-grained.  They do not provide as
920** much information about problems as programmers might like.  In an effort to
921** address this, newer versions of SQLite (version 3.3.8 and later) include
922** support for additional result codes that provide more detailed information
923** about errors. The extended result codes are enabled or disabled
924** on a per database connection basis using the
925** [sqlite3_extended_result_codes()] API.
926**
927** Some of the available extended result codes are listed here.
928** One may expect the number of extended result codes will be expand
929** over time.  Software that uses extended result codes should expect
930** to see new result codes in future releases of SQLite.
931**
932** The SQLITE_OK result code will never be extended.  It will always
933** be exactly zero.
934*/
935#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
936#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
937#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
938#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
939#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
940#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
941#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
942#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
943#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
944#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
945#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
946#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
947#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
948#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
949#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
950#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
951#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
952#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED | (1<<8) )
953
954/*
955** CAPI3REF: Flags For File Open Operations
956**
957** These bit values are intended for use in the
958** 3rd parameter to the [sqlite3_open_v2()] interface and
959** in the 4th parameter to the xOpen method of the
960** [sqlite3_vfs] object.
961*/
962#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
963#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
964#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
965#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
966#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
967#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
968#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
969#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
970#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
971#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
972#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
973#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
974#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
975#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
976#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
977#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
978
979/*
980** CAPI3REF: Device Characteristics
981**
982** The xDeviceCapabilities method of the [sqlite3_io_methods]
983** object returns an integer which is a vector of the these
984** bit values expressing I/O characteristics of the mass storage
985** device that holds the file that the [sqlite3_io_methods]
986** refers to.
987**
988** The SQLITE_IOCAP_ATOMIC property means that all writes of
989** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
990** mean that writes of blocks that are nnn bytes in size and
991** are aligned to an address which is an integer multiple of
992** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
993** that when data is appended to a file, the data is appended
994** first then the size of the file is extended, never the other
995** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
996** information is written to disk in the same order as calls
997** to xWrite().
998*/
999#define SQLITE_IOCAP_ATOMIC          0x00000001
1000#define SQLITE_IOCAP_ATOMIC512       0x00000002
1001#define SQLITE_IOCAP_ATOMIC1K        0x00000004
1002#define SQLITE_IOCAP_ATOMIC2K        0x00000008
1003#define SQLITE_IOCAP_ATOMIC4K        0x00000010
1004#define SQLITE_IOCAP_ATOMIC8K        0x00000020
1005#define SQLITE_IOCAP_ATOMIC16K       0x00000040
1006#define SQLITE_IOCAP_ATOMIC32K       0x00000080
1007#define SQLITE_IOCAP_ATOMIC64K       0x00000100
1008#define SQLITE_IOCAP_SAFE_APPEND     0x00000200
1009#define SQLITE_IOCAP_SEQUENTIAL      0x00000400
1010
1011/*
1012** CAPI3REF: File Locking Levels
1013**
1014** SQLite uses one of these integer values as the second
1015** argument to calls it makes to the xLock() and xUnlock() methods
1016** of an [sqlite3_io_methods] object.
1017*/
1018#define SQLITE_LOCK_NONE          0
1019#define SQLITE_LOCK_SHARED        1
1020#define SQLITE_LOCK_RESERVED      2
1021#define SQLITE_LOCK_PENDING       3
1022#define SQLITE_LOCK_EXCLUSIVE     4
1023
1024/*
1025** CAPI3REF: Synchronization Type Flags
1026**
1027** When SQLite invokes the xSync() method of an
1028** [sqlite3_io_methods] object it uses a combination of
1029** these integer values as the second argument.
1030**
1031** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1032** sync operation only needs to flush data to mass storage.  Inode
1033** information need not be flushed. If the lower four bits of the flag
1034** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1035** If the lower four bits equal SQLITE_SYNC_FULL, that means
1036** to use Mac OS X style fullsync instead of fsync().
1037*/
1038#define SQLITE_SYNC_NORMAL        0x00002
1039#define SQLITE_SYNC_FULL          0x00003
1040#define SQLITE_SYNC_DATAONLY      0x00010
1041
1042/*
1043** CAPI3REF: OS Interface Open File Handle
1044**
1045** An [sqlite3_file] object represents an open file in the
1046** [sqlite3_vfs | OS interface layer].  Individual OS interface
1047** implementations will
1048** want to subclass this object by appending additional fields
1049** for their own use.  The pMethods entry is a pointer to an
1050** [sqlite3_io_methods] object that defines methods for performing
1051** I/O operations on the open file.
1052*/
1053typedef struct sqlite3_file sqlite3_file;
1054struct sqlite3_file {
1055  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1056};
1057
1058/*
1059** CAPI3REF: OS Interface File Virtual Methods Object
1060**
1061** Every file opened by the [sqlite3_vfs] xOpen method populates an
1062** [sqlite3_file] object (or, more commonly, a subclass of the
1063** [sqlite3_file] object) with a pointer to an instance of this object.
1064** This object defines the methods used to perform various operations
1065** against the open file represented by the [sqlite3_file] object.
1066**
1067** If the xOpen method sets the sqlite3_file.pMethods element
1068** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1069** may be invoked even if the xOpen reported that it failed.  The
1070** only way to prevent a call to xClose following a failed xOpen
1071** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1072**
1073** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1074** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1075** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1076** flag may be ORed in to indicate that only the data of the file
1077** and not its inode needs to be synced.
1078**
1079** The integer values to xLock() and xUnlock() are one of
1080** <ul>
1081** <li> [SQLITE_LOCK_NONE],
1082** <li> [SQLITE_LOCK_SHARED],
1083** <li> [SQLITE_LOCK_RESERVED],
1084** <li> [SQLITE_LOCK_PENDING], or
1085** <li> [SQLITE_LOCK_EXCLUSIVE].
1086** </ul>
1087** xLock() increases the lock. xUnlock() decreases the lock.
1088** The xCheckReservedLock() method checks whether any database connection,
1089** either in this process or in some other process, is holding a RESERVED,
1090** PENDING, or EXCLUSIVE lock on the file.  It returns true
1091** if such a lock exists and false otherwise.
1092**
1093** The xFileControl() method is a generic interface that allows custom
1094** VFS implementations to directly control an open file using the
1095** [sqlite3_file_control()] interface.  The second "op" argument is an
1096** integer opcode.  The third argument is a generic pointer intended to
1097** point to a structure that may contain arguments or space in which to
1098** write return values.  Potential uses for xFileControl() might be
1099** functions to enable blocking locks with timeouts, to change the
1100** locking strategy (for example to use dot-file locks), to inquire
1101** about the status of a lock, or to break stale locks.  The SQLite
1102** core reserves all opcodes less than 100 for its own use.
1103** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1104** Applications that define a custom xFileControl method should use opcodes
1105** greater than 100 to avoid conflicts.
1106**
1107** The xSectorSize() method returns the sector size of the
1108** device that underlies the file.  The sector size is the
1109** minimum write that can be performed without disturbing
1110** other bytes in the file.  The xDeviceCharacteristics()
1111** method returns a bit vector describing behaviors of the
1112** underlying device:
1113**
1114** <ul>
1115** <li> [SQLITE_IOCAP_ATOMIC]
1116** <li> [SQLITE_IOCAP_ATOMIC512]
1117** <li> [SQLITE_IOCAP_ATOMIC1K]
1118** <li> [SQLITE_IOCAP_ATOMIC2K]
1119** <li> [SQLITE_IOCAP_ATOMIC4K]
1120** <li> [SQLITE_IOCAP_ATOMIC8K]
1121** <li> [SQLITE_IOCAP_ATOMIC16K]
1122** <li> [SQLITE_IOCAP_ATOMIC32K]
1123** <li> [SQLITE_IOCAP_ATOMIC64K]
1124** <li> [SQLITE_IOCAP_SAFE_APPEND]
1125** <li> [SQLITE_IOCAP_SEQUENTIAL]
1126** </ul>
1127**
1128** The SQLITE_IOCAP_ATOMIC property means that all writes of
1129** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1130** mean that writes of blocks that are nnn bytes in size and
1131** are aligned to an address which is an integer multiple of
1132** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1133** that when data is appended to a file, the data is appended
1134** first then the size of the file is extended, never the other
1135** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1136** information is written to disk in the same order as calls
1137** to xWrite().
1138**
1139** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1140** in the unread portions of the buffer with zeros.  A VFS that
1141** fails to zero-fill short reads might seem to work.  However,
1142** failure to zero-fill short reads will eventually lead to
1143** database corruption.
1144*/
1145typedef struct sqlite3_io_methods sqlite3_io_methods;
1146struct sqlite3_io_methods {
1147  int iVersion;
1148  int (*xClose)(sqlite3_file*);
1149  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1150  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1151  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1152  int (*xSync)(sqlite3_file*, int flags);
1153  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1154  int (*xLock)(sqlite3_file*, int);
1155  int (*xUnlock)(sqlite3_file*, int);
1156  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1157  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1158  int (*xSectorSize)(sqlite3_file*);
1159  int (*xDeviceCharacteristics)(sqlite3_file*);
1160  /* Additional methods may be added in future releases */
1161};
1162
1163/*
1164** CAPI3REF: Standard File Control Opcodes
1165**
1166** These integer constants are opcodes for the xFileControl method
1167** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1168** interface.
1169**
1170** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1171** opcode causes the xFileControl method to write the current state of
1172** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1173** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1174** into an integer that the pArg argument points to. This capability
1175** is used during testing and only needs to be supported when SQLITE_TEST
1176** is defined.
1177*/
1178#define SQLITE_FCNTL_LOCKSTATE        1
1179#define SQLITE_GET_LOCKPROXYFILE      2
1180#define SQLITE_SET_LOCKPROXYFILE      3
1181#define SQLITE_LAST_ERRNO             4
1182
1183/*
1184** CAPI3REF: Mutex Handle
1185**
1186** The mutex module within SQLite defines [sqlite3_mutex] to be an
1187** abstract type for a mutex object.  The SQLite core never looks
1188** at the internal representation of an [sqlite3_mutex].  It only
1189** deals with pointers to the [sqlite3_mutex] object.
1190**
1191** Mutexes are created using [sqlite3_mutex_alloc()].
1192*/
1193typedef struct sqlite3_mutex sqlite3_mutex;
1194
1195/*
1196** CAPI3REF: OS Interface Object
1197**
1198** An instance of the sqlite3_vfs object defines the interface between
1199** the SQLite core and the underlying operating system.  The "vfs"
1200** in the name of the object stands for "virtual file system".
1201**
1202** The value of the iVersion field is initially 1 but may be larger in
1203** future versions of SQLite.  Additional fields may be appended to this
1204** object when the iVersion value is increased.  Note that the structure
1205** of the sqlite3_vfs object changes in the transaction between
1206** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1207** modified.
1208**
1209** The szOsFile field is the size of the subclassed [sqlite3_file]
1210** structure used by this VFS.  mxPathname is the maximum length of
1211** a pathname in this VFS.
1212**
1213** Registered sqlite3_vfs objects are kept on a linked list formed by
1214** the pNext pointer.  The [sqlite3_vfs_register()]
1215** and [sqlite3_vfs_unregister()] interfaces manage this list
1216** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1217** searches the list.  Neither the application code nor the VFS
1218** implementation should use the pNext pointer.
1219**
1220** The pNext field is the only field in the sqlite3_vfs
1221** structure that SQLite will ever modify.  SQLite will only access
1222** or modify this field while holding a particular static mutex.
1223** The application should never modify anything within the sqlite3_vfs
1224** object once the object has been registered.
1225**
1226** The zName field holds the name of the VFS module.  The name must
1227** be unique across all VFS modules.
1228**
1229** SQLite will guarantee that the zFilename parameter to xOpen
1230** is either a NULL pointer or string obtained
1231** from xFullPathname().  SQLite further guarantees that
1232** the string will be valid and unchanged until xClose() is
1233** called. Because of the previous sentence,
1234** the [sqlite3_file] can safely store a pointer to the
1235** filename if it needs to remember the filename for some reason.
1236** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1237** must invent its own temporary name for the file.  Whenever the
1238** xFilename parameter is NULL it will also be the case that the
1239** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1240**
1241** The flags argument to xOpen() includes all bits set in
1242** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1243** or [sqlite3_open16()] is used, then flags includes at least
1244** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1245** If xOpen() opens a file read-only then it sets *pOutFlags to
1246** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1247**
1248** SQLite will also add one of the following flags to the xOpen()
1249** call, depending on the object being opened:
1250**
1251** <ul>
1252** <li>  [SQLITE_OPEN_MAIN_DB]
1253** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1254** <li>  [SQLITE_OPEN_TEMP_DB]
1255** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1256** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1257** <li>  [SQLITE_OPEN_SUBJOURNAL]
1258** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1259** </ul>
1260**
1261** The file I/O implementation can use the object type flags to
1262** change the way it deals with files.  For example, an application
1263** that does not care about crash recovery or rollback might make
1264** the open of a journal file a no-op.  Writes to this journal would
1265** also be no-ops, and any attempt to read the journal would return
1266** SQLITE_IOERR.  Or the implementation might recognize that a database
1267** file will be doing page-aligned sector reads and writes in a random
1268** order and set up its I/O subsystem accordingly.
1269**
1270** SQLite might also add one of the following flags to the xOpen method:
1271**
1272** <ul>
1273** <li> [SQLITE_OPEN_DELETEONCLOSE]
1274** <li> [SQLITE_OPEN_EXCLUSIVE]
1275** </ul>
1276**
1277** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1278** deleted when it is closed.  The [SQLITE_OPEN_DELETEONCLOSE]
1279** will be set for TEMP  databases, journals and for subjournals.
1280**
1281** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1282** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1283** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1284** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1285** SQLITE_OPEN_CREATE, is used to indicate that file should always
1286** be created, and that it is an error if it already exists.
1287** It is <i>not</i> used to indicate the file should be opened
1288** for exclusive access.
1289**
1290** At least szOsFile bytes of memory are allocated by SQLite
1291** to hold the  [sqlite3_file] structure passed as the third
1292** argument to xOpen.  The xOpen method does not have to
1293** allocate the structure; it should just fill it in.  Note that
1294** the xOpen method must set the sqlite3_file.pMethods to either
1295** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1296** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1297** element will be valid after xOpen returns regardless of the success
1298** or failure of the xOpen call.
1299**
1300** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1301** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1302** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1303** to test whether a file is at least readable.   The file can be a
1304** directory.
1305**
1306** SQLite will always allocate at least mxPathname+1 bytes for the
1307** output buffer xFullPathname.  The exact size of the output buffer
1308** is also passed as a parameter to both  methods. If the output buffer
1309** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1310** handled as a fatal error by SQLite, vfs implementations should endeavor
1311** to prevent this by setting mxPathname to a sufficiently large value.
1312**
1313** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1314** are not strictly a part of the filesystem, but they are
1315** included in the VFS structure for completeness.
1316** The xRandomness() function attempts to return nBytes bytes
1317** of good-quality randomness into zOut.  The return value is
1318** the actual number of bytes of randomness obtained.
1319** The xSleep() method causes the calling thread to sleep for at
1320** least the number of microseconds given.  The xCurrentTime()
1321** method returns a Julian Day Number for the current date and time.
1322**
1323*/
1324typedef struct sqlite3_vfs sqlite3_vfs;
1325struct sqlite3_vfs {
1326  int iVersion;            /* Structure version number */
1327  int szOsFile;            /* Size of subclassed sqlite3_file */
1328  int mxPathname;          /* Maximum file pathname length */
1329  sqlite3_vfs *pNext;      /* Next registered VFS */
1330  const char *zName;       /* Name of this virtual file system */
1331  void *pAppData;          /* Pointer to application-specific data */
1332  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1333               int flags, int *pOutFlags);
1334  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1335  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1336  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1337  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1338  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1339  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1340  void (*xDlClose)(sqlite3_vfs*, void*);
1341  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1342  int (*xSleep)(sqlite3_vfs*, int microseconds);
1343  int (*xCurrentTime)(sqlite3_vfs*, double*);
1344  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1345  /* New fields may be appended in figure versions.  The iVersion
1346  ** value will increment whenever this happens. */
1347};
1348
1349/*
1350** CAPI3REF: Flags for the xAccess VFS method
1351**
1352** These integer constants can be used as the third parameter to
1353** the xAccess method of an [sqlite3_vfs] object.  They determine
1354** what kind of permissions the xAccess method is looking for.
1355** With SQLITE_ACCESS_EXISTS, the xAccess method
1356** simply checks whether the file exists.
1357** With SQLITE_ACCESS_READWRITE, the xAccess method
1358** checks whether the file is both readable and writable.
1359** With SQLITE_ACCESS_READ, the xAccess method
1360** checks whether the file is readable.
1361*/
1362#define SQLITE_ACCESS_EXISTS    0
1363#define SQLITE_ACCESS_READWRITE 1
1364#define SQLITE_ACCESS_READ      2
1365
1366/*
1367** CAPI3REF: Initialize The SQLite Library
1368**
1369** ^The sqlite3_initialize() routine initializes the
1370** SQLite library.  ^The sqlite3_shutdown() routine
1371** deallocates any resources that were allocated by sqlite3_initialize().
1372** These routines are designed to aid in process initialization and
1373** shutdown on embedded systems.  Workstation applications using
1374** SQLite normally do not need to invoke either of these routines.
1375**
1376** A call to sqlite3_initialize() is an "effective" call if it is
1377** the first time sqlite3_initialize() is invoked during the lifetime of
1378** the process, or if it is the first time sqlite3_initialize() is invoked
1379** following a call to sqlite3_shutdown().  ^(Only an effective call
1380** of sqlite3_initialize() does any initialization.  All other calls
1381** are harmless no-ops.)^
1382**
1383** A call to sqlite3_shutdown() is an "effective" call if it is the first
1384** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1385** an effective call to sqlite3_shutdown() does any deinitialization.
1386** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1387**
1388** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1389** is not.  The sqlite3_shutdown() interface must only be called from a
1390** single thread.  All open [database connections] must be closed and all
1391** other SQLite resources must be deallocated prior to invoking
1392** sqlite3_shutdown().
1393**
1394** Among other things, ^sqlite3_initialize() will invoke
1395** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1396** will invoke sqlite3_os_end().
1397**
1398** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1399** ^If for some reason, sqlite3_initialize() is unable to initialize
1400** the library (perhaps it is unable to allocate a needed resource such
1401** as a mutex) it returns an [error code] other than [SQLITE_OK].
1402**
1403** ^The sqlite3_initialize() routine is called internally by many other
1404** SQLite interfaces so that an application usually does not need to
1405** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1406** calls sqlite3_initialize() so the SQLite library will be automatically
1407** initialized when [sqlite3_open()] is called if it has not be initialized
1408** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1409** compile-time option, then the automatic calls to sqlite3_initialize()
1410** are omitted and the application must call sqlite3_initialize() directly
1411** prior to using any other SQLite interface.  For maximum portability,
1412** it is recommended that applications always invoke sqlite3_initialize()
1413** directly prior to using any other SQLite interface.  Future releases
1414** of SQLite may require this.  In other words, the behavior exhibited
1415** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1416** default behavior in some future release of SQLite.
1417**
1418** The sqlite3_os_init() routine does operating-system specific
1419** initialization of the SQLite library.  The sqlite3_os_end()
1420** routine undoes the effect of sqlite3_os_init().  Typical tasks
1421** performed by these routines include allocation or deallocation
1422** of static resources, initialization of global variables,
1423** setting up a default [sqlite3_vfs] module, or setting up
1424** a default configuration using [sqlite3_config()].
1425**
1426** The application should never invoke either sqlite3_os_init()
1427** or sqlite3_os_end() directly.  The application should only invoke
1428** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1429** interface is called automatically by sqlite3_initialize() and
1430** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1431** implementations for sqlite3_os_init() and sqlite3_os_end()
1432** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1433** When [custom builds | built for other platforms]
1434** (using the [SQLITE_OS_OTHER=1] compile-time
1435** option) the application must supply a suitable implementation for
1436** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1437** implementation of sqlite3_os_init() or sqlite3_os_end()
1438** must return [SQLITE_OK] on success and some other [error code] upon
1439** failure.
1440*/
1441SQLITE_API int sqlite3_initialize(void);
1442SQLITE_API int sqlite3_shutdown(void);
1443SQLITE_API int sqlite3_os_init(void);
1444SQLITE_API int sqlite3_os_end(void);
1445
1446/*
1447** CAPI3REF: Configuring The SQLite Library
1448** EXPERIMENTAL
1449**
1450** The sqlite3_config() interface is used to make global configuration
1451** changes to SQLite in order to tune SQLite to the specific needs of
1452** the application.  The default configuration is recommended for most
1453** applications and so this routine is usually not necessary.  It is
1454** provided to support rare applications with unusual needs.
1455**
1456** The sqlite3_config() interface is not threadsafe.  The application
1457** must insure that no other SQLite interfaces are invoked by other
1458** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1459** may only be invoked prior to library initialization using
1460** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1461** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1462** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1463** Note, however, that ^sqlite3_config() can be called as part of the
1464** implementation of an application-defined [sqlite3_os_init()].
1465**
1466** The first argument to sqlite3_config() is an integer
1467** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1468** what property of SQLite is to be configured.  Subsequent arguments
1469** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1470** in the first argument.
1471**
1472** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1473** ^If the option is unknown or SQLite is unable to set the option
1474** then this routine returns a non-zero [error code].
1475*/
1476SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
1477
1478/*
1479** CAPI3REF: Configure database connections
1480** EXPERIMENTAL
1481**
1482** The sqlite3_db_config() interface is used to make configuration
1483** changes to a [database connection].  The interface is similar to
1484** [sqlite3_config()] except that the changes apply to a single
1485** [database connection] (specified in the first argument).  The
1486** sqlite3_db_config() interface should only be used immediately after
1487** the database connection is created using [sqlite3_open()],
1488** [sqlite3_open16()], or [sqlite3_open_v2()].
1489**
1490** The second argument to sqlite3_db_config(D,V,...)  is the
1491** configuration verb - an integer code that indicates what
1492** aspect of the [database connection] is being configured.
1493** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1494** New verbs are likely to be added in future releases of SQLite.
1495** Additional arguments depend on the verb.
1496**
1497** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1498** the call is considered successful.
1499*/
1500SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
1501
1502/*
1503** CAPI3REF: Memory Allocation Routines
1504** EXPERIMENTAL
1505**
1506** An instance of this object defines the interface between SQLite
1507** and low-level memory allocation routines.
1508**
1509** This object is used in only one place in the SQLite interface.
1510** A pointer to an instance of this object is the argument to
1511** [sqlite3_config()] when the configuration option is
1512** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1513** By creating an instance of this object
1514** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1515** during configuration, an application can specify an alternative
1516** memory allocation subsystem for SQLite to use for all of its
1517** dynamic memory needs.
1518**
1519** Note that SQLite comes with several [built-in memory allocators]
1520** that are perfectly adequate for the overwhelming majority of applications
1521** and that this object is only useful to a tiny minority of applications
1522** with specialized memory allocation requirements.  This object is
1523** also used during testing of SQLite in order to specify an alternative
1524** memory allocator that simulates memory out-of-memory conditions in
1525** order to verify that SQLite recovers gracefully from such
1526** conditions.
1527**
1528** The xMalloc and xFree methods must work like the
1529** malloc() and free() functions from the standard C library.
1530** The xRealloc method must work like realloc() from the standard C library
1531** with the exception that if the second argument to xRealloc is zero,
1532** xRealloc must be a no-op - it must not perform any allocation or
1533** deallocation.  ^SQLite guarantees that the second argument to
1534** xRealloc is always a value returned by a prior call to xRoundup.
1535** And so in cases where xRoundup always returns a positive number,
1536** xRealloc can perform exactly as the standard library realloc() and
1537** still be in compliance with this specification.
1538**
1539** xSize should return the allocated size of a memory allocation
1540** previously obtained from xMalloc or xRealloc.  The allocated size
1541** is always at least as big as the requested size but may be larger.
1542**
1543** The xRoundup method returns what would be the allocated size of
1544** a memory allocation given a particular requested size.  Most memory
1545** allocators round up memory allocations at least to the next multiple
1546** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1547** Every memory allocation request coming in through [sqlite3_malloc()]
1548** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1549** that causes the corresponding memory allocation to fail.
1550**
1551** The xInit method initializes the memory allocator.  (For example,
1552** it might allocate any require mutexes or initialize internal data
1553** structures.  The xShutdown method is invoked (indirectly) by
1554** [sqlite3_shutdown()] and should deallocate any resources acquired
1555** by xInit.  The pAppData pointer is used as the only parameter to
1556** xInit and xShutdown.
1557**
1558** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1559** the xInit method, so the xInit method need not be threadsafe.  The
1560** xShutdown method is only called from [sqlite3_shutdown()] so it does
1561** not need to be threadsafe either.  For all other methods, SQLite
1562** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1563** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1564** it is by default) and so the methods are automatically serialized.
1565** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1566** methods must be threadsafe or else make their own arrangements for
1567** serialization.
1568**
1569** SQLite will never invoke xInit() more than once without an intervening
1570** call to xShutdown().
1571*/
1572typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1573struct sqlite3_mem_methods {
1574  void *(*xMalloc)(int);         /* Memory allocation function */
1575  void (*xFree)(void*);          /* Free a prior allocation */
1576  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1577  int (*xSize)(void*);           /* Return the size of an allocation */
1578  int (*xRoundup)(int);          /* Round up request size to allocation size */
1579  int (*xInit)(void*);           /* Initialize the memory allocator */
1580  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1581  void *pAppData;                /* Argument to xInit() and xShutdown() */
1582};
1583
1584/*
1585** CAPI3REF: Configuration Options
1586** EXPERIMENTAL
1587**
1588** These constants are the available integer configuration options that
1589** can be passed as the first argument to the [sqlite3_config()] interface.
1590**
1591** New configuration options may be added in future releases of SQLite.
1592** Existing configuration options might be discontinued.  Applications
1593** should check the return code from [sqlite3_config()] to make sure that
1594** the call worked.  The [sqlite3_config()] interface will return a
1595** non-zero [error code] if a discontinued or unsupported configuration option
1596** is invoked.
1597**
1598** <dl>
1599** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1600** <dd>There are no arguments to this option.  ^This option sets the
1601** [threading mode] to Single-thread.  In other words, it disables
1602** all mutexing and puts SQLite into a mode where it can only be used
1603** by a single thread.   ^If SQLite is compiled with
1604** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1605** it is not possible to change the [threading mode] from its default
1606** value of Single-thread and so [sqlite3_config()] will return
1607** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1608** configuration option.</dd>
1609**
1610** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1611** <dd>There are no arguments to this option.  ^This option sets the
1612** [threading mode] to Multi-thread.  In other words, it disables
1613** mutexing on [database connection] and [prepared statement] objects.
1614** The application is responsible for serializing access to
1615** [database connections] and [prepared statements].  But other mutexes
1616** are enabled so that SQLite will be safe to use in a multi-threaded
1617** environment as long as no two threads attempt to use the same
1618** [database connection] at the same time.  ^If SQLite is compiled with
1619** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1620** it is not possible to set the Multi-thread [threading mode] and
1621** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1622** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1623**
1624** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1625** <dd>There are no arguments to this option.  ^This option sets the
1626** [threading mode] to Serialized. In other words, this option enables
1627** all mutexes including the recursive
1628** mutexes on [database connection] and [prepared statement] objects.
1629** In this mode (which is the default when SQLite is compiled with
1630** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1631** to [database connections] and [prepared statements] so that the
1632** application is free to use the same [database connection] or the
1633** same [prepared statement] in different threads at the same time.
1634** ^If SQLite is compiled with
1635** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1636** it is not possible to set the Serialized [threading mode] and
1637** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1638** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1639**
1640** <dt>SQLITE_CONFIG_MALLOC</dt>
1641** <dd> ^(This option takes a single argument which is a pointer to an
1642** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1643** alternative low-level memory allocation routines to be used in place of
1644** the memory allocation routines built into SQLite.)^ ^SQLite makes
1645** its own private copy of the content of the [sqlite3_mem_methods] structure
1646** before the [sqlite3_config()] call returns.</dd>
1647**
1648** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1649** <dd> ^(This option takes a single argument which is a pointer to an
1650** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1651** structure is filled with the currently defined memory allocation routines.)^
1652** This option can be used to overload the default memory allocation
1653** routines with a wrapper that simulations memory allocation failure or
1654** tracks memory usage, for example. </dd>
1655**
1656** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1657** <dd> ^This option takes single argument of type int, interpreted as a
1658** boolean, which enables or disables the collection of memory allocation
1659** statistics. ^(When memory allocation statistics are disabled, the
1660** following SQLite interfaces become non-operational:
1661**   <ul>
1662**   <li> [sqlite3_memory_used()]
1663**   <li> [sqlite3_memory_highwater()]
1664**   <li> [sqlite3_soft_heap_limit()]
1665**   <li> [sqlite3_status()]
1666**   </ul>)^
1667** ^Memory allocation statistics are enabled by default unless SQLite is
1668** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1669** allocation statistics are disabled by default.
1670** </dd>
1671**
1672** <dt>SQLITE_CONFIG_SCRATCH</dt>
1673** <dd> ^This option specifies a static memory buffer that SQLite can use for
1674** scratch memory.  There are three arguments:  A pointer an 8-byte
1675** aligned memory buffer from which the scrach allocations will be
1676** drawn, the size of each scratch allocation (sz),
1677** and the maximum number of scratch allocations (N).  The sz
1678** argument must be a multiple of 16. The sz parameter should be a few bytes
1679** larger than the actual scratch space required due to internal overhead.
1680** The first argument must be a pointer to an 8-byte aligned buffer
1681** of at least sz*N bytes of memory.
1682** ^SQLite will use no more than one scratch buffer per thread.  So
1683** N should be set to the expected maximum number of threads.  ^SQLite will
1684** never require a scratch buffer that is more than 6 times the database
1685** page size. ^If SQLite needs needs additional scratch memory beyond
1686** what is provided by this configuration option, then
1687** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1688**
1689** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1690** <dd> ^This option specifies a static memory buffer that SQLite can use for
1691** the database page cache with the default page cache implemenation.
1692** This configuration should not be used if an application-define page
1693** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1694** There are three arguments to this option: A pointer to 8-byte aligned
1695** memory, the size of each page buffer (sz), and the number of pages (N).
1696** The sz argument should be the size of the largest database page
1697** (a power of two between 512 and 32768) plus a little extra for each
1698** page header.  ^The page header size is 20 to 40 bytes depending on
1699** the host architecture.  ^It is harmless, apart from the wasted memory,
1700** to make sz a little too large.  The first
1701** argument should point to an allocation of at least sz*N bytes of memory.
1702** ^SQLite will use the memory provided by the first argument to satisfy its
1703** memory needs for the first N pages that it adds to cache.  ^If additional
1704** page cache memory is needed beyond what is provided by this option, then
1705** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1706** ^The implementation might use one or more of the N buffers to hold
1707** memory accounting information. The pointer in the first argument must
1708** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1709** will be undefined.</dd>
1710**
1711** <dt>SQLITE_CONFIG_HEAP</dt>
1712** <dd> ^This option specifies a static memory buffer that SQLite will use
1713** for all of its dynamic memory allocation needs beyond those provided
1714** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1715** There are three arguments: An 8-byte aligned pointer to the memory,
1716** the number of bytes in the memory buffer, and the minimum allocation size.
1717** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1718** to using its default memory allocator (the system malloc() implementation),
1719** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1720** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1721** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1722** allocator is engaged to handle all of SQLites memory allocation needs.
1723** The first pointer (the memory pointer) must be aligned to an 8-byte
1724** boundary or subsequent behavior of SQLite will be undefined.</dd>
1725**
1726** <dt>SQLITE_CONFIG_MUTEX</dt>
1727** <dd> ^(This option takes a single argument which is a pointer to an
1728** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1729** alternative low-level mutex routines to be used in place
1730** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1731** content of the [sqlite3_mutex_methods] structure before the call to
1732** [sqlite3_config()] returns. ^If SQLite is compiled with
1733** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1734** the entire mutexing subsystem is omitted from the build and hence calls to
1735** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1736** return [SQLITE_ERROR].</dd>
1737**
1738** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1739** <dd> ^(This option takes a single argument which is a pointer to an
1740** instance of the [sqlite3_mutex_methods] structure.  The
1741** [sqlite3_mutex_methods]
1742** structure is filled with the currently defined mutex routines.)^
1743** This option can be used to overload the default mutex allocation
1744** routines with a wrapper used to track mutex usage for performance
1745** profiling or testing, for example.   ^If SQLite is compiled with
1746** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1747** the entire mutexing subsystem is omitted from the build and hence calls to
1748** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1749** return [SQLITE_ERROR].</dd>
1750**
1751** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1752** <dd> ^(This option takes two arguments that determine the default
1753** memory allocation for the lookaside memory allocator on each
1754** [database connection].  The first argument is the
1755** size of each lookaside buffer slot and the second is the number of
1756** slots allocated to each database connection.)^  ^(This option sets the
1757** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1758** verb to [sqlite3_db_config()] can be used to change the lookaside
1759** configuration on individual connections.)^ </dd>
1760**
1761** <dt>SQLITE_CONFIG_PCACHE</dt>
1762** <dd> ^(This option takes a single argument which is a pointer to
1763** an [sqlite3_pcache_methods] object.  This object specifies the interface
1764** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1765** object and uses it for page cache memory allocations.</dd>
1766**
1767** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1768** <dd> ^(This option takes a single argument which is a pointer to an
1769** [sqlite3_pcache_methods] object.  SQLite copies of the current
1770** page cache implementation into that object.)^ </dd>
1771**
1772** </dl>
1773*/
1774#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1775#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1776#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1777#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1778#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1779#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1780#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1781#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1782#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1783#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1784#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1785/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
1786#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1787#define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1788#define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1789
1790/*
1791** CAPI3REF: Configuration Options
1792** EXPERIMENTAL
1793**
1794** These constants are the available integer configuration options that
1795** can be passed as the second argument to the [sqlite3_db_config()] interface.
1796**
1797** New configuration options may be added in future releases of SQLite.
1798** Existing configuration options might be discontinued.  Applications
1799** should check the return code from [sqlite3_db_config()] to make sure that
1800** the call worked.  ^The [sqlite3_db_config()] interface will return a
1801** non-zero [error code] if a discontinued or unsupported configuration option
1802** is invoked.
1803**
1804** <dl>
1805** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1806** <dd> ^This option takes three additional arguments that determine the
1807** [lookaside memory allocator] configuration for the [database connection].
1808** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1809** pointer to an memory buffer to use for lookaside memory.
1810** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1811** may be NULL in which case SQLite will allocate the
1812** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1813** size of each lookaside buffer slot.  ^The third argument is the number of
1814** slots.  The size of the buffer in the first argument must be greater than
1815** or equal to the product of the second and third arguments.  The buffer
1816** must be aligned to an 8-byte boundary.  ^If the second argument to
1817** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1818** rounded down to the next smaller
1819** multiple of 8.  See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
1820**
1821** </dl>
1822*/
1823#define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1824
1825
1826/*
1827** CAPI3REF: Enable Or Disable Extended Result Codes
1828**
1829** ^The sqlite3_extended_result_codes() routine enables or disables the
1830** [extended result codes] feature of SQLite. ^The extended result
1831** codes are disabled by default for historical compatibility.
1832*/
1833SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1834
1835/*
1836** CAPI3REF: Last Insert Rowid
1837**
1838** ^Each entry in an SQLite table has a unique 64-bit signed
1839** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1840** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1841** names are not also used by explicitly declared columns. ^If
1842** the table has a column of type [INTEGER PRIMARY KEY] then that column
1843** is another alias for the rowid.
1844**
1845** ^This routine returns the [rowid] of the most recent
1846** successful [INSERT] into the database from the [database connection]
1847** in the first argument.  ^If no successful [INSERT]s
1848** have ever occurred on that database connection, zero is returned.
1849**
1850** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
1851** row is returned by this routine as long as the trigger is running.
1852** But once the trigger terminates, the value returned by this routine
1853** reverts to the last value inserted before the trigger fired.)^
1854**
1855** ^An [INSERT] that fails due to a constraint violation is not a
1856** successful [INSERT] and does not change the value returned by this
1857** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1858** and INSERT OR ABORT make no changes to the return value of this
1859** routine when their insertion fails.  ^(When INSERT OR REPLACE
1860** encounters a constraint violation, it does not fail.  The
1861** INSERT continues to completion after deleting rows that caused
1862** the constraint problem so INSERT OR REPLACE will always change
1863** the return value of this interface.)^
1864**
1865** ^For the purposes of this routine, an [INSERT] is considered to
1866** be successful even if it is subsequently rolled back.
1867**
1868** This function is accessible to SQL statements via the
1869** [last_insert_rowid() SQL function].
1870**
1871** If a separate thread performs a new [INSERT] on the same
1872** database connection while the [sqlite3_last_insert_rowid()]
1873** function is running and thus changes the last insert [rowid],
1874** then the value returned by [sqlite3_last_insert_rowid()] is
1875** unpredictable and might not equal either the old or the new
1876** last insert [rowid].
1877*/
1878SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1879
1880/*
1881** CAPI3REF: Count The Number Of Rows Modified
1882**
1883** ^This function returns the number of database rows that were changed
1884** or inserted or deleted by the most recently completed SQL statement
1885** on the [database connection] specified by the first parameter.
1886** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
1887** or [DELETE] statement are counted.  Auxiliary changes caused by
1888** triggers or [foreign key actions] are not counted.)^ Use the
1889** [sqlite3_total_changes()] function to find the total number of changes
1890** including changes caused by triggers and foreign key actions.
1891**
1892** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
1893** are not counted.  Only real table changes are counted.
1894**
1895** ^(A "row change" is a change to a single row of a single table
1896** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
1897** are changed as side effects of [REPLACE] constraint resolution,
1898** rollback, ABORT processing, [DROP TABLE], or by any other
1899** mechanisms do not count as direct row changes.)^
1900**
1901** A "trigger context" is a scope of execution that begins and
1902** ends with the script of a [CREATE TRIGGER | trigger].
1903** Most SQL statements are
1904** evaluated outside of any trigger.  This is the "top level"
1905** trigger context.  If a trigger fires from the top level, a
1906** new trigger context is entered for the duration of that one
1907** trigger.  Subtriggers create subcontexts for their duration.
1908**
1909** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
1910** not create a new trigger context.
1911**
1912** ^This function returns the number of direct row changes in the
1913** most recent INSERT, UPDATE, or DELETE statement within the same
1914** trigger context.
1915**
1916** ^Thus, when called from the top level, this function returns the
1917** number of changes in the most recent INSERT, UPDATE, or DELETE
1918** that also occurred at the top level.  ^(Within the body of a trigger,
1919** the sqlite3_changes() interface can be called to find the number of
1920** changes in the most recently completed INSERT, UPDATE, or DELETE
1921** statement within the body of the same trigger.
1922** However, the number returned does not include changes
1923** caused by subtriggers since those have their own context.)^
1924**
1925** See also the [sqlite3_total_changes()] interface, the
1926** [count_changes pragma], and the [changes() SQL function].
1927**
1928** If a separate thread makes changes on the same database connection
1929** while [sqlite3_changes()] is running then the value returned
1930** is unpredictable and not meaningful.
1931*/
1932SQLITE_API int sqlite3_changes(sqlite3*);
1933
1934/*
1935** CAPI3REF: Total Number Of Rows Modified
1936**
1937** ^This function returns the number of row changes caused by [INSERT],
1938** [UPDATE] or [DELETE] statements since the [database connection] was opened.
1939** ^(The count returned by sqlite3_total_changes() includes all changes
1940** from all [CREATE TRIGGER | trigger] contexts and changes made by
1941** [foreign key actions]. However,
1942** the count does not include changes used to implement [REPLACE] constraints,
1943** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
1944** count does not include rows of views that fire an [INSTEAD OF trigger],
1945** though if the INSTEAD OF trigger makes changes of its own, those changes
1946** are counted.)^
1947** ^The sqlite3_total_changes() function counts the changes as soon as
1948** the statement that makes them is completed (when the statement handle
1949** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
1950**
1951** See also the [sqlite3_changes()] interface, the
1952** [count_changes pragma], and the [total_changes() SQL function].
1953**
1954** If a separate thread makes changes on the same database connection
1955** while [sqlite3_total_changes()] is running then the value
1956** returned is unpredictable and not meaningful.
1957*/
1958SQLITE_API int sqlite3_total_changes(sqlite3*);
1959
1960/*
1961** CAPI3REF: Interrupt A Long-Running Query
1962**
1963** ^This function causes any pending database operation to abort and
1964** return at its earliest opportunity. This routine is typically
1965** called in response to a user action such as pressing "Cancel"
1966** or Ctrl-C where the user wants a long query operation to halt
1967** immediately.
1968**
1969** ^It is safe to call this routine from a thread different from the
1970** thread that is currently running the database operation.  But it
1971** is not safe to call this routine with a [database connection] that
1972** is closed or might close before sqlite3_interrupt() returns.
1973**
1974** ^If an SQL operation is very nearly finished at the time when
1975** sqlite3_interrupt() is called, then it might not have an opportunity
1976** to be interrupted and might continue to completion.
1977**
1978** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
1979** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
1980** that is inside an explicit transaction, then the entire transaction
1981** will be rolled back automatically.
1982**
1983** ^The sqlite3_interrupt(D) call is in effect until all currently running
1984** SQL statements on [database connection] D complete.  ^Any new SQL statements
1985** that are started after the sqlite3_interrupt() call and before the
1986** running statements reaches zero are interrupted as if they had been
1987** running prior to the sqlite3_interrupt() call.  ^New SQL statements
1988** that are started after the running statement count reaches zero are
1989** not effected by the sqlite3_interrupt().
1990** ^A call to sqlite3_interrupt(D) that occurs when there are no running
1991** SQL statements is a no-op and has no effect on SQL statements
1992** that are started after the sqlite3_interrupt() call returns.
1993**
1994** If the database connection closes while [sqlite3_interrupt()]
1995** is running then bad things will likely happen.
1996*/
1997SQLITE_API void sqlite3_interrupt(sqlite3*);
1998
1999/*
2000** CAPI3REF: Determine If An SQL Statement Is Complete
2001**
2002** These routines are useful during command-line input to determine if the
2003** currently entered text seems to form a complete SQL statement or
2004** if additional input is needed before sending the text into
2005** SQLite for parsing.  ^These routines return 1 if the input string
2006** appears to be a complete SQL statement.  ^A statement is judged to be
2007** complete if it ends with a semicolon token and is not a prefix of a
2008** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2009** string literals or quoted identifier names or comments are not
2010** independent tokens (they are part of the token in which they are
2011** embedded) and thus do not count as a statement terminator.  ^Whitespace
2012** and comments that follow the final semicolon are ignored.
2013**
2014** ^These routines return 0 if the statement is incomplete.  ^If a
2015** memory allocation fails, then SQLITE_NOMEM is returned.
2016**
2017** ^These routines do not parse the SQL statements thus
2018** will not detect syntactically incorrect SQL.
2019**
2020** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2021** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2022** automatically by sqlite3_complete16().  If that initialization fails,
2023** then the return value from sqlite3_complete16() will be non-zero
2024** regardless of whether or not the input SQL is complete.)^
2025**
2026** The input to [sqlite3_complete()] must be a zero-terminated
2027** UTF-8 string.
2028**
2029** The input to [sqlite3_complete16()] must be a zero-terminated
2030** UTF-16 string in native byte order.
2031*/
2032SQLITE_API int sqlite3_complete(const char *sql);
2033SQLITE_API int sqlite3_complete16(const void *sql);
2034
2035/*
2036** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2037**
2038** ^This routine sets a callback function that might be invoked whenever
2039** an attempt is made to open a database table that another thread
2040** or process has locked.
2041**
2042** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2043** is returned immediately upon encountering the lock.  ^If the busy callback
2044** is not NULL, then the callback might be invoked with two arguments.
2045**
2046** ^The first argument to the busy handler is a copy of the void* pointer which
2047** is the third argument to sqlite3_busy_handler().  ^The second argument to
2048** the busy handler callback is the number of times that the busy handler has
2049** been invoked for this locking event.  ^If the
2050** busy callback returns 0, then no additional attempts are made to
2051** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2052** ^If the callback returns non-zero, then another attempt
2053** is made to open the database for reading and the cycle repeats.
2054**
2055** The presence of a busy handler does not guarantee that it will be invoked
2056** when there is lock contention. ^If SQLite determines that invoking the busy
2057** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2058** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2059** Consider a scenario where one process is holding a read lock that
2060** it is trying to promote to a reserved lock and
2061** a second process is holding a reserved lock that it is trying
2062** to promote to an exclusive lock.  The first process cannot proceed
2063** because it is blocked by the second and the second process cannot
2064** proceed because it is blocked by the first.  If both processes
2065** invoke the busy handlers, neither will make any progress.  Therefore,
2066** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2067** will induce the first process to release its read lock and allow
2068** the second process to proceed.
2069**
2070** ^The default busy callback is NULL.
2071**
2072** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2073** when SQLite is in the middle of a large transaction where all the
2074** changes will not fit into the in-memory cache.  SQLite will
2075** already hold a RESERVED lock on the database file, but it needs
2076** to promote this lock to EXCLUSIVE so that it can spill cache
2077** pages into the database file without harm to concurrent
2078** readers.  ^If it is unable to promote the lock, then the in-memory
2079** cache will be left in an inconsistent state and so the error
2080** code is promoted from the relatively benign [SQLITE_BUSY] to
2081** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2082** forces an automatic rollback of the changes.  See the
2083** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2084** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2085** this is important.
2086**
2087** ^(There can only be a single busy handler defined for each
2088** [database connection].  Setting a new busy handler clears any
2089** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2090** will also set or clear the busy handler.
2091**
2092** The busy callback should not take any actions which modify the
2093** database connection that invoked the busy handler.  Any such actions
2094** result in undefined behavior.
2095**
2096** A busy handler must not close the database connection
2097** or [prepared statement] that invoked the busy handler.
2098*/
2099SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2100
2101/*
2102** CAPI3REF: Set A Busy Timeout
2103**
2104** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2105** for a specified amount of time when a table is locked.  ^The handler
2106** will sleep multiple times until at least "ms" milliseconds of sleeping
2107** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2108** the handler returns 0 which causes [sqlite3_step()] to return
2109** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2110**
2111** ^Calling this routine with an argument less than or equal to zero
2112** turns off all busy handlers.
2113**
2114** ^(There can only be a single busy handler for a particular
2115** [database connection] any any given moment.  If another busy handler
2116** was defined  (using [sqlite3_busy_handler()]) prior to calling
2117** this routine, that other busy handler is cleared.)^
2118*/
2119SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2120
2121/*
2122** CAPI3REF: Convenience Routines For Running Queries
2123**
2124** Definition: A <b>result table</b> is memory data structure created by the
2125** [sqlite3_get_table()] interface.  A result table records the
2126** complete query results from one or more queries.
2127**
2128** The table conceptually has a number of rows and columns.  But
2129** these numbers are not part of the result table itself.  These
2130** numbers are obtained separately.  Let N be the number of rows
2131** and M be the number of columns.
2132**
2133** A result table is an array of pointers to zero-terminated UTF-8 strings.
2134** There are (N+1)*M elements in the array.  The first M pointers point
2135** to zero-terminated strings that  contain the names of the columns.
2136** The remaining entries all point to query results.  NULL values result
2137** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2138** string representation as returned by [sqlite3_column_text()].
2139**
2140** A result table might consist of one or more memory allocations.
2141** It is not safe to pass a result table directly to [sqlite3_free()].
2142** A result table should be deallocated using [sqlite3_free_table()].
2143**
2144** As an example of the result table format, suppose a query result
2145** is as follows:
2146**
2147** <blockquote><pre>
2148**        Name        | Age
2149**        -----------------------
2150**        Alice       | 43
2151**        Bob         | 28
2152**        Cindy       | 21
2153** </pre></blockquote>
2154**
2155** There are two column (M==2) and three rows (N==3).  Thus the
2156** result table has 8 entries.  Suppose the result table is stored
2157** in an array names azResult.  Then azResult holds this content:
2158**
2159** <blockquote><pre>
2160**        azResult&#91;0] = "Name";
2161**        azResult&#91;1] = "Age";
2162**        azResult&#91;2] = "Alice";
2163**        azResult&#91;3] = "43";
2164**        azResult&#91;4] = "Bob";
2165**        azResult&#91;5] = "28";
2166**        azResult&#91;6] = "Cindy";
2167**        azResult&#91;7] = "21";
2168** </pre></blockquote>
2169**
2170** ^The sqlite3_get_table() function evaluates one or more
2171** semicolon-separated SQL statements in the zero-terminated UTF-8
2172** string of its 2nd parameter and returns a result table to the
2173** pointer given in its 3rd parameter.
2174**
2175** After the application has finished with the result from sqlite3_get_table(),
2176** it should pass the result table pointer to sqlite3_free_table() in order to
2177** release the memory that was malloced.  Because of the way the
2178** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2179** function must not try to call [sqlite3_free()] directly.  Only
2180** [sqlite3_free_table()] is able to release the memory properly and safely.
2181**
2182** ^(The sqlite3_get_table() interface is implemented as a wrapper around
2183** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2184** to any internal data structures of SQLite.  It uses only the public
2185** interface defined here.  As a consequence, errors that occur in the
2186** wrapper layer outside of the internal [sqlite3_exec()] call are not
2187** reflected in subsequent calls to [sqlite3_errcode()] or
2188** [sqlite3_errmsg()].)^
2189*/
2190SQLITE_API int sqlite3_get_table(
2191  sqlite3 *db,          /* An open database */
2192  const char *zSql,     /* SQL to be evaluated */
2193  char ***pazResult,    /* Results of the query */
2194  int *pnRow,           /* Number of result rows written here */
2195  int *pnColumn,        /* Number of result columns written here */
2196  char **pzErrmsg       /* Error msg written here */
2197);
2198SQLITE_API void sqlite3_free_table(char **result);
2199
2200/*
2201** CAPI3REF: Formatted String Printing Functions
2202**
2203** These routines are work-alikes of the "printf()" family of functions
2204** from the standard C library.
2205**
2206** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2207** results into memory obtained from [sqlite3_malloc()].
2208** The strings returned by these two routines should be
2209** released by [sqlite3_free()].  ^Both routines return a
2210** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2211** memory to hold the resulting string.
2212**
2213** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
2214** the standard C library.  The result is written into the
2215** buffer supplied as the second parameter whose size is given by
2216** the first parameter. Note that the order of the
2217** first two parameters is reversed from snprintf().)^  This is an
2218** historical accident that cannot be fixed without breaking
2219** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2220** returns a pointer to its buffer instead of the number of
2221** characters actually written into the buffer.)^  We admit that
2222** the number of characters written would be a more useful return
2223** value but we cannot change the implementation of sqlite3_snprintf()
2224** now without breaking compatibility.
2225**
2226** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2227** guarantees that the buffer is always zero-terminated.  ^The first
2228** parameter "n" is the total size of the buffer, including space for
2229** the zero terminator.  So the longest string that can be completely
2230** written will be n-1 characters.
2231**
2232** These routines all implement some additional formatting
2233** options that are useful for constructing SQL statements.
2234** All of the usual printf() formatting options apply.  In addition, there
2235** is are "%q", "%Q", and "%z" options.
2236**
2237** ^(The %q option works like %s in that it substitutes a null-terminated
2238** string from the argument list.  But %q also doubles every '\'' character.
2239** %q is designed for use inside a string literal.)^  By doubling each '\''
2240** character it escapes that character and allows it to be inserted into
2241** the string.
2242**
2243** For example, assume the string variable zText contains text as follows:
2244**
2245** <blockquote><pre>
2246**  char *zText = "It's a happy day!";
2247** </pre></blockquote>
2248**
2249** One can use this text in an SQL statement as follows:
2250**
2251** <blockquote><pre>
2252**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2253**  sqlite3_exec(db, zSQL, 0, 0, 0);
2254**  sqlite3_free(zSQL);
2255** </pre></blockquote>
2256**
2257** Because the %q format string is used, the '\'' character in zText
2258** is escaped and the SQL generated is as follows:
2259**
2260** <blockquote><pre>
2261**  INSERT INTO table1 VALUES('It''s a happy day!')
2262** </pre></blockquote>
2263**
2264** This is correct.  Had we used %s instead of %q, the generated SQL
2265** would have looked like this:
2266**
2267** <blockquote><pre>
2268**  INSERT INTO table1 VALUES('It's a happy day!');
2269** </pre></blockquote>
2270**
2271** This second example is an SQL syntax error.  As a general rule you should
2272** always use %q instead of %s when inserting text into a string literal.
2273**
2274** ^(The %Q option works like %q except it also adds single quotes around
2275** the outside of the total string.  Additionally, if the parameter in the
2276** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2277** single quotes).)^  So, for example, one could say:
2278**
2279** <blockquote><pre>
2280**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2281**  sqlite3_exec(db, zSQL, 0, 0, 0);
2282**  sqlite3_free(zSQL);
2283** </pre></blockquote>
2284**
2285** The code above will render a correct SQL statement in the zSQL
2286** variable even if the zText variable is a NULL pointer.
2287**
2288** ^(The "%z" formatting option works like "%s" but with the
2289** addition that after the string has been read and copied into
2290** the result, [sqlite3_free()] is called on the input string.)^
2291*/
2292SQLITE_API char *sqlite3_mprintf(const char*,...);
2293SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2294SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2295
2296/*
2297** CAPI3REF: Memory Allocation Subsystem
2298**
2299** The SQLite core uses these three routines for all of its own
2300** internal memory allocation needs. "Core" in the previous sentence
2301** does not include operating-system specific VFS implementation.  The
2302** Windows VFS uses native malloc() and free() for some operations.
2303**
2304** ^The sqlite3_malloc() routine returns a pointer to a block
2305** of memory at least N bytes in length, where N is the parameter.
2306** ^If sqlite3_malloc() is unable to obtain sufficient free
2307** memory, it returns a NULL pointer.  ^If the parameter N to
2308** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2309** a NULL pointer.
2310**
2311** ^Calling sqlite3_free() with a pointer previously returned
2312** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2313** that it might be reused.  ^The sqlite3_free() routine is
2314** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2315** to sqlite3_free() is harmless.  After being freed, memory
2316** should neither be read nor written.  Even reading previously freed
2317** memory might result in a segmentation fault or other severe error.
2318** Memory corruption, a segmentation fault, or other severe error
2319** might result if sqlite3_free() is called with a non-NULL pointer that
2320** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2321**
2322** ^(The sqlite3_realloc() interface attempts to resize a
2323** prior memory allocation to be at least N bytes, where N is the
2324** second parameter.  The memory allocation to be resized is the first
2325** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2326** is a NULL pointer then its behavior is identical to calling
2327** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2328** ^If the second parameter to sqlite3_realloc() is zero or
2329** negative then the behavior is exactly the same as calling
2330** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2331** ^sqlite3_realloc() returns a pointer to a memory allocation
2332** of at least N bytes in size or NULL if sufficient memory is unavailable.
2333** ^If M is the size of the prior allocation, then min(N,M) bytes
2334** of the prior allocation are copied into the beginning of buffer returned
2335** by sqlite3_realloc() and the prior allocation is freed.
2336** ^If sqlite3_realloc() returns NULL, then the prior allocation
2337** is not freed.
2338**
2339** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2340** is always aligned to at least an 8 byte boundary.
2341**
2342** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2343** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2344** implementation of these routines to be omitted.  That capability
2345** is no longer provided.  Only built-in memory allocators can be used.
2346**
2347** The Windows OS interface layer calls
2348** the system malloc() and free() directly when converting
2349** filenames between the UTF-8 encoding used by SQLite
2350** and whatever filename encoding is used by the particular Windows
2351** installation.  Memory allocation errors are detected, but
2352** they are reported back as [SQLITE_CANTOPEN] or
2353** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2354**
2355** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2356** must be either NULL or else pointers obtained from a prior
2357** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2358** not yet been released.
2359**
2360** The application must not read or write any part of
2361** a block of memory after it has been released using
2362** [sqlite3_free()] or [sqlite3_realloc()].
2363*/
2364SQLITE_API void *sqlite3_malloc(int);
2365SQLITE_API void *sqlite3_realloc(void*, int);
2366SQLITE_API void sqlite3_free(void*);
2367
2368/*
2369** CAPI3REF: Memory Allocator Statistics
2370**
2371** SQLite provides these two interfaces for reporting on the status
2372** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2373** routines, which form the built-in memory allocation subsystem.
2374**
2375** ^The [sqlite3_memory_used()] routine returns the number of bytes
2376** of memory currently outstanding (malloced but not freed).
2377** ^The [sqlite3_memory_highwater()] routine returns the maximum
2378** value of [sqlite3_memory_used()] since the high-water mark
2379** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2380** [sqlite3_memory_highwater()] include any overhead
2381** added by SQLite in its implementation of [sqlite3_malloc()],
2382** but not overhead added by the any underlying system library
2383** routines that [sqlite3_malloc()] may call.
2384**
2385** ^The memory high-water mark is reset to the current value of
2386** [sqlite3_memory_used()] if and only if the parameter to
2387** [sqlite3_memory_highwater()] is true.  ^The value returned
2388** by [sqlite3_memory_highwater(1)] is the high-water mark
2389** prior to the reset.
2390*/
2391SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2392SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2393
2394/*
2395** CAPI3REF: Pseudo-Random Number Generator
2396**
2397** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2398** select random [ROWID | ROWIDs] when inserting new records into a table that
2399** already uses the largest possible [ROWID].  The PRNG is also used for
2400** the build-in random() and randomblob() SQL functions.  This interface allows
2401** applications to access the same PRNG for other purposes.
2402**
2403** ^A call to this routine stores N bytes of randomness into buffer P.
2404**
2405** ^The first time this routine is invoked (either internally or by
2406** the application) the PRNG is seeded using randomness obtained
2407** from the xRandomness method of the default [sqlite3_vfs] object.
2408** ^On all subsequent invocations, the pseudo-randomness is generated
2409** internally and without recourse to the [sqlite3_vfs] xRandomness
2410** method.
2411*/
2412SQLITE_API void sqlite3_randomness(int N, void *P);
2413
2414/*
2415** CAPI3REF: Compile-Time Authorization Callbacks
2416**
2417** ^This routine registers a authorizer callback with a particular
2418** [database connection], supplied in the first argument.
2419** ^The authorizer callback is invoked as SQL statements are being compiled
2420** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2421** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2422** points during the compilation process, as logic is being created
2423** to perform various actions, the authorizer callback is invoked to
2424** see if those actions are allowed.  ^The authorizer callback should
2425** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2426** specific action but allow the SQL statement to continue to be
2427** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2428** rejected with an error.  ^If the authorizer callback returns
2429** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2430** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2431** the authorizer will fail with an error message.
2432**
2433** When the callback returns [SQLITE_OK], that means the operation
2434** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2435** [sqlite3_prepare_v2()] or equivalent call that triggered the
2436** authorizer will fail with an error message explaining that
2437** access is denied.
2438**
2439** ^The first parameter to the authorizer callback is a copy of the third
2440** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2441** to the callback is an integer [SQLITE_COPY | action code] that specifies
2442** the particular action to be authorized. ^The third through sixth parameters
2443** to the callback are zero-terminated strings that contain additional
2444** details about the action to be authorized.
2445**
2446** ^If the action code is [SQLITE_READ]
2447** and the callback returns [SQLITE_IGNORE] then the
2448** [prepared statement] statement is constructed to substitute
2449** a NULL value in place of the table column that would have
2450** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2451** return can be used to deny an untrusted user access to individual
2452** columns of a table.
2453** ^If the action code is [SQLITE_DELETE] and the callback returns
2454** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2455** [truncate optimization] is disabled and all rows are deleted individually.
2456**
2457** An authorizer is used when [sqlite3_prepare | preparing]
2458** SQL statements from an untrusted source, to ensure that the SQL statements
2459** do not try to access data they are not allowed to see, or that they do not
2460** try to execute malicious statements that damage the database.  For
2461** example, an application may allow a user to enter arbitrary
2462** SQL queries for evaluation by a database.  But the application does
2463** not want the user to be able to make arbitrary changes to the
2464** database.  An authorizer could then be put in place while the
2465** user-entered SQL is being [sqlite3_prepare | prepared] that
2466** disallows everything except [SELECT] statements.
2467**
2468** Applications that need to process SQL from untrusted sources
2469** might also consider lowering resource limits using [sqlite3_limit()]
2470** and limiting database size using the [max_page_count] [PRAGMA]
2471** in addition to using an authorizer.
2472**
2473** ^(Only a single authorizer can be in place on a database connection
2474** at a time.  Each call to sqlite3_set_authorizer overrides the
2475** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2476** The authorizer is disabled by default.
2477**
2478** The authorizer callback must not do anything that will modify
2479** the database connection that invoked the authorizer callback.
2480** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2481** database connections for the meaning of "modify" in this paragraph.
2482**
2483** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2484** statement might be re-prepared during [sqlite3_step()] due to a
2485** schema change.  Hence, the application should ensure that the
2486** correct authorizer callback remains in place during the [sqlite3_step()].
2487**
2488** ^Note that the authorizer callback is invoked only during
2489** [sqlite3_prepare()] or its variants.  Authorization is not
2490** performed during statement evaluation in [sqlite3_step()], unless
2491** as stated in the previous paragraph, sqlite3_step() invokes
2492** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2493*/
2494SQLITE_API int sqlite3_set_authorizer(
2495  sqlite3*,
2496  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2497  void *pUserData
2498);
2499
2500/*
2501** CAPI3REF: Authorizer Return Codes
2502**
2503** The [sqlite3_set_authorizer | authorizer callback function] must
2504** return either [SQLITE_OK] or one of these two constants in order
2505** to signal SQLite whether or not the action is permitted.  See the
2506** [sqlite3_set_authorizer | authorizer documentation] for additional
2507** information.
2508*/
2509#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2510#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2511
2512/*
2513** CAPI3REF: Authorizer Action Codes
2514**
2515** The [sqlite3_set_authorizer()] interface registers a callback function
2516** that is invoked to authorize certain SQL statement actions.  The
2517** second parameter to the callback is an integer code that specifies
2518** what action is being authorized.  These are the integer action codes that
2519** the authorizer callback may be passed.
2520**
2521** These action code values signify what kind of operation is to be
2522** authorized.  The 3rd and 4th parameters to the authorization
2523** callback function will be parameters or NULL depending on which of these
2524** codes is used as the second parameter.  ^(The 5th parameter to the
2525** authorizer callback is the name of the database ("main", "temp",
2526** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2527** is the name of the inner-most trigger or view that is responsible for
2528** the access attempt or NULL if this access attempt is directly from
2529** top-level SQL code.
2530*/
2531/******************************************* 3rd ************ 4th ***********/
2532#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2533#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2534#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2535#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2536#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2537#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2538#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2539#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2540#define SQLITE_DELETE                9   /* Table Name      NULL            */
2541#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2542#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2543#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2544#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2545#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2546#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2547#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2548#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2549#define SQLITE_INSERT               18   /* Table Name      NULL            */
2550#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2551#define SQLITE_READ                 20   /* Table Name      Column Name     */
2552#define SQLITE_SELECT               21   /* NULL            NULL            */
2553#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2554#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2555#define SQLITE_ATTACH               24   /* Filename        NULL            */
2556#define SQLITE_DETACH               25   /* Database Name   NULL            */
2557#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2558#define SQLITE_REINDEX              27   /* Index Name      NULL            */
2559#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2560#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2561#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2562#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2563#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2564#define SQLITE_COPY                  0   /* No longer used */
2565
2566/*
2567** CAPI3REF: Tracing And Profiling Functions
2568** EXPERIMENTAL
2569**
2570** These routines register callback functions that can be used for
2571** tracing and profiling the execution of SQL statements.
2572**
2573** ^The callback function registered by sqlite3_trace() is invoked at
2574** various times when an SQL statement is being run by [sqlite3_step()].
2575** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2576** SQL statement text as the statement first begins executing.
2577** ^(Additional sqlite3_trace() callbacks might occur
2578** as each triggered subprogram is entered.  The callbacks for triggers
2579** contain a UTF-8 SQL comment that identifies the trigger.)^
2580**
2581** ^The callback function registered by sqlite3_profile() is invoked
2582** as each SQL statement finishes.  ^The profile callback contains
2583** the original statement text and an estimate of wall-clock time
2584** of how long that statement took to run.
2585*/
2586SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2587SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2588   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2589
2590/*
2591** CAPI3REF: Query Progress Callbacks
2592**
2593** ^This routine configures a callback function - the
2594** progress callback - that is invoked periodically during long
2595** running calls to [sqlite3_exec()], [sqlite3_step()] and
2596** [sqlite3_get_table()].  An example use for this
2597** interface is to keep a GUI updated during a large query.
2598**
2599** ^If the progress callback returns non-zero, the operation is
2600** interrupted.  This feature can be used to implement a
2601** "Cancel" button on a GUI progress dialog box.
2602**
2603** The progress handler must not do anything that will modify
2604** the database connection that invoked the progress handler.
2605** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2606** database connections for the meaning of "modify" in this paragraph.
2607**
2608*/
2609SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2610
2611/*
2612** CAPI3REF: Opening A New Database Connection
2613**
2614** ^These routines open an SQLite database file whose name is given by the
2615** filename argument. ^The filename argument is interpreted as UTF-8 for
2616** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2617** order for sqlite3_open16(). ^(A [database connection] handle is usually
2618** returned in *ppDb, even if an error occurs.  The only exception is that
2619** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2620** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2621** object.)^ ^(If the database is opened (and/or created) successfully, then
2622** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2623** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2624** an English language description of the error following a failure of any
2625** of the sqlite3_open() routines.
2626**
2627** ^The default encoding for the database will be UTF-8 if
2628** sqlite3_open() or sqlite3_open_v2() is called and
2629** UTF-16 in the native byte order if sqlite3_open16() is used.
2630**
2631** Whether or not an error occurs when it is opened, resources
2632** associated with the [database connection] handle should be released by
2633** passing it to [sqlite3_close()] when it is no longer required.
2634**
2635** The sqlite3_open_v2() interface works like sqlite3_open()
2636** except that it accepts two additional parameters for additional control
2637** over the new database connection.  ^(The flags parameter to
2638** sqlite3_open_v2() can take one of
2639** the following three values, optionally combined with the
2640** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2641** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2642**
2643** <dl>
2644** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2645** <dd>The database is opened in read-only mode.  If the database does not
2646** already exist, an error is returned.</dd>)^
2647**
2648** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2649** <dd>The database is opened for reading and writing if possible, or reading
2650** only if the file is write protected by the operating system.  In either
2651** case the database must already exist, otherwise an error is returned.</dd>)^
2652**
2653** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2654** <dd>The database is opened for reading and writing, and is creates it if
2655** it does not already exist. This is the behavior that is always used for
2656** sqlite3_open() and sqlite3_open16().</dd>)^
2657** </dl>
2658**
2659** If the 3rd parameter to sqlite3_open_v2() is not one of the
2660** combinations shown above or one of the combinations shown above combined
2661** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2662** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
2663** then the behavior is undefined.
2664**
2665** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2666** opens in the multi-thread [threading mode] as long as the single-thread
2667** mode has not been set at compile-time or start-time.  ^If the
2668** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2669** in the serialized [threading mode] unless single-thread was
2670** previously selected at compile-time or start-time.
2671** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2672** eligible to use [shared cache mode], regardless of whether or not shared
2673** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2674** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2675** participate in [shared cache mode] even if it is enabled.
2676**
2677** ^If the filename is ":memory:", then a private, temporary in-memory database
2678** is created for the connection.  ^This in-memory database will vanish when
2679** the database connection is closed.  Future versions of SQLite might
2680** make use of additional special filenames that begin with the ":" character.
2681** It is recommended that when a database filename actually does begin with
2682** a ":" character you should prefix the filename with a pathname such as
2683** "./" to avoid ambiguity.
2684**
2685** ^If the filename is an empty string, then a private, temporary
2686** on-disk database will be created.  ^This private database will be
2687** automatically deleted as soon as the database connection is closed.
2688**
2689** ^The fourth parameter to sqlite3_open_v2() is the name of the
2690** [sqlite3_vfs] object that defines the operating system interface that
2691** the new database connection should use.  ^If the fourth parameter is
2692** a NULL pointer then the default [sqlite3_vfs] object is used.
2693**
2694** <b>Note to Windows users:</b>  The encoding used for the filename argument
2695** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2696** codepage is currently defined.  Filenames containing international
2697** characters must be converted to UTF-8 prior to passing them into
2698** sqlite3_open() or sqlite3_open_v2().
2699*/
2700SQLITE_API int sqlite3_open(
2701  const char *filename,   /* Database filename (UTF-8) */
2702  sqlite3 **ppDb          /* OUT: SQLite db handle */
2703);
2704SQLITE_API int sqlite3_open16(
2705  const void *filename,   /* Database filename (UTF-16) */
2706  sqlite3 **ppDb          /* OUT: SQLite db handle */
2707);
2708SQLITE_API int sqlite3_open_v2(
2709  const char *filename,   /* Database filename (UTF-8) */
2710  sqlite3 **ppDb,         /* OUT: SQLite db handle */
2711  int flags,              /* Flags */
2712  const char *zVfs        /* Name of VFS module to use */
2713);
2714
2715/*
2716** CAPI3REF: Error Codes And Messages
2717**
2718** ^The sqlite3_errcode() interface returns the numeric [result code] or
2719** [extended result code] for the most recent failed sqlite3_* API call
2720** associated with a [database connection]. If a prior API call failed
2721** but the most recent API call succeeded, the return value from
2722** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2723** interface is the same except that it always returns the
2724** [extended result code] even when extended result codes are
2725** disabled.
2726**
2727** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2728** text that describes the error, as either UTF-8 or UTF-16 respectively.
2729** ^(Memory to hold the error message string is managed internally.
2730** The application does not need to worry about freeing the result.
2731** However, the error string might be overwritten or deallocated by
2732** subsequent calls to other SQLite interface functions.)^
2733**
2734** When the serialized [threading mode] is in use, it might be the
2735** case that a second error occurs on a separate thread in between
2736** the time of the first error and the call to these interfaces.
2737** When that happens, the second error will be reported since these
2738** interfaces always report the most recent result.  To avoid
2739** this, each thread can obtain exclusive use of the [database connection] D
2740** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2741** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2742** all calls to the interfaces listed here are completed.
2743**
2744** If an interface fails with SQLITE_MISUSE, that means the interface
2745** was invoked incorrectly by the application.  In that case, the
2746** error code and message may or may not be set.
2747*/
2748SQLITE_API int sqlite3_errcode(sqlite3 *db);
2749SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
2750SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2751SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2752
2753/*
2754** CAPI3REF: SQL Statement Object
2755** KEYWORDS: {prepared statement} {prepared statements}
2756**
2757** An instance of this object represents a single SQL statement.
2758** This object is variously known as a "prepared statement" or a
2759** "compiled SQL statement" or simply as a "statement".
2760**
2761** The life of a statement object goes something like this:
2762**
2763** <ol>
2764** <li> Create the object using [sqlite3_prepare_v2()] or a related
2765**      function.
2766** <li> Bind values to [host parameters] using the sqlite3_bind_*()
2767**      interfaces.
2768** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2769** <li> Reset the statement using [sqlite3_reset()] then go back
2770**      to step 2.  Do this zero or more times.
2771** <li> Destroy the object using [sqlite3_finalize()].
2772** </ol>
2773**
2774** Refer to documentation on individual methods above for additional
2775** information.
2776*/
2777typedef struct sqlite3_stmt sqlite3_stmt;
2778
2779/*
2780** CAPI3REF: Run-time Limits
2781**
2782** ^(This interface allows the size of various constructs to be limited
2783** on a connection by connection basis.  The first parameter is the
2784** [database connection] whose limit is to be set or queried.  The
2785** second parameter is one of the [limit categories] that define a
2786** class of constructs to be size limited.  The third parameter is the
2787** new limit for that construct.  The function returns the old limit.)^
2788**
2789** ^If the new limit is a negative number, the limit is unchanged.
2790** ^(For the limit category of SQLITE_LIMIT_XYZ there is a
2791** [limits | hard upper bound]
2792** set by a compile-time C preprocessor macro named
2793** [limits | SQLITE_MAX_XYZ].
2794** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2795** ^Attempts to increase a limit above its hard upper bound are
2796** silently truncated to the hard upper bound.
2797**
2798** Run-time limits are intended for use in applications that manage
2799** both their own internal database and also databases that are controlled
2800** by untrusted external sources.  An example application might be a
2801** web browser that has its own databases for storing history and
2802** separate databases controlled by JavaScript applications downloaded
2803** off the Internet.  The internal databases can be given the
2804** large, default limits.  Databases managed by external sources can
2805** be given much smaller limits designed to prevent a denial of service
2806** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
2807** interface to further control untrusted SQL.  The size of the database
2808** created by an untrusted script can be contained using the
2809** [max_page_count] [PRAGMA].
2810**
2811** New run-time limit categories may be added in future releases.
2812*/
2813SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
2814
2815/*
2816** CAPI3REF: Run-Time Limit Categories
2817** KEYWORDS: {limit category} {*limit categories}
2818**
2819** These constants define various performance limits
2820** that can be lowered at run-time using [sqlite3_limit()].
2821** The synopsis of the meanings of the various limits is shown below.
2822** Additional information is available at [limits | Limits in SQLite].
2823**
2824** <dl>
2825** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2826** <dd>The maximum size of any string or BLOB or table row.<dd>)^
2827**
2828** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
2829** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
2830**
2831** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
2832** <dd>The maximum number of columns in a table definition or in the
2833** result set of a [SELECT] or the maximum number of columns in an index
2834** or in an ORDER BY or GROUP BY clause.</dd>)^
2835**
2836** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
2837** <dd>The maximum depth of the parse tree on any expression.</dd>)^
2838**
2839** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
2840** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
2841**
2842** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
2843** <dd>The maximum number of instructions in a virtual machine program
2844** used to implement an SQL statement.</dd>)^
2845**
2846** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
2847** <dd>The maximum number of arguments on a function.</dd>)^
2848**
2849** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
2850** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
2851**
2852** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
2853** <dd>The maximum length of the pattern argument to the [LIKE] or
2854** [GLOB] operators.</dd>)^
2855**
2856** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
2857** <dd>The maximum number of variables in an SQL statement that can
2858** be bound.</dd>)^
2859**
2860** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
2861** <dd>The maximum depth of recursion for triggers.</dd>)^
2862** </dl>
2863*/
2864#define SQLITE_LIMIT_LENGTH                    0
2865#define SQLITE_LIMIT_SQL_LENGTH                1
2866#define SQLITE_LIMIT_COLUMN                    2
2867#define SQLITE_LIMIT_EXPR_DEPTH                3
2868#define SQLITE_LIMIT_COMPOUND_SELECT           4
2869#define SQLITE_LIMIT_VDBE_OP                   5
2870#define SQLITE_LIMIT_FUNCTION_ARG              6
2871#define SQLITE_LIMIT_ATTACHED                  7
2872#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
2873#define SQLITE_LIMIT_VARIABLE_NUMBER           9
2874#define SQLITE_LIMIT_TRIGGER_DEPTH            10
2875
2876/*
2877** CAPI3REF: Compiling An SQL Statement
2878** KEYWORDS: {SQL statement compiler}
2879**
2880** To execute an SQL query, it must first be compiled into a byte-code
2881** program using one of these routines.
2882**
2883** The first argument, "db", is a [database connection] obtained from a
2884** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
2885** [sqlite3_open16()].  The database connection must not have been closed.
2886**
2887** The second argument, "zSql", is the statement to be compiled, encoded
2888** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
2889** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
2890** use UTF-16.
2891**
2892** ^If the nByte argument is less than zero, then zSql is read up to the
2893** first zero terminator. ^If nByte is non-negative, then it is the maximum
2894** number of  bytes read from zSql.  ^When nByte is non-negative, the
2895** zSql string ends at either the first '\000' or '\u0000' character or
2896** the nByte-th byte, whichever comes first. If the caller knows
2897** that the supplied string is nul-terminated, then there is a small
2898** performance advantage to be gained by passing an nByte parameter that
2899** is equal to the number of bytes in the input string <i>including</i>
2900** the nul-terminator bytes.
2901**
2902** ^If pzTail is not NULL then *pzTail is made to point to the first byte
2903** past the end of the first SQL statement in zSql.  These routines only
2904** compile the first statement in zSql, so *pzTail is left pointing to
2905** what remains uncompiled.
2906**
2907** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
2908** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
2909** to NULL.  ^If the input text contains no SQL (if the input is an empty
2910** string or a comment) then *ppStmt is set to NULL.
2911** The calling procedure is responsible for deleting the compiled
2912** SQL statement using [sqlite3_finalize()] after it has finished with it.
2913** ppStmt may not be NULL.
2914**
2915** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
2916** otherwise an [error code] is returned.
2917**
2918** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
2919** recommended for all new programs. The two older interfaces are retained
2920** for backwards compatibility, but their use is discouraged.
2921** ^In the "v2" interfaces, the prepared statement
2922** that is returned (the [sqlite3_stmt] object) contains a copy of the
2923** original SQL text. This causes the [sqlite3_step()] interface to
2924** behave differently in three ways:
2925**
2926** <ol>
2927** <li>
2928** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
2929** always used to do, [sqlite3_step()] will automatically recompile the SQL
2930** statement and try to run it again.  ^If the schema has changed in
2931** a way that makes the statement no longer valid, [sqlite3_step()] will still
2932** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
2933** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
2934** error go away.  Note: use [sqlite3_errmsg()] to find the text
2935** of the parsing error that results in an [SQLITE_SCHEMA] return.
2936** </li>
2937**
2938** <li>
2939** ^When an error occurs, [sqlite3_step()] will return one of the detailed
2940** [error codes] or [extended error codes].  ^The legacy behavior was that
2941** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
2942** and the application would have to make a second call to [sqlite3_reset()]
2943** in order to find the underlying cause of the problem. With the "v2" prepare
2944** interfaces, the underlying reason for the error is returned immediately.
2945** </li>
2946**
2947** <li>
2948** ^If the value of a [parameter | host parameter] in the WHERE clause might
2949** change the query plan for a statement, then the statement may be
2950** automatically recompiled (as if there had been a schema change) on the first
2951** [sqlite3_step()] call following any change to the
2952** [sqlite3_bind_text | bindings] of the [parameter].
2953** </li>
2954** </ol>
2955*/
2956SQLITE_API int sqlite3_prepare(
2957  sqlite3 *db,            /* Database handle */
2958  const char *zSql,       /* SQL statement, UTF-8 encoded */
2959  int nByte,              /* Maximum length of zSql in bytes. */
2960  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2961  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2962);
2963SQLITE_API int sqlite3_prepare_v2(
2964  sqlite3 *db,            /* Database handle */
2965  const char *zSql,       /* SQL statement, UTF-8 encoded */
2966  int nByte,              /* Maximum length of zSql in bytes. */
2967  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2968  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2969);
2970SQLITE_API int sqlite3_prepare16(
2971  sqlite3 *db,            /* Database handle */
2972  const void *zSql,       /* SQL statement, UTF-16 encoded */
2973  int nByte,              /* Maximum length of zSql in bytes. */
2974  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2975  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2976);
2977SQLITE_API int sqlite3_prepare16_v2(
2978  sqlite3 *db,            /* Database handle */
2979  const void *zSql,       /* SQL statement, UTF-16 encoded */
2980  int nByte,              /* Maximum length of zSql in bytes. */
2981  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2982  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2983);
2984
2985/*
2986** CAPI3REF: Retrieving Statement SQL
2987**
2988** ^This interface can be used to retrieve a saved copy of the original
2989** SQL text used to create a [prepared statement] if that statement was
2990** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
2991*/
2992SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
2993
2994/*
2995** CAPI3REF: Dynamically Typed Value Object
2996** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
2997**
2998** SQLite uses the sqlite3_value object to represent all values
2999** that can be stored in a database table. SQLite uses dynamic typing
3000** for the values it stores.  ^Values stored in sqlite3_value objects
3001** can be integers, floating point values, strings, BLOBs, or NULL.
3002**
3003** An sqlite3_value object may be either "protected" or "unprotected".
3004** Some interfaces require a protected sqlite3_value.  Other interfaces
3005** will accept either a protected or an unprotected sqlite3_value.
3006** Every interface that accepts sqlite3_value arguments specifies
3007** whether or not it requires a protected sqlite3_value.
3008**
3009** The terms "protected" and "unprotected" refer to whether or not
3010** a mutex is held.  A internal mutex is held for a protected
3011** sqlite3_value object but no mutex is held for an unprotected
3012** sqlite3_value object.  If SQLite is compiled to be single-threaded
3013** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3014** or if SQLite is run in one of reduced mutex modes
3015** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3016** then there is no distinction between protected and unprotected
3017** sqlite3_value objects and they can be used interchangeably.  However,
3018** for maximum code portability it is recommended that applications
3019** still make the distinction between between protected and unprotected
3020** sqlite3_value objects even when not strictly required.
3021**
3022** ^The sqlite3_value objects that are passed as parameters into the
3023** implementation of [application-defined SQL functions] are protected.
3024** ^The sqlite3_value object returned by
3025** [sqlite3_column_value()] is unprotected.
3026** Unprotected sqlite3_value objects may only be used with
3027** [sqlite3_result_value()] and [sqlite3_bind_value()].
3028** The [sqlite3_value_blob | sqlite3_value_type()] family of
3029** interfaces require protected sqlite3_value objects.
3030*/
3031typedef struct Mem sqlite3_value;
3032
3033/*
3034** CAPI3REF: SQL Function Context Object
3035**
3036** The context in which an SQL function executes is stored in an
3037** sqlite3_context object.  ^A pointer to an sqlite3_context object
3038** is always first parameter to [application-defined SQL functions].
3039** The application-defined SQL function implementation will pass this
3040** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3041** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3042** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3043** and/or [sqlite3_set_auxdata()].
3044*/
3045typedef struct sqlite3_context sqlite3_context;
3046
3047/*
3048** CAPI3REF: Binding Values To Prepared Statements
3049** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3050** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3051**
3052** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3053** literals may be replaced by a [parameter] that matches one of following
3054** templates:
3055**
3056** <ul>
3057** <li>  ?
3058** <li>  ?NNN
3059** <li>  :VVV
3060** <li>  @VVV
3061** <li>  $VVV
3062** </ul>
3063**
3064** In the templates above, NNN represents an integer literal,
3065** and VVV represents an alphanumeric identifer.)^  ^The values of these
3066** parameters (also called "host parameter names" or "SQL parameters")
3067** can be set using the sqlite3_bind_*() routines defined here.
3068**
3069** ^The first argument to the sqlite3_bind_*() routines is always
3070** a pointer to the [sqlite3_stmt] object returned from
3071** [sqlite3_prepare_v2()] or its variants.
3072**
3073** ^The second argument is the index of the SQL parameter to be set.
3074** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3075** SQL parameter is used more than once, second and subsequent
3076** occurrences have the same index as the first occurrence.
3077** ^The index for named parameters can be looked up using the
3078** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3079** for "?NNN" parameters is the value of NNN.
3080** ^The NNN value must be between 1 and the [sqlite3_limit()]
3081** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3082**
3083** ^The third argument is the value to bind to the parameter.
3084**
3085** ^(In those routines that have a fourth argument, its value is the
3086** number of bytes in the parameter.  To be clear: the value is the
3087** number of <u>bytes</u> in the value, not the number of characters.)^
3088** ^If the fourth parameter is negative, the length of the string is
3089** the number of bytes up to the first zero terminator.
3090**
3091** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3092** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3093** string after SQLite has finished with it. ^If the fifth argument is
3094** the special value [SQLITE_STATIC], then SQLite assumes that the
3095** information is in static, unmanaged space and does not need to be freed.
3096** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3097** SQLite makes its own private copy of the data immediately, before
3098** the sqlite3_bind_*() routine returns.
3099**
3100** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3101** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3102** (just an integer to hold its size) while it is being processed.
3103** Zeroblobs are intended to serve as placeholders for BLOBs whose
3104** content is later written using
3105** [sqlite3_blob_open | incremental BLOB I/O] routines.
3106** ^A negative value for the zeroblob results in a zero-length BLOB.
3107**
3108** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3109** for the [prepared statement] or with a prepared statement for which
3110** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3111** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3112** routine is passed a [prepared statement] that has been finalized, the
3113** result is undefined and probably harmful.
3114**
3115** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3116** ^Unbound parameters are interpreted as NULL.
3117**
3118** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3119** [error code] if anything goes wrong.
3120** ^[SQLITE_RANGE] is returned if the parameter
3121** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3122**
3123** See also: [sqlite3_bind_parameter_count()],
3124** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3125*/
3126SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3127SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3128SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3129SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3130SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3131SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3132SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3133SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3134SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3135
3136/*
3137** CAPI3REF: Number Of SQL Parameters
3138**
3139** ^This routine can be used to find the number of [SQL parameters]
3140** in a [prepared statement].  SQL parameters are tokens of the
3141** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3142** placeholders for values that are [sqlite3_bind_blob | bound]
3143** to the parameters at a later time.
3144**
3145** ^(This routine actually returns the index of the largest (rightmost)
3146** parameter. For all forms except ?NNN, this will correspond to the
3147** number of unique parameters.  If parameters of the ?NNN form are used,
3148** there may be gaps in the list.)^
3149**
3150** See also: [sqlite3_bind_blob|sqlite3_bind()],
3151** [sqlite3_bind_parameter_name()], and
3152** [sqlite3_bind_parameter_index()].
3153*/
3154SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3155
3156/*
3157** CAPI3REF: Name Of A Host Parameter
3158**
3159** ^The sqlite3_bind_parameter_name(P,N) interface returns
3160** the name of the N-th [SQL parameter] in the [prepared statement] P.
3161** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3162** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3163** respectively.
3164** In other words, the initial ":" or "$" or "@" or "?"
3165** is included as part of the name.)^
3166** ^Parameters of the form "?" without a following integer have no name
3167** and are referred to as "nameless" or "anonymous parameters".
3168**
3169** ^The first host parameter has an index of 1, not 0.
3170**
3171** ^If the value N is out of range or if the N-th parameter is
3172** nameless, then NULL is returned.  ^The returned string is
3173** always in UTF-8 encoding even if the named parameter was
3174** originally specified as UTF-16 in [sqlite3_prepare16()] or
3175** [sqlite3_prepare16_v2()].
3176**
3177** See also: [sqlite3_bind_blob|sqlite3_bind()],
3178** [sqlite3_bind_parameter_count()], and
3179** [sqlite3_bind_parameter_index()].
3180*/
3181SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3182
3183/*
3184** CAPI3REF: Index Of A Parameter With A Given Name
3185**
3186** ^Return the index of an SQL parameter given its name.  ^The
3187** index value returned is suitable for use as the second
3188** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3189** is returned if no matching parameter is found.  ^The parameter
3190** name must be given in UTF-8 even if the original statement
3191** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3192**
3193** See also: [sqlite3_bind_blob|sqlite3_bind()],
3194** [sqlite3_bind_parameter_count()], and
3195** [sqlite3_bind_parameter_index()].
3196*/
3197SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3198
3199/*
3200** CAPI3REF: Reset All Bindings On A Prepared Statement
3201**
3202** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3203** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3204** ^Use this routine to reset all host parameters to NULL.
3205*/
3206SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3207
3208/*
3209** CAPI3REF: Number Of Columns In A Result Set
3210**
3211** ^Return the number of columns in the result set returned by the
3212** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3213** statement that does not return data (for example an [UPDATE]).
3214*/
3215SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3216
3217/*
3218** CAPI3REF: Column Names In A Result Set
3219**
3220** ^These routines return the name assigned to a particular column
3221** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3222** interface returns a pointer to a zero-terminated UTF-8 string
3223** and sqlite3_column_name16() returns a pointer to a zero-terminated
3224** UTF-16 string.  ^The first parameter is the [prepared statement]
3225** that implements the [SELECT] statement. ^The second parameter is the
3226** column number.  ^The leftmost column is number 0.
3227**
3228** ^The returned string pointer is valid until either the [prepared statement]
3229** is destroyed by [sqlite3_finalize()] or until the next call to
3230** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3231**
3232** ^If sqlite3_malloc() fails during the processing of either routine
3233** (for example during a conversion from UTF-8 to UTF-16) then a
3234** NULL pointer is returned.
3235**
3236** ^The name of a result column is the value of the "AS" clause for
3237** that column, if there is an AS clause.  If there is no AS clause
3238** then the name of the column is unspecified and may change from
3239** one release of SQLite to the next.
3240*/
3241SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3242SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3243
3244/*
3245** CAPI3REF: Source Of Data In A Query Result
3246**
3247** ^These routines provide a means to determine the database, table, and
3248** table column that is the origin of a particular result column in
3249** [SELECT] statement.
3250** ^The name of the database or table or column can be returned as
3251** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3252** the database name, the _table_ routines return the table name, and
3253** the origin_ routines return the column name.
3254** ^The returned string is valid until the [prepared statement] is destroyed
3255** using [sqlite3_finalize()] or until the same information is requested
3256** again in a different encoding.
3257**
3258** ^The names returned are the original un-aliased names of the
3259** database, table, and column.
3260**
3261** ^The first argument to these interfaces is a [prepared statement].
3262** ^These functions return information about the Nth result column returned by
3263** the statement, where N is the second function argument.
3264** ^The left-most column is column 0 for these routines.
3265**
3266** ^If the Nth column returned by the statement is an expression or
3267** subquery and is not a column value, then all of these functions return
3268** NULL.  ^These routine might also return NULL if a memory allocation error
3269** occurs.  ^Otherwise, they return the name of the attached database, table,
3270** or column that query result column was extracted from.
3271**
3272** ^As with all other SQLite APIs, those whose names end with "16" return
3273** UTF-16 encoded strings and the other functions return UTF-8.
3274**
3275** ^These APIs are only available if the library was compiled with the
3276** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3277**
3278** If two or more threads call one or more of these routines against the same
3279** prepared statement and column at the same time then the results are
3280** undefined.
3281**
3282** If two or more threads call one or more
3283** [sqlite3_column_database_name | column metadata interfaces]
3284** for the same [prepared statement] and result column
3285** at the same time then the results are undefined.
3286*/
3287SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3288SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3289SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3290SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3291SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3292SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3293
3294/*
3295** CAPI3REF: Declared Datatype Of A Query Result
3296**
3297** ^(The first parameter is a [prepared statement].
3298** If this statement is a [SELECT] statement and the Nth column of the
3299** returned result set of that [SELECT] is a table column (not an
3300** expression or subquery) then the declared type of the table
3301** column is returned.)^  ^If the Nth column of the result set is an
3302** expression or subquery, then a NULL pointer is returned.
3303** ^The returned string is always UTF-8 encoded.
3304**
3305** ^(For example, given the database schema:
3306**
3307** CREATE TABLE t1(c1 VARIANT);
3308**
3309** and the following statement to be compiled:
3310**
3311** SELECT c1 + 1, c1 FROM t1;
3312**
3313** this routine would return the string "VARIANT" for the second result
3314** column (i==1), and a NULL pointer for the first result column (i==0).)^
3315**
3316** ^SQLite uses dynamic run-time typing.  ^So just because a column
3317** is declared to contain a particular type does not mean that the
3318** data stored in that column is of the declared type.  SQLite is
3319** strongly typed, but the typing is dynamic not static.  ^Type
3320** is associated with individual values, not with the containers
3321** used to hold those values.
3322*/
3323SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3324SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3325
3326/*
3327** CAPI3REF: Evaluate An SQL Statement
3328**
3329** After a [prepared statement] has been prepared using either
3330** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3331** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3332** must be called one or more times to evaluate the statement.
3333**
3334** The details of the behavior of the sqlite3_step() interface depend
3335** on whether the statement was prepared using the newer "v2" interface
3336** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3337** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3338** new "v2" interface is recommended for new applications but the legacy
3339** interface will continue to be supported.
3340**
3341** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3342** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3343** ^With the "v2" interface, any of the other [result codes] or
3344** [extended result codes] might be returned as well.
3345**
3346** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3347** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3348** or occurs outside of an explicit transaction, then you can retry the
3349** statement.  If the statement is not a [COMMIT] and occurs within a
3350** explicit transaction then you should rollback the transaction before
3351** continuing.
3352**
3353** ^[SQLITE_DONE] means that the statement has finished executing
3354** successfully.  sqlite3_step() should not be called again on this virtual
3355** machine without first calling [sqlite3_reset()] to reset the virtual
3356** machine back to its initial state.
3357**
3358** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3359** is returned each time a new row of data is ready for processing by the
3360** caller. The values may be accessed using the [column access functions].
3361** sqlite3_step() is called again to retrieve the next row of data.
3362**
3363** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3364** violation) has occurred.  sqlite3_step() should not be called again on
3365** the VM. More information may be found by calling [sqlite3_errmsg()].
3366** ^With the legacy interface, a more specific error code (for example,
3367** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3368** can be obtained by calling [sqlite3_reset()] on the
3369** [prepared statement].  ^In the "v2" interface,
3370** the more specific error code is returned directly by sqlite3_step().
3371**
3372** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3373** Perhaps it was called on a [prepared statement] that has
3374** already been [sqlite3_finalize | finalized] or on one that had
3375** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3376** be the case that the same database connection is being used by two or
3377** more threads at the same moment in time.
3378**
3379** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3380** API always returns a generic error code, [SQLITE_ERROR], following any
3381** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3382** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3383** specific [error codes] that better describes the error.
3384** We admit that this is a goofy design.  The problem has been fixed
3385** with the "v2" interface.  If you prepare all of your SQL statements
3386** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3387** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3388** then the more specific [error codes] are returned directly
3389** by sqlite3_step().  The use of the "v2" interface is recommended.
3390*/
3391SQLITE_API int sqlite3_step(sqlite3_stmt*);
3392
3393/*
3394** CAPI3REF: Number of columns in a result set
3395**
3396** ^The sqlite3_data_count(P) the number of columns in the
3397** of the result set of [prepared statement] P.
3398*/
3399SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3400
3401/*
3402** CAPI3REF: Fundamental Datatypes
3403** KEYWORDS: SQLITE_TEXT
3404**
3405** ^(Every value in SQLite has one of five fundamental datatypes:
3406**
3407** <ul>
3408** <li> 64-bit signed integer
3409** <li> 64-bit IEEE floating point number
3410** <li> string
3411** <li> BLOB
3412** <li> NULL
3413** </ul>)^
3414**
3415** These constants are codes for each of those types.
3416**
3417** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3418** for a completely different meaning.  Software that links against both
3419** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3420** SQLITE_TEXT.
3421*/
3422#define SQLITE_INTEGER  1
3423#define SQLITE_FLOAT    2
3424#define SQLITE_BLOB     4
3425#define SQLITE_NULL     5
3426#ifdef SQLITE_TEXT
3427# undef SQLITE_TEXT
3428#else
3429# define SQLITE_TEXT     3
3430#endif
3431#define SQLITE3_TEXT     3
3432
3433/*
3434** CAPI3REF: Result Values From A Query
3435** KEYWORDS: {column access functions}
3436**
3437** These routines form the "result set" interface.
3438**
3439** ^These routines return information about a single column of the current
3440** result row of a query.  ^In every case the first argument is a pointer
3441** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3442** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3443** and the second argument is the index of the column for which information
3444** should be returned. ^The leftmost column of the result set has the index 0.
3445** ^The number of columns in the result can be determined using
3446** [sqlite3_column_count()].
3447**
3448** If the SQL statement does not currently point to a valid row, or if the
3449** column index is out of range, the result is undefined.
3450** These routines may only be called when the most recent call to
3451** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3452** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3453** If any of these routines are called after [sqlite3_reset()] or
3454** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3455** something other than [SQLITE_ROW], the results are undefined.
3456** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3457** are called from a different thread while any of these routines
3458** are pending, then the results are undefined.
3459**
3460** ^The sqlite3_column_type() routine returns the
3461** [SQLITE_INTEGER | datatype code] for the initial data type
3462** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3463** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3464** returned by sqlite3_column_type() is only meaningful if no type
3465** conversions have occurred as described below.  After a type conversion,
3466** the value returned by sqlite3_column_type() is undefined.  Future
3467** versions of SQLite may change the behavior of sqlite3_column_type()
3468** following a type conversion.
3469**
3470** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3471** routine returns the number of bytes in that BLOB or string.
3472** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3473** the string to UTF-8 and then returns the number of bytes.
3474** ^If the result is a numeric value then sqlite3_column_bytes() uses
3475** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3476** the number of bytes in that string.
3477** ^The value returned does not include the zero terminator at the end
3478** of the string.  ^For clarity: the value returned is the number of
3479** bytes in the string, not the number of characters.
3480**
3481** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3482** even empty strings, are always zero terminated.  ^The return
3483** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
3484** pointer, possibly even a NULL pointer.
3485**
3486** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3487** but leaves the result in UTF-16 in native byte order instead of UTF-8.
3488** ^The zero terminator is not included in this count.
3489**
3490** ^The object returned by [sqlite3_column_value()] is an
3491** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3492** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3493** If the [unprotected sqlite3_value] object returned by
3494** [sqlite3_column_value()] is used in any other way, including calls
3495** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3496** or [sqlite3_value_bytes()], then the behavior is undefined.
3497**
3498** These routines attempt to convert the value where appropriate.  ^For
3499** example, if the internal representation is FLOAT and a text result
3500** is requested, [sqlite3_snprintf()] is used internally to perform the
3501** conversion automatically.  ^(The following table details the conversions
3502** that are applied:
3503**
3504** <blockquote>
3505** <table border="1">
3506** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3507**
3508** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3509** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3510** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3511** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3512** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3513** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3514** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3515** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3516** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3517** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3518** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3519** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3520** <tr><td>  TEXT    <td>   BLOB    <td> No change
3521** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3522** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3523** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3524** </table>
3525** </blockquote>)^
3526**
3527** The table above makes reference to standard C library functions atoi()
3528** and atof().  SQLite does not really use these functions.  It has its
3529** own equivalent internal routines.  The atoi() and atof() names are
3530** used in the table for brevity and because they are familiar to most
3531** C programmers.
3532**
3533** ^Note that when type conversions occur, pointers returned by prior
3534** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3535** sqlite3_column_text16() may be invalidated.
3536** ^(Type conversions and pointer invalidations might occur
3537** in the following cases:
3538**
3539** <ul>
3540** <li> The initial content is a BLOB and sqlite3_column_text() or
3541**      sqlite3_column_text16() is called.  A zero-terminator might
3542**      need to be added to the string.</li>
3543** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3544**      sqlite3_column_text16() is called.  The content must be converted
3545**      to UTF-16.</li>
3546** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3547**      sqlite3_column_text() is called.  The content must be converted
3548**      to UTF-8.</li>
3549** </ul>)^
3550**
3551** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3552** not invalidate a prior pointer, though of course the content of the buffer
3553** that the prior pointer points to will have been modified.  Other kinds
3554** of conversion are done in place when it is possible, but sometimes they
3555** are not possible and in those cases prior pointers are invalidated.
3556**
3557** ^(The safest and easiest to remember policy is to invoke these routines
3558** in one of the following ways:
3559**
3560** <ul>
3561**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3562**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3563**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3564** </ul>)^
3565**
3566** In other words, you should call sqlite3_column_text(),
3567** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3568** into the desired format, then invoke sqlite3_column_bytes() or
3569** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3570** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3571** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3572** with calls to sqlite3_column_bytes().
3573**
3574** ^The pointers returned are valid until a type conversion occurs as
3575** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3576** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3577** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3578** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3579** [sqlite3_free()].
3580**
3581** ^(If a memory allocation error occurs during the evaluation of any
3582** of these routines, a default value is returned.  The default value
3583** is either the integer 0, the floating point number 0.0, or a NULL
3584** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3585** [SQLITE_NOMEM].)^
3586*/
3587SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3588SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3589SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3590SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3591SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3592SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3593SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3594SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3595SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3596SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3597
3598/*
3599** CAPI3REF: Destroy A Prepared Statement Object
3600**
3601** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3602** ^If the statement was executed successfully or not executed at all, then
3603** SQLITE_OK is returned. ^If execution of the statement failed then an
3604** [error code] or [extended error code] is returned.
3605**
3606** ^This routine can be called at any point during the execution of the
3607** [prepared statement].  ^If the virtual machine has not
3608** completed execution when this routine is called, that is like
3609** encountering an error or an [sqlite3_interrupt | interrupt].
3610** ^Incomplete updates may be rolled back and transactions canceled,
3611** depending on the circumstances, and the
3612** [error code] returned will be [SQLITE_ABORT].
3613*/
3614SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3615
3616/*
3617** CAPI3REF: Reset A Prepared Statement Object
3618**
3619** The sqlite3_reset() function is called to reset a [prepared statement]
3620** object back to its initial state, ready to be re-executed.
3621** ^Any SQL statement variables that had values bound to them using
3622** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3623** Use [sqlite3_clear_bindings()] to reset the bindings.
3624**
3625** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3626** back to the beginning of its program.
3627**
3628** ^If the most recent call to [sqlite3_step(S)] for the
3629** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3630** or if [sqlite3_step(S)] has never before been called on S,
3631** then [sqlite3_reset(S)] returns [SQLITE_OK].
3632**
3633** ^If the most recent call to [sqlite3_step(S)] for the
3634** [prepared statement] S indicated an error, then
3635** [sqlite3_reset(S)] returns an appropriate [error code].
3636**
3637** ^The [sqlite3_reset(S)] interface does not change the values
3638** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3639*/
3640SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3641
3642/*
3643** CAPI3REF: Create Or Redefine SQL Functions
3644** KEYWORDS: {function creation routines}
3645** KEYWORDS: {application-defined SQL function}
3646** KEYWORDS: {application-defined SQL functions}
3647**
3648** ^These two functions (collectively known as "function creation routines")
3649** are used to add SQL functions or aggregates or to redefine the behavior
3650** of existing SQL functions or aggregates.  The only difference between the
3651** two is that the second parameter, the name of the (scalar) function or
3652** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
3653** for sqlite3_create_function16().
3654**
3655** ^The first parameter is the [database connection] to which the SQL
3656** function is to be added.  ^If an application uses more than one database
3657** connection then application-defined SQL functions must be added
3658** to each database connection separately.
3659**
3660** The second parameter is the name of the SQL function to be created or
3661** redefined.  ^The length of the name is limited to 255 bytes, exclusive of
3662** the zero-terminator.  Note that the name length limit is in bytes, not
3663** characters.  ^Any attempt to create a function with a longer name
3664** will result in [SQLITE_ERROR] being returned.
3665**
3666** ^The third parameter (nArg)
3667** is the number of arguments that the SQL function or
3668** aggregate takes. ^If this parameter is -1, then the SQL function or
3669** aggregate may take any number of arguments between 0 and the limit
3670** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
3671** parameter is less than -1 or greater than 127 then the behavior is
3672** undefined.
3673**
3674** The fourth parameter, eTextRep, specifies what
3675** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3676** its parameters.  Any SQL function implementation should be able to work
3677** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3678** more efficient with one encoding than another.  ^An application may
3679** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3680** times with the same function but with different values of eTextRep.
3681** ^When multiple implementations of the same function are available, SQLite
3682** will pick the one that involves the least amount of data conversion.
3683** If there is only a single implementation which does not care what text
3684** encoding is used, then the fourth argument should be [SQLITE_ANY].
3685**
3686** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
3687** function can gain access to this pointer using [sqlite3_user_data()].)^
3688**
3689** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3690** pointers to C-language functions that implement the SQL function or
3691** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3692** callback only; NULL pointers should be passed as the xStep and xFinal
3693** parameters. ^An aggregate SQL function requires an implementation of xStep
3694** and xFinal and NULL should be passed for xFunc. ^To delete an existing
3695** SQL function or aggregate, pass NULL for all three function callbacks.
3696**
3697** ^It is permitted to register multiple implementations of the same
3698** functions with the same name but with either differing numbers of
3699** arguments or differing preferred text encodings.  ^SQLite will use
3700** the implementation that most closely matches the way in which the
3701** SQL function is used.  ^A function implementation with a non-negative
3702** nArg parameter is a better match than a function implementation with
3703** a negative nArg.  ^A function where the preferred text encoding
3704** matches the database encoding is a better
3705** match than a function where the encoding is different.
3706** ^A function where the encoding difference is between UTF16le and UTF16be
3707** is a closer match than a function where the encoding difference is
3708** between UTF8 and UTF16.
3709**
3710** ^Built-in functions may be overloaded by new application-defined functions.
3711** ^The first application-defined function with a given name overrides all
3712** built-in functions in the same [database connection] with the same name.
3713** ^Subsequent application-defined functions of the same name only override
3714** prior application-defined functions that are an exact match for the
3715** number of parameters and preferred encoding.
3716**
3717** ^An application-defined function is permitted to call other
3718** SQLite interfaces.  However, such calls must not
3719** close the database connection nor finalize or reset the prepared
3720** statement in which the function is running.
3721*/
3722SQLITE_API int sqlite3_create_function(
3723  sqlite3 *db,
3724  const char *zFunctionName,
3725  int nArg,
3726  int eTextRep,
3727  void *pApp,
3728  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3729  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3730  void (*xFinal)(sqlite3_context*)
3731);
3732SQLITE_API int sqlite3_create_function16(
3733  sqlite3 *db,
3734  const void *zFunctionName,
3735  int nArg,
3736  int eTextRep,
3737  void *pApp,
3738  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3739  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3740  void (*xFinal)(sqlite3_context*)
3741);
3742
3743/*
3744** CAPI3REF: Text Encodings
3745**
3746** These constant define integer codes that represent the various
3747** text encodings supported by SQLite.
3748*/
3749#define SQLITE_UTF8           1
3750#define SQLITE_UTF16LE        2
3751#define SQLITE_UTF16BE        3
3752#define SQLITE_UTF16          4    /* Use native byte order */
3753#define SQLITE_ANY            5    /* sqlite3_create_function only */
3754#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
3755
3756/*
3757** CAPI3REF: Deprecated Functions
3758** DEPRECATED
3759**
3760** These functions are [deprecated].  In order to maintain
3761** backwards compatibility with older code, these functions continue
3762** to be supported.  However, new applications should avoid
3763** the use of these functions.  To help encourage people to avoid
3764** using these functions, we are not going to tell you what they do.
3765*/
3766#ifndef SQLITE_OMIT_DEPRECATED
3767SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
3768SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
3769SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
3770SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
3771SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
3772SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
3773#endif
3774
3775/*
3776** CAPI3REF: Obtaining SQL Function Parameter Values
3777**
3778** The C-language implementation of SQL functions and aggregates uses
3779** this set of interface routines to access the parameter values on
3780** the function or aggregate.
3781**
3782** The xFunc (for scalar functions) or xStep (for aggregates) parameters
3783** to [sqlite3_create_function()] and [sqlite3_create_function16()]
3784** define callbacks that implement the SQL functions and aggregates.
3785** The 4th parameter to these callbacks is an array of pointers to
3786** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
3787** each parameter to the SQL function.  These routines are used to
3788** extract values from the [sqlite3_value] objects.
3789**
3790** These routines work only with [protected sqlite3_value] objects.
3791** Any attempt to use these routines on an [unprotected sqlite3_value]
3792** object results in undefined behavior.
3793**
3794** ^These routines work just like the corresponding [column access functions]
3795** except that  these routines take a single [protected sqlite3_value] object
3796** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
3797**
3798** ^The sqlite3_value_text16() interface extracts a UTF-16 string
3799** in the native byte-order of the host machine.  ^The
3800** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
3801** extract UTF-16 strings as big-endian and little-endian respectively.
3802**
3803** ^(The sqlite3_value_numeric_type() interface attempts to apply
3804** numeric affinity to the value.  This means that an attempt is
3805** made to convert the value to an integer or floating point.  If
3806** such a conversion is possible without loss of information (in other
3807** words, if the value is a string that looks like a number)
3808** then the conversion is performed.  Otherwise no conversion occurs.
3809** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
3810**
3811** Please pay particular attention to the fact that the pointer returned
3812** from [sqlite3_value_blob()], [sqlite3_value_text()], or
3813** [sqlite3_value_text16()] can be invalidated by a subsequent call to
3814** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
3815** or [sqlite3_value_text16()].
3816**
3817** These routines must be called from the same thread as
3818** the SQL function that supplied the [sqlite3_value*] parameters.
3819*/
3820SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
3821SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
3822SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
3823SQLITE_API double sqlite3_value_double(sqlite3_value*);
3824SQLITE_API int sqlite3_value_int(sqlite3_value*);
3825SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
3826SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
3827SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
3828SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
3829SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
3830SQLITE_API int sqlite3_value_type(sqlite3_value*);
3831SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
3832
3833/*
3834** CAPI3REF: Obtain Aggregate Function Context
3835**
3836** Implementions of aggregate SQL functions use this
3837** routine to allocate memory for storing their state.
3838**
3839** ^The first time the sqlite3_aggregate_context(C,N) routine is called
3840** for a particular aggregate function, SQLite
3841** allocates N of memory, zeroes out that memory, and returns a pointer
3842** to the new memory. ^On second and subsequent calls to
3843** sqlite3_aggregate_context() for the same aggregate function instance,
3844** the same buffer is returned.  Sqlite3_aggregate_context() is normally
3845** called once for each invocation of the xStep callback and then one
3846** last time when the xFinal callback is invoked.  ^(When no rows match
3847** an aggregate query, the xStep() callback of the aggregate function
3848** implementation is never called and xFinal() is called exactly once.
3849** In those cases, sqlite3_aggregate_context() might be called for the
3850** first time from within xFinal().)^
3851**
3852** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
3853** less than or equal to zero or if a memory allocate error occurs.
3854**
3855** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
3856** determined by the N parameter on first successful call.  Changing the
3857** value of N in subsequent call to sqlite3_aggregate_context() within
3858** the same aggregate function instance will not resize the memory
3859** allocation.)^
3860**
3861** ^SQLite automatically frees the memory allocated by
3862** sqlite3_aggregate_context() when the aggregate query concludes.
3863**
3864** The first parameter must be a copy of the
3865** [sqlite3_context | SQL function context] that is the first parameter
3866** to the xStep or xFinal callback routine that implements the aggregate
3867** function.
3868**
3869** This routine must be called from the same thread in which
3870** the aggregate SQL function is running.
3871*/
3872SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
3873
3874/*
3875** CAPI3REF: User Data For Functions
3876**
3877** ^The sqlite3_user_data() interface returns a copy of
3878** the pointer that was the pUserData parameter (the 5th parameter)
3879** of the [sqlite3_create_function()]
3880** and [sqlite3_create_function16()] routines that originally
3881** registered the application defined function.
3882**
3883** This routine must be called from the same thread in which
3884** the application-defined function is running.
3885*/
3886SQLITE_API void *sqlite3_user_data(sqlite3_context*);
3887
3888/*
3889** CAPI3REF: Database Connection For Functions
3890**
3891** ^The sqlite3_context_db_handle() interface returns a copy of
3892** the pointer to the [database connection] (the 1st parameter)
3893** of the [sqlite3_create_function()]
3894** and [sqlite3_create_function16()] routines that originally
3895** registered the application defined function.
3896*/
3897SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
3898
3899/*
3900** CAPI3REF: Function Auxiliary Data
3901**
3902** The following two functions may be used by scalar SQL functions to
3903** associate metadata with argument values. If the same value is passed to
3904** multiple invocations of the same SQL function during query execution, under
3905** some circumstances the associated metadata may be preserved. This may
3906** be used, for example, to add a regular-expression matching scalar
3907** function. The compiled version of the regular expression is stored as
3908** metadata associated with the SQL value passed as the regular expression
3909** pattern.  The compiled regular expression can be reused on multiple
3910** invocations of the same function so that the original pattern string
3911** does not need to be recompiled on each invocation.
3912**
3913** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
3914** associated by the sqlite3_set_auxdata() function with the Nth argument
3915** value to the application-defined function. ^If no metadata has been ever
3916** been set for the Nth argument of the function, or if the corresponding
3917** function parameter has changed since the meta-data was set,
3918** then sqlite3_get_auxdata() returns a NULL pointer.
3919**
3920** ^The sqlite3_set_auxdata() interface saves the metadata
3921** pointed to by its 3rd parameter as the metadata for the N-th
3922** argument of the application-defined function.  Subsequent
3923** calls to sqlite3_get_auxdata() might return this data, if it has
3924** not been destroyed.
3925** ^If it is not NULL, SQLite will invoke the destructor
3926** function given by the 4th parameter to sqlite3_set_auxdata() on
3927** the metadata when the corresponding function parameter changes
3928** or when the SQL statement completes, whichever comes first.
3929**
3930** SQLite is free to call the destructor and drop metadata on any
3931** parameter of any function at any time.  ^The only guarantee is that
3932** the destructor will be called before the metadata is dropped.
3933**
3934** ^(In practice, metadata is preserved between function calls for
3935** expressions that are constant at compile time. This includes literal
3936** values and [parameters].)^
3937**
3938** These routines must be called from the same thread in which
3939** the SQL function is running.
3940*/
3941SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
3942SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
3943
3944
3945/*
3946** CAPI3REF: Constants Defining Special Destructor Behavior
3947**
3948** These are special values for the destructor that is passed in as the
3949** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
3950** argument is SQLITE_STATIC, it means that the content pointer is constant
3951** and will never change.  It does not need to be destroyed.  ^The
3952** SQLITE_TRANSIENT value means that the content will likely change in
3953** the near future and that SQLite should make its own private copy of
3954** the content before returning.
3955**
3956** The typedef is necessary to work around problems in certain
3957** C++ compilers.  See ticket #2191.
3958*/
3959typedef void (*sqlite3_destructor_type)(void*);
3960#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
3961#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
3962
3963/*
3964** CAPI3REF: Setting The Result Of An SQL Function
3965**
3966** These routines are used by the xFunc or xFinal callbacks that
3967** implement SQL functions and aggregates.  See
3968** [sqlite3_create_function()] and [sqlite3_create_function16()]
3969** for additional information.
3970**
3971** These functions work very much like the [parameter binding] family of
3972** functions used to bind values to host parameters in prepared statements.
3973** Refer to the [SQL parameter] documentation for additional information.
3974**
3975** ^The sqlite3_result_blob() interface sets the result from
3976** an application-defined function to be the BLOB whose content is pointed
3977** to by the second parameter and which is N bytes long where N is the
3978** third parameter.
3979**
3980** ^The sqlite3_result_zeroblob() interfaces set the result of
3981** the application-defined function to be a BLOB containing all zero
3982** bytes and N bytes in size, where N is the value of the 2nd parameter.
3983**
3984** ^The sqlite3_result_double() interface sets the result from
3985** an application-defined function to be a floating point value specified
3986** by its 2nd argument.
3987**
3988** ^The sqlite3_result_error() and sqlite3_result_error16() functions
3989** cause the implemented SQL function to throw an exception.
3990** ^SQLite uses the string pointed to by the
3991** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
3992** as the text of an error message.  ^SQLite interprets the error
3993** message string from sqlite3_result_error() as UTF-8. ^SQLite
3994** interprets the string from sqlite3_result_error16() as UTF-16 in native
3995** byte order.  ^If the third parameter to sqlite3_result_error()
3996** or sqlite3_result_error16() is negative then SQLite takes as the error
3997** message all text up through the first zero character.
3998** ^If the third parameter to sqlite3_result_error() or
3999** sqlite3_result_error16() is non-negative then SQLite takes that many
4000** bytes (not characters) from the 2nd parameter as the error message.
4001** ^The sqlite3_result_error() and sqlite3_result_error16()
4002** routines make a private copy of the error message text before
4003** they return.  Hence, the calling function can deallocate or
4004** modify the text after they return without harm.
4005** ^The sqlite3_result_error_code() function changes the error code
4006** returned by SQLite as a result of an error in a function.  ^By default,
4007** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4008** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4009**
4010** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4011** indicating that a string or BLOB is too long to represent.
4012**
4013** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4014** indicating that a memory allocation failed.
4015**
4016** ^The sqlite3_result_int() interface sets the return value
4017** of the application-defined function to be the 32-bit signed integer
4018** value given in the 2nd argument.
4019** ^The sqlite3_result_int64() interface sets the return value
4020** of the application-defined function to be the 64-bit signed integer
4021** value given in the 2nd argument.
4022**
4023** ^The sqlite3_result_null() interface sets the return value
4024** of the application-defined function to be NULL.
4025**
4026** ^The sqlite3_result_text(), sqlite3_result_text16(),
4027** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4028** set the return value of the application-defined function to be
4029** a text string which is represented as UTF-8, UTF-16 native byte order,
4030** UTF-16 little endian, or UTF-16 big endian, respectively.
4031** ^SQLite takes the text result from the application from
4032** the 2nd parameter of the sqlite3_result_text* interfaces.
4033** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4034** is negative, then SQLite takes result text from the 2nd parameter
4035** through the first zero character.
4036** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4037** is non-negative, then as many bytes (not characters) of the text
4038** pointed to by the 2nd parameter are taken as the application-defined
4039** function result.
4040** ^If the 4th parameter to the sqlite3_result_text* interfaces
4041** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4042** function as the destructor on the text or BLOB result when it has
4043** finished using that result.
4044** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4045** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4046** assumes that the text or BLOB result is in constant space and does not
4047** copy the content of the parameter nor call a destructor on the content
4048** when it has finished using that result.
4049** ^If the 4th parameter to the sqlite3_result_text* interfaces
4050** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4051** then SQLite makes a copy of the result into space obtained from
4052** from [sqlite3_malloc()] before it returns.
4053**
4054** ^The sqlite3_result_value() interface sets the result of
4055** the application-defined function to be a copy the
4056** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4057** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4058** so that the [sqlite3_value] specified in the parameter may change or
4059** be deallocated after sqlite3_result_value() returns without harm.
4060** ^A [protected sqlite3_value] object may always be used where an
4061** [unprotected sqlite3_value] object is required, so either
4062** kind of [sqlite3_value] object can be used with this interface.
4063**
4064** If these routines are called from within the different thread
4065** than the one containing the application-defined function that received
4066** the [sqlite3_context] pointer, the results are undefined.
4067*/
4068SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4069SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4070SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4071SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4072SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4073SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4074SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4075SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4076SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4077SQLITE_API void sqlite3_result_null(sqlite3_context*);
4078SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4079SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4080SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4081SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4082SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4083SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4084
4085/*
4086** CAPI3REF: Define New Collating Sequences
4087**
4088** These functions are used to add new collation sequences to the
4089** [database connection] specified as the first argument.
4090**
4091** ^The name of the new collation sequence is specified as a UTF-8 string
4092** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4093** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
4094** the name is passed as the second function argument.
4095**
4096** ^The third argument may be one of the constants [SQLITE_UTF8],
4097** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
4098** routine expects to be passed pointers to strings encoded using UTF-8,
4099** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
4100** third argument might also be [SQLITE_UTF16] to indicate that the routine
4101** expects pointers to be UTF-16 strings in the native byte order, or the
4102** argument can be [SQLITE_UTF16_ALIGNED] if the
4103** the routine expects pointers to 16-bit word aligned strings
4104** of UTF-16 in the native byte order.
4105**
4106** A pointer to the user supplied routine must be passed as the fifth
4107** argument.  ^If it is NULL, this is the same as deleting the collation
4108** sequence (so that SQLite cannot call it anymore).
4109** ^Each time the application supplied function is invoked, it is passed
4110** as its first parameter a copy of the void* passed as the fourth argument
4111** to sqlite3_create_collation() or sqlite3_create_collation16().
4112**
4113** ^The remaining arguments to the application-supplied routine are two strings,
4114** each represented by a (length, data) pair and encoded in the encoding
4115** that was passed as the third argument when the collation sequence was
4116** registered.  The application defined collation routine should
4117** return negative, zero or positive if the first string is less than,
4118** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
4119**
4120** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4121** except that it takes an extra argument which is a destructor for
4122** the collation.  ^The destructor is called when the collation is
4123** destroyed and is passed a copy of the fourth parameter void* pointer
4124** of the sqlite3_create_collation_v2().
4125** ^Collations are destroyed when they are overridden by later calls to the
4126** collation creation functions or when the [database connection] is closed
4127** using [sqlite3_close()].
4128**
4129** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4130*/
4131SQLITE_API int sqlite3_create_collation(
4132  sqlite3*,
4133  const char *zName,
4134  int eTextRep,
4135  void*,
4136  int(*xCompare)(void*,int,const void*,int,const void*)
4137);
4138SQLITE_API int sqlite3_create_collation_v2(
4139  sqlite3*,
4140  const char *zName,
4141  int eTextRep,
4142  void*,
4143  int(*xCompare)(void*,int,const void*,int,const void*),
4144  void(*xDestroy)(void*)
4145);
4146SQLITE_API int sqlite3_create_collation16(
4147  sqlite3*,
4148  const void *zName,
4149  int eTextRep,
4150  void*,
4151  int(*xCompare)(void*,int,const void*,int,const void*)
4152);
4153
4154/*
4155** CAPI3REF: Collation Needed Callbacks
4156**
4157** ^To avoid having to register all collation sequences before a database
4158** can be used, a single callback function may be registered with the
4159** [database connection] to be invoked whenever an undefined collation
4160** sequence is required.
4161**
4162** ^If the function is registered using the sqlite3_collation_needed() API,
4163** then it is passed the names of undefined collation sequences as strings
4164** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4165** the names are passed as UTF-16 in machine native byte order.
4166** ^A call to either function replaces the existing collation-needed callback.
4167**
4168** ^(When the callback is invoked, the first argument passed is a copy
4169** of the second argument to sqlite3_collation_needed() or
4170** sqlite3_collation_needed16().  The second argument is the database
4171** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4172** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4173** sequence function required.  The fourth parameter is the name of the
4174** required collation sequence.)^
4175**
4176** The callback function should register the desired collation using
4177** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4178** [sqlite3_create_collation_v2()].
4179*/
4180SQLITE_API int sqlite3_collation_needed(
4181  sqlite3*,
4182  void*,
4183  void(*)(void*,sqlite3*,int eTextRep,const char*)
4184);
4185SQLITE_API int sqlite3_collation_needed16(
4186  sqlite3*,
4187  void*,
4188  void(*)(void*,sqlite3*,int eTextRep,const void*)
4189);
4190
4191/*
4192** Specify the key for an encrypted database.  This routine should be
4193** called right after sqlite3_open().
4194**
4195** The code to implement this API is not available in the public release
4196** of SQLite.
4197*/
4198SQLITE_API int sqlite3_key(
4199  sqlite3 *db,                   /* Database to be rekeyed */
4200  const void *pKey, int nKey     /* The key */
4201);
4202
4203/*
4204** Change the key on an open database.  If the current database is not
4205** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4206** database is decrypted.
4207**
4208** The code to implement this API is not available in the public release
4209** of SQLite.
4210*/
4211SQLITE_API int sqlite3_rekey(
4212  sqlite3 *db,                   /* Database to be rekeyed */
4213  const void *pKey, int nKey     /* The new key */
4214);
4215
4216/*
4217** CAPI3REF: Suspend Execution For A Short Time
4218**
4219** ^The sqlite3_sleep() function causes the current thread to suspend execution
4220** for at least a number of milliseconds specified in its parameter.
4221**
4222** ^If the operating system does not support sleep requests with
4223** millisecond time resolution, then the time will be rounded up to
4224** the nearest second. ^The number of milliseconds of sleep actually
4225** requested from the operating system is returned.
4226**
4227** ^SQLite implements this interface by calling the xSleep()
4228** method of the default [sqlite3_vfs] object.
4229*/
4230SQLITE_API int sqlite3_sleep(int);
4231
4232/*
4233** CAPI3REF: Name Of The Folder Holding Temporary Files
4234**
4235** ^(If this global variable is made to point to a string which is
4236** the name of a folder (a.k.a. directory), then all temporary files
4237** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4238** will be placed in that directory.)^  ^If this variable
4239** is a NULL pointer, then SQLite performs a search for an appropriate
4240** temporary file directory.
4241**
4242** It is not safe to read or modify this variable in more than one
4243** thread at a time.  It is not safe to read or modify this variable
4244** if a [database connection] is being used at the same time in a separate
4245** thread.
4246** It is intended that this variable be set once
4247** as part of process initialization and before any SQLite interface
4248** routines have been called and that this variable remain unchanged
4249** thereafter.
4250**
4251** ^The [temp_store_directory pragma] may modify this variable and cause
4252** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4253** the [temp_store_directory pragma] always assumes that any string
4254** that this variable points to is held in memory obtained from
4255** [sqlite3_malloc] and the pragma may attempt to free that memory
4256** using [sqlite3_free].
4257** Hence, if this variable is modified directly, either it should be
4258** made NULL or made to point to memory obtained from [sqlite3_malloc]
4259** or else the use of the [temp_store_directory pragma] should be avoided.
4260*/
4261SQLITE_API char *sqlite3_temp_directory;
4262
4263/*
4264** CAPI3REF: Test For Auto-Commit Mode
4265** KEYWORDS: {autocommit mode}
4266**
4267** ^The sqlite3_get_autocommit() interface returns non-zero or
4268** zero if the given database connection is or is not in autocommit mode,
4269** respectively.  ^Autocommit mode is on by default.
4270** ^Autocommit mode is disabled by a [BEGIN] statement.
4271** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4272**
4273** If certain kinds of errors occur on a statement within a multi-statement
4274** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4275** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4276** transaction might be rolled back automatically.  The only way to
4277** find out whether SQLite automatically rolled back the transaction after
4278** an error is to use this function.
4279**
4280** If another thread changes the autocommit status of the database
4281** connection while this routine is running, then the return value
4282** is undefined.
4283*/
4284SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4285
4286/*
4287** CAPI3REF: Find The Database Handle Of A Prepared Statement
4288**
4289** ^The sqlite3_db_handle interface returns the [database connection] handle
4290** to which a [prepared statement] belongs.  ^The [database connection]
4291** returned by sqlite3_db_handle is the same [database connection]
4292** that was the first argument
4293** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4294** create the statement in the first place.
4295*/
4296SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4297
4298/*
4299** CAPI3REF: Find the next prepared statement
4300**
4301** ^This interface returns a pointer to the next [prepared statement] after
4302** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4303** then this interface returns a pointer to the first prepared statement
4304** associated with the database connection pDb.  ^If no prepared statement
4305** satisfies the conditions of this routine, it returns NULL.
4306**
4307** The [database connection] pointer D in a call to
4308** [sqlite3_next_stmt(D,S)] must refer to an open database
4309** connection and in particular must not be a NULL pointer.
4310*/
4311SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4312
4313/*
4314** CAPI3REF: Commit And Rollback Notification Callbacks
4315**
4316** ^The sqlite3_commit_hook() interface registers a callback
4317** function to be invoked whenever a transaction is [COMMIT | committed].
4318** ^Any callback set by a previous call to sqlite3_commit_hook()
4319** for the same database connection is overridden.
4320** ^The sqlite3_rollback_hook() interface registers a callback
4321** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4322** ^Any callback set by a previous call to sqlite3_rollback_hook()
4323** for the same database connection is overridden.
4324** ^The pArg argument is passed through to the callback.
4325** ^If the callback on a commit hook function returns non-zero,
4326** then the commit is converted into a rollback.
4327**
4328** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4329** return the P argument from the previous call of the same function
4330** on the same [database connection] D, or NULL for
4331** the first call for each function on D.
4332**
4333** The callback implementation must not do anything that will modify
4334** the database connection that invoked the callback.  Any actions
4335** to modify the database connection must be deferred until after the
4336** completion of the [sqlite3_step()] call that triggered the commit
4337** or rollback hook in the first place.
4338** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4339** database connections for the meaning of "modify" in this paragraph.
4340**
4341** ^Registering a NULL function disables the callback.
4342**
4343** ^When the commit hook callback routine returns zero, the [COMMIT]
4344** operation is allowed to continue normally.  ^If the commit hook
4345** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4346** ^The rollback hook is invoked on a rollback that results from a commit
4347** hook returning non-zero, just as it would be with any other rollback.
4348**
4349** ^For the purposes of this API, a transaction is said to have been
4350** rolled back if an explicit "ROLLBACK" statement is executed, or
4351** an error or constraint causes an implicit rollback to occur.
4352** ^The rollback callback is not invoked if a transaction is
4353** automatically rolled back because the database connection is closed.
4354** ^The rollback callback is not invoked if a transaction is
4355** rolled back because a commit callback returned non-zero.
4356**
4357** See also the [sqlite3_update_hook()] interface.
4358*/
4359SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4360SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4361
4362/*
4363** CAPI3REF: Data Change Notification Callbacks
4364**
4365** ^The sqlite3_update_hook() interface registers a callback function
4366** with the [database connection] identified by the first argument
4367** to be invoked whenever a row is updated, inserted or deleted.
4368** ^Any callback set by a previous call to this function
4369** for the same database connection is overridden.
4370**
4371** ^The second argument is a pointer to the function to invoke when a
4372** row is updated, inserted or deleted.
4373** ^The first argument to the callback is a copy of the third argument
4374** to sqlite3_update_hook().
4375** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4376** or [SQLITE_UPDATE], depending on the operation that caused the callback
4377** to be invoked.
4378** ^The third and fourth arguments to the callback contain pointers to the
4379** database and table name containing the affected row.
4380** ^The final callback parameter is the [rowid] of the row.
4381** ^In the case of an update, this is the [rowid] after the update takes place.
4382**
4383** ^(The update hook is not invoked when internal system tables are
4384** modified (i.e. sqlite_master and sqlite_sequence).)^
4385**
4386** ^In the current implementation, the update hook
4387** is not invoked when duplication rows are deleted because of an
4388** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4389** invoked when rows are deleted using the [truncate optimization].
4390** The exceptions defined in this paragraph might change in a future
4391** release of SQLite.
4392**
4393** The update hook implementation must not do anything that will modify
4394** the database connection that invoked the update hook.  Any actions
4395** to modify the database connection must be deferred until after the
4396** completion of the [sqlite3_step()] call that triggered the update hook.
4397** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4398** database connections for the meaning of "modify" in this paragraph.
4399**
4400** ^The sqlite3_update_hook(D,C,P) function
4401** returns the P argument from the previous call
4402** on the same [database connection] D, or NULL for
4403** the first call on D.
4404**
4405** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4406** interfaces.
4407*/
4408SQLITE_API void *sqlite3_update_hook(
4409  sqlite3*,
4410  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4411  void*
4412);
4413
4414/*
4415** CAPI3REF: Enable Or Disable Shared Pager Cache
4416** KEYWORDS: {shared cache}
4417**
4418** ^(This routine enables or disables the sharing of the database cache
4419** and schema data structures between [database connection | connections]
4420** to the same database. Sharing is enabled if the argument is true
4421** and disabled if the argument is false.)^
4422**
4423** ^Cache sharing is enabled and disabled for an entire process.
4424** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4425** sharing was enabled or disabled for each thread separately.
4426**
4427** ^(The cache sharing mode set by this interface effects all subsequent
4428** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4429** Existing database connections continue use the sharing mode
4430** that was in effect at the time they were opened.)^
4431**
4432** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4433** successfully.  An [error code] is returned otherwise.)^
4434**
4435** ^Shared cache is disabled by default. But this might change in
4436** future releases of SQLite.  Applications that care about shared
4437** cache setting should set it explicitly.
4438**
4439** See Also:  [SQLite Shared-Cache Mode]
4440*/
4441SQLITE_API int sqlite3_enable_shared_cache(int);
4442
4443/*
4444** CAPI3REF: Attempt To Free Heap Memory
4445**
4446** ^The sqlite3_release_memory() interface attempts to free N bytes
4447** of heap memory by deallocating non-essential memory allocations
4448** held by the database library.   Memory used to cache database
4449** pages to improve performance is an example of non-essential memory.
4450** ^sqlite3_release_memory() returns the number of bytes actually freed,
4451** which might be more or less than the amount requested.
4452*/
4453SQLITE_API int sqlite3_release_memory(int);
4454
4455/*
4456** CAPI3REF: Impose A Limit On Heap Size
4457**
4458** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
4459** on the amount of heap memory that may be allocated by SQLite.
4460** ^If an internal allocation is requested that would exceed the
4461** soft heap limit, [sqlite3_release_memory()] is invoked one or
4462** more times to free up some space before the allocation is performed.
4463**
4464** ^The limit is called "soft" because if [sqlite3_release_memory()]
4465** cannot free sufficient memory to prevent the limit from being exceeded,
4466** the memory is allocated anyway and the current operation proceeds.
4467**
4468** ^A negative or zero value for N means that there is no soft heap limit and
4469** [sqlite3_release_memory()] will only be called when memory is exhausted.
4470** ^The default value for the soft heap limit is zero.
4471**
4472** ^(SQLite makes a best effort to honor the soft heap limit.
4473** But if the soft heap limit cannot be honored, execution will
4474** continue without error or notification.)^  This is why the limit is
4475** called a "soft" limit.  It is advisory only.
4476**
4477** Prior to SQLite version 3.5.0, this routine only constrained the memory
4478** allocated by a single thread - the same thread in which this routine
4479** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
4480** applied to all threads. The value specified for the soft heap limit
4481** is an upper bound on the total memory allocation for all threads. In
4482** version 3.5.0 there is no mechanism for limiting the heap usage for
4483** individual threads.
4484*/
4485SQLITE_API void sqlite3_soft_heap_limit(int);
4486
4487/*
4488** CAPI3REF: Extract Metadata About A Column Of A Table
4489**
4490** ^This routine returns metadata about a specific column of a specific
4491** database table accessible using the [database connection] handle
4492** passed as the first function argument.
4493**
4494** ^The column is identified by the second, third and fourth parameters to
4495** this function. ^The second parameter is either the name of the database
4496** (i.e. "main", "temp", or an attached database) containing the specified
4497** table or NULL. ^If it is NULL, then all attached databases are searched
4498** for the table using the same algorithm used by the database engine to
4499** resolve unqualified table references.
4500**
4501** ^The third and fourth parameters to this function are the table and column
4502** name of the desired column, respectively. Neither of these parameters
4503** may be NULL.
4504**
4505** ^Metadata is returned by writing to the memory locations passed as the 5th
4506** and subsequent parameters to this function. ^Any of these arguments may be
4507** NULL, in which case the corresponding element of metadata is omitted.
4508**
4509** ^(<blockquote>
4510** <table border="1">
4511** <tr><th> Parameter <th> Output<br>Type <th>  Description
4512**
4513** <tr><td> 5th <td> const char* <td> Data type
4514** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4515** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4516** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4517** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4518** </table>
4519** </blockquote>)^
4520**
4521** ^The memory pointed to by the character pointers returned for the
4522** declaration type and collation sequence is valid only until the next
4523** call to any SQLite API function.
4524**
4525** ^If the specified table is actually a view, an [error code] is returned.
4526**
4527** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4528** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4529** parameters are set for the explicitly declared column. ^(If there is no
4530** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4531** parameters are set as follows:
4532**
4533** <pre>
4534**     data type: "INTEGER"
4535**     collation sequence: "BINARY"
4536**     not null: 0
4537**     primary key: 1
4538**     auto increment: 0
4539** </pre>)^
4540**
4541** ^(This function may load one or more schemas from database files. If an
4542** error occurs during this process, or if the requested table or column
4543** cannot be found, an [error code] is returned and an error message left
4544** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4545**
4546** ^This API is only available if the library was compiled with the
4547** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4548*/
4549SQLITE_API int sqlite3_table_column_metadata(
4550  sqlite3 *db,                /* Connection handle */
4551  const char *zDbName,        /* Database name or NULL */
4552  const char *zTableName,     /* Table name */
4553  const char *zColumnName,    /* Column name */
4554  char const **pzDataType,    /* OUTPUT: Declared data type */
4555  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4556  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4557  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
4558  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
4559);
4560
4561/*
4562** CAPI3REF: Load An Extension
4563**
4564** ^This interface loads an SQLite extension library from the named file.
4565**
4566** ^The sqlite3_load_extension() interface attempts to load an
4567** SQLite extension library contained in the file zFile.
4568**
4569** ^The entry point is zProc.
4570** ^zProc may be 0, in which case the name of the entry point
4571** defaults to "sqlite3_extension_init".
4572** ^The sqlite3_load_extension() interface returns
4573** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
4574** ^If an error occurs and pzErrMsg is not 0, then the
4575** [sqlite3_load_extension()] interface shall attempt to
4576** fill *pzErrMsg with error message text stored in memory
4577** obtained from [sqlite3_malloc()]. The calling function
4578** should free this memory by calling [sqlite3_free()].
4579**
4580** ^Extension loading must be enabled using
4581** [sqlite3_enable_load_extension()] prior to calling this API,
4582** otherwise an error will be returned.
4583**
4584** See also the [load_extension() SQL function].
4585*/
4586SQLITE_API int sqlite3_load_extension(
4587  sqlite3 *db,          /* Load the extension into this database connection */
4588  const char *zFile,    /* Name of the shared library containing extension */
4589  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
4590  char **pzErrMsg       /* Put error message here if not 0 */
4591);
4592
4593/*
4594** CAPI3REF: Enable Or Disable Extension Loading
4595**
4596** ^So as not to open security holes in older applications that are
4597** unprepared to deal with extension loading, and as a means of disabling
4598** extension loading while evaluating user-entered SQL, the following API
4599** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
4600**
4601** ^Extension loading is off by default. See ticket #1863.
4602** ^Call the sqlite3_enable_load_extension() routine with onoff==1
4603** to turn extension loading on and call it with onoff==0 to turn
4604** it back off again.
4605*/
4606SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4607
4608/*
4609** CAPI3REF: Automatically Load An Extensions
4610**
4611** ^This API can be invoked at program startup in order to register
4612** one or more statically linked extensions that will be available
4613** to all new [database connections].
4614**
4615** ^(This routine stores a pointer to the extension entry point
4616** in an array that is obtained from [sqlite3_malloc()].  That memory
4617** is deallocated by [sqlite3_reset_auto_extension()].)^
4618**
4619** ^This function registers an extension entry point that is
4620** automatically invoked whenever a new [database connection]
4621** is opened using [sqlite3_open()], [sqlite3_open16()],
4622** or [sqlite3_open_v2()].
4623** ^Duplicate extensions are detected so calling this routine
4624** multiple times with the same extension is harmless.
4625** ^Automatic extensions apply across all threads.
4626*/
4627SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4628
4629/*
4630** CAPI3REF: Reset Automatic Extension Loading
4631**
4632** ^(This function disables all previously registered automatic
4633** extensions. It undoes the effect of all prior
4634** [sqlite3_auto_extension()] calls.)^
4635**
4636** ^This function disables automatic extensions in all threads.
4637*/
4638SQLITE_API void sqlite3_reset_auto_extension(void);
4639
4640/*
4641****** EXPERIMENTAL - subject to change without notice **************
4642**
4643** The interface to the virtual-table mechanism is currently considered
4644** to be experimental.  The interface might change in incompatible ways.
4645** If this is a problem for you, do not use the interface at this time.
4646**
4647** When the virtual-table mechanism stabilizes, we will declare the
4648** interface fixed, support it indefinitely, and remove this comment.
4649*/
4650
4651/*
4652** Structures used by the virtual table interface
4653*/
4654typedef struct sqlite3_vtab sqlite3_vtab;
4655typedef struct sqlite3_index_info sqlite3_index_info;
4656typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4657typedef struct sqlite3_module sqlite3_module;
4658
4659/*
4660** CAPI3REF: Virtual Table Object
4661** KEYWORDS: sqlite3_module {virtual table module}
4662** EXPERIMENTAL
4663**
4664** This structure, sometimes called a a "virtual table module",
4665** defines the implementation of a [virtual tables].
4666** This structure consists mostly of methods for the module.
4667**
4668** ^A virtual table module is created by filling in a persistent
4669** instance of this structure and passing a pointer to that instance
4670** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4671** ^The registration remains valid until it is replaced by a different
4672** module or until the [database connection] closes.  The content
4673** of this structure must not change while it is registered with
4674** any database connection.
4675*/
4676struct sqlite3_module {
4677  int iVersion;
4678  int (*xCreate)(sqlite3*, void *pAux,
4679               int argc, const char *const*argv,
4680               sqlite3_vtab **ppVTab, char**);
4681  int (*xConnect)(sqlite3*, void *pAux,
4682               int argc, const char *const*argv,
4683               sqlite3_vtab **ppVTab, char**);
4684  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
4685  int (*xDisconnect)(sqlite3_vtab *pVTab);
4686  int (*xDestroy)(sqlite3_vtab *pVTab);
4687  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
4688  int (*xClose)(sqlite3_vtab_cursor*);
4689  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
4690                int argc, sqlite3_value **argv);
4691  int (*xNext)(sqlite3_vtab_cursor*);
4692  int (*xEof)(sqlite3_vtab_cursor*);
4693  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
4694  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
4695  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
4696  int (*xBegin)(sqlite3_vtab *pVTab);
4697  int (*xSync)(sqlite3_vtab *pVTab);
4698  int (*xCommit)(sqlite3_vtab *pVTab);
4699  int (*xRollback)(sqlite3_vtab *pVTab);
4700  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
4701                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
4702                       void **ppArg);
4703  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
4704};
4705
4706/*
4707** CAPI3REF: Virtual Table Indexing Information
4708** KEYWORDS: sqlite3_index_info
4709** EXPERIMENTAL
4710**
4711** The sqlite3_index_info structure and its substructures is used to
4712** pass information into and receive the reply from the [xBestIndex]
4713** method of a [virtual table module].  The fields under **Inputs** are the
4714** inputs to xBestIndex and are read-only.  xBestIndex inserts its
4715** results into the **Outputs** fields.
4716**
4717** ^(The aConstraint[] array records WHERE clause constraints of the form:
4718**
4719** <pre>column OP expr</pre>
4720**
4721** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
4722** stored in aConstraint[].op.)^  ^(The index of the column is stored in
4723** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
4724** expr on the right-hand side can be evaluated (and thus the constraint
4725** is usable) and false if it cannot.)^
4726**
4727** ^The optimizer automatically inverts terms of the form "expr OP column"
4728** and makes other simplifications to the WHERE clause in an attempt to
4729** get as many WHERE clause terms into the form shown above as possible.
4730** ^The aConstraint[] array only reports WHERE clause terms that are
4731** relevant to the particular virtual table being queried.
4732**
4733** ^Information about the ORDER BY clause is stored in aOrderBy[].
4734** ^Each term of aOrderBy records a column of the ORDER BY clause.
4735**
4736** The [xBestIndex] method must fill aConstraintUsage[] with information
4737** about what parameters to pass to xFilter.  ^If argvIndex>0 then
4738** the right-hand side of the corresponding aConstraint[] is evaluated
4739** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
4740** is true, then the constraint is assumed to be fully handled by the
4741** virtual table and is not checked again by SQLite.)^
4742**
4743** ^The idxNum and idxPtr values are recorded and passed into the
4744** [xFilter] method.
4745** ^[sqlite3_free()] is used to free idxPtr if and only if
4746** needToFreeIdxPtr is true.
4747**
4748** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
4749** the correct order to satisfy the ORDER BY clause so that no separate
4750** sorting step is required.
4751**
4752** ^The estimatedCost value is an estimate of the cost of doing the
4753** particular lookup.  A full scan of a table with N entries should have
4754** a cost of N.  A binary search of a table of N entries should have a
4755** cost of approximately log(N).
4756*/
4757struct sqlite3_index_info {
4758  /* Inputs */
4759  int nConstraint;           /* Number of entries in aConstraint */
4760  struct sqlite3_index_constraint {
4761     int iColumn;              /* Column on left-hand side of constraint */
4762     unsigned char op;         /* Constraint operator */
4763     unsigned char usable;     /* True if this constraint is usable */
4764     int iTermOffset;          /* Used internally - xBestIndex should ignore */
4765  } *aConstraint;            /* Table of WHERE clause constraints */
4766  int nOrderBy;              /* Number of terms in the ORDER BY clause */
4767  struct sqlite3_index_orderby {
4768     int iColumn;              /* Column number */
4769     unsigned char desc;       /* True for DESC.  False for ASC. */
4770  } *aOrderBy;               /* The ORDER BY clause */
4771  /* Outputs */
4772  struct sqlite3_index_constraint_usage {
4773    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
4774    unsigned char omit;      /* Do not code a test for this constraint */
4775  } *aConstraintUsage;
4776  int idxNum;                /* Number used to identify the index */
4777  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
4778  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
4779  int orderByConsumed;       /* True if output is already ordered */
4780  double estimatedCost;      /* Estimated cost of using this index */
4781};
4782#define SQLITE_INDEX_CONSTRAINT_EQ    2
4783#define SQLITE_INDEX_CONSTRAINT_GT    4
4784#define SQLITE_INDEX_CONSTRAINT_LE    8
4785#define SQLITE_INDEX_CONSTRAINT_LT    16
4786#define SQLITE_INDEX_CONSTRAINT_GE    32
4787#define SQLITE_INDEX_CONSTRAINT_MATCH 64
4788
4789/*
4790** CAPI3REF: Register A Virtual Table Implementation
4791** EXPERIMENTAL
4792**
4793** ^These routines are used to register a new [virtual table module] name.
4794** ^Module names must be registered before
4795** creating a new [virtual table] using the module and before using a
4796** preexisting [virtual table] for the module.
4797**
4798** ^The module name is registered on the [database connection] specified
4799** by the first parameter.  ^The name of the module is given by the
4800** second parameter.  ^The third parameter is a pointer to
4801** the implementation of the [virtual table module].   ^The fourth
4802** parameter is an arbitrary client data pointer that is passed through
4803** into the [xCreate] and [xConnect] methods of the virtual table module
4804** when a new virtual table is be being created or reinitialized.
4805**
4806** ^The sqlite3_create_module_v2() interface has a fifth parameter which
4807** is a pointer to a destructor for the pClientData.  ^SQLite will
4808** invoke the destructor function (if it is not NULL) when SQLite
4809** no longer needs the pClientData pointer.  ^The sqlite3_create_module()
4810** interface is equivalent to sqlite3_create_module_v2() with a NULL
4811** destructor.
4812*/
4813SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
4814  sqlite3 *db,               /* SQLite connection to register module with */
4815  const char *zName,         /* Name of the module */
4816  const sqlite3_module *p,   /* Methods for the module */
4817  void *pClientData          /* Client data for xCreate/xConnect */
4818);
4819SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
4820  sqlite3 *db,               /* SQLite connection to register module with */
4821  const char *zName,         /* Name of the module */
4822  const sqlite3_module *p,   /* Methods for the module */
4823  void *pClientData,         /* Client data for xCreate/xConnect */
4824  void(*xDestroy)(void*)     /* Module destructor function */
4825);
4826
4827/*
4828** CAPI3REF: Virtual Table Instance Object
4829** KEYWORDS: sqlite3_vtab
4830** EXPERIMENTAL
4831**
4832** Every [virtual table module] implementation uses a subclass
4833** of this object to describe a particular instance
4834** of the [virtual table].  Each subclass will
4835** be tailored to the specific needs of the module implementation.
4836** The purpose of this superclass is to define certain fields that are
4837** common to all module implementations.
4838**
4839** ^Virtual tables methods can set an error message by assigning a
4840** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
4841** take care that any prior string is freed by a call to [sqlite3_free()]
4842** prior to assigning a new string to zErrMsg.  ^After the error message
4843** is delivered up to the client application, the string will be automatically
4844** freed by sqlite3_free() and the zErrMsg field will be zeroed.
4845*/
4846struct sqlite3_vtab {
4847  const sqlite3_module *pModule;  /* The module for this virtual table */
4848  int nRef;                       /* NO LONGER USED */
4849  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
4850  /* Virtual table implementations will typically add additional fields */
4851};
4852
4853/*
4854** CAPI3REF: Virtual Table Cursor Object
4855** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
4856** EXPERIMENTAL
4857**
4858** Every [virtual table module] implementation uses a subclass of the
4859** following structure to describe cursors that point into the
4860** [virtual table] and are used
4861** to loop through the virtual table.  Cursors are created using the
4862** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
4863** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
4864** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
4865** of the module.  Each module implementation will define
4866** the content of a cursor structure to suit its own needs.
4867**
4868** This superclass exists in order to define fields of the cursor that
4869** are common to all implementations.
4870*/
4871struct sqlite3_vtab_cursor {
4872  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
4873  /* Virtual table implementations will typically add additional fields */
4874};
4875
4876/*
4877** CAPI3REF: Declare The Schema Of A Virtual Table
4878** EXPERIMENTAL
4879**
4880** ^The [xCreate] and [xConnect] methods of a
4881** [virtual table module] call this interface
4882** to declare the format (the names and datatypes of the columns) of
4883** the virtual tables they implement.
4884*/
4885SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
4886
4887/*
4888** CAPI3REF: Overload A Function For A Virtual Table
4889** EXPERIMENTAL
4890**
4891** ^(Virtual tables can provide alternative implementations of functions
4892** using the [xFindFunction] method of the [virtual table module].
4893** But global versions of those functions
4894** must exist in order to be overloaded.)^
4895**
4896** ^(This API makes sure a global version of a function with a particular
4897** name and number of parameters exists.  If no such function exists
4898** before this API is called, a new function is created.)^  ^The implementation
4899** of the new function always causes an exception to be thrown.  So
4900** the new function is not good for anything by itself.  Its only
4901** purpose is to be a placeholder function that can be overloaded
4902** by a [virtual table].
4903*/
4904SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
4905
4906/*
4907** The interface to the virtual-table mechanism defined above (back up
4908** to a comment remarkably similar to this one) is currently considered
4909** to be experimental.  The interface might change in incompatible ways.
4910** If this is a problem for you, do not use the interface at this time.
4911**
4912** When the virtual-table mechanism stabilizes, we will declare the
4913** interface fixed, support it indefinitely, and remove this comment.
4914**
4915****** EXPERIMENTAL - subject to change without notice **************
4916*/
4917
4918/*
4919** CAPI3REF: A Handle To An Open BLOB
4920** KEYWORDS: {BLOB handle} {BLOB handles}
4921**
4922** An instance of this object represents an open BLOB on which
4923** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
4924** ^Objects of this type are created by [sqlite3_blob_open()]
4925** and destroyed by [sqlite3_blob_close()].
4926** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
4927** can be used to read or write small subsections of the BLOB.
4928** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
4929*/
4930typedef struct sqlite3_blob sqlite3_blob;
4931
4932/*
4933** CAPI3REF: Open A BLOB For Incremental I/O
4934**
4935** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
4936** in row iRow, column zColumn, table zTable in database zDb;
4937** in other words, the same BLOB that would be selected by:
4938**
4939** <pre>
4940**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
4941** </pre>)^
4942**
4943** ^If the flags parameter is non-zero, then the BLOB is opened for read
4944** and write access. ^If it is zero, the BLOB is opened for read access.
4945** ^It is not possible to open a column that is part of an index or primary
4946** key for writing. ^If [foreign key constraints] are enabled, it is
4947** not possible to open a column that is part of a [child key] for writing.
4948**
4949** ^Note that the database name is not the filename that contains
4950** the database but rather the symbolic name of the database that
4951** appears after the AS keyword when the database is connected using [ATTACH].
4952** ^For the main database file, the database name is "main".
4953** ^For TEMP tables, the database name is "temp".
4954**
4955** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
4956** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
4957** to be a null pointer.)^
4958** ^This function sets the [database connection] error code and message
4959** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
4960** functions. ^Note that the *ppBlob variable is always initialized in a
4961** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
4962** regardless of the success or failure of this routine.
4963**
4964** ^(If the row that a BLOB handle points to is modified by an
4965** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
4966** then the BLOB handle is marked as "expired".
4967** This is true if any column of the row is changed, even a column
4968** other than the one the BLOB handle is open on.)^
4969** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
4970** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
4971** ^(Changes written into a BLOB prior to the BLOB expiring are not
4972** rolled back by the expiration of the BLOB.  Such changes will eventually
4973** commit if the transaction continues to completion.)^
4974**
4975** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
4976** the opened blob.  ^The size of a blob may not be changed by this
4977** interface.  Use the [UPDATE] SQL command to change the size of a
4978** blob.
4979**
4980** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
4981** and the built-in [zeroblob] SQL function can be used, if desired,
4982** to create an empty, zero-filled blob in which to read or write using
4983** this interface.
4984**
4985** To avoid a resource leak, every open [BLOB handle] should eventually
4986** be released by a call to [sqlite3_blob_close()].
4987*/
4988SQLITE_API int sqlite3_blob_open(
4989  sqlite3*,
4990  const char *zDb,
4991  const char *zTable,
4992  const char *zColumn,
4993  sqlite3_int64 iRow,
4994  int flags,
4995  sqlite3_blob **ppBlob
4996);
4997
4998/*
4999** CAPI3REF: Close A BLOB Handle
5000**
5001** ^Closes an open [BLOB handle].
5002**
5003** ^Closing a BLOB shall cause the current transaction to commit
5004** if there are no other BLOBs, no pending prepared statements, and the
5005** database connection is in [autocommit mode].
5006** ^If any writes were made to the BLOB, they might be held in cache
5007** until the close operation if they will fit.
5008**
5009** ^(Closing the BLOB often forces the changes
5010** out to disk and so if any I/O errors occur, they will likely occur
5011** at the time when the BLOB is closed.  Any errors that occur during
5012** closing are reported as a non-zero return value.)^
5013**
5014** ^(The BLOB is closed unconditionally.  Even if this routine returns
5015** an error code, the BLOB is still closed.)^
5016**
5017** ^Calling this routine with a null pointer (such as would be returned
5018** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5019*/
5020SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5021
5022/*
5023** CAPI3REF: Return The Size Of An Open BLOB
5024**
5025** ^Returns the size in bytes of the BLOB accessible via the
5026** successfully opened [BLOB handle] in its only argument.  ^The
5027** incremental blob I/O routines can only read or overwriting existing
5028** blob content; they cannot change the size of a blob.
5029**
5030** This routine only works on a [BLOB handle] which has been created
5031** by a prior successful call to [sqlite3_blob_open()] and which has not
5032** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5033** to this routine results in undefined and probably undesirable behavior.
5034*/
5035SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5036
5037/*
5038** CAPI3REF: Read Data From A BLOB Incrementally
5039**
5040** ^(This function is used to read data from an open [BLOB handle] into a
5041** caller-supplied buffer. N bytes of data are copied into buffer Z
5042** from the open BLOB, starting at offset iOffset.)^
5043**
5044** ^If offset iOffset is less than N bytes from the end of the BLOB,
5045** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5046** less than zero, [SQLITE_ERROR] is returned and no data is read.
5047** ^The size of the blob (and hence the maximum value of N+iOffset)
5048** can be determined using the [sqlite3_blob_bytes()] interface.
5049**
5050** ^An attempt to read from an expired [BLOB handle] fails with an
5051** error code of [SQLITE_ABORT].
5052**
5053** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5054** Otherwise, an [error code] or an [extended error code] is returned.)^
5055**
5056** This routine only works on a [BLOB handle] which has been created
5057** by a prior successful call to [sqlite3_blob_open()] and which has not
5058** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5059** to this routine results in undefined and probably undesirable behavior.
5060**
5061** See also: [sqlite3_blob_write()].
5062*/
5063SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5064
5065/*
5066** CAPI3REF: Write Data Into A BLOB Incrementally
5067**
5068** ^This function is used to write data into an open [BLOB handle] from a
5069** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5070** into the open BLOB, starting at offset iOffset.
5071**
5072** ^If the [BLOB handle] passed as the first argument was not opened for
5073** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5074** this function returns [SQLITE_READONLY].
5075**
5076** ^This function may only modify the contents of the BLOB; it is
5077** not possible to increase the size of a BLOB using this API.
5078** ^If offset iOffset is less than N bytes from the end of the BLOB,
5079** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5080** less than zero [SQLITE_ERROR] is returned and no data is written.
5081** The size of the BLOB (and hence the maximum value of N+iOffset)
5082** can be determined using the [sqlite3_blob_bytes()] interface.
5083**
5084** ^An attempt to write to an expired [BLOB handle] fails with an
5085** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5086** before the [BLOB handle] expired are not rolled back by the
5087** expiration of the handle, though of course those changes might
5088** have been overwritten by the statement that expired the BLOB handle
5089** or by other independent statements.
5090**
5091** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5092** Otherwise, an  [error code] or an [extended error code] is returned.)^
5093**
5094** This routine only works on a [BLOB handle] which has been created
5095** by a prior successful call to [sqlite3_blob_open()] and which has not
5096** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5097** to this routine results in undefined and probably undesirable behavior.
5098**
5099** See also: [sqlite3_blob_read()].
5100*/
5101SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5102
5103/*
5104** CAPI3REF: Virtual File System Objects
5105**
5106** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5107** that SQLite uses to interact
5108** with the underlying operating system.  Most SQLite builds come with a
5109** single default VFS that is appropriate for the host computer.
5110** New VFSes can be registered and existing VFSes can be unregistered.
5111** The following interfaces are provided.
5112**
5113** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5114** ^Names are case sensitive.
5115** ^Names are zero-terminated UTF-8 strings.
5116** ^If there is no match, a NULL pointer is returned.
5117** ^If zVfsName is NULL then the default VFS is returned.
5118**
5119** ^New VFSes are registered with sqlite3_vfs_register().
5120** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5121** ^The same VFS can be registered multiple times without injury.
5122** ^To make an existing VFS into the default VFS, register it again
5123** with the makeDflt flag set.  If two different VFSes with the
5124** same name are registered, the behavior is undefined.  If a
5125** VFS is registered with a name that is NULL or an empty string,
5126** then the behavior is undefined.
5127**
5128** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5129** ^(If the default VFS is unregistered, another VFS is chosen as
5130** the default.  The choice for the new VFS is arbitrary.)^
5131*/
5132SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5133SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5134SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5135
5136/*
5137** CAPI3REF: Mutexes
5138**
5139** The SQLite core uses these routines for thread
5140** synchronization. Though they are intended for internal
5141** use by SQLite, code that links against SQLite is
5142** permitted to use any of these routines.
5143**
5144** The SQLite source code contains multiple implementations
5145** of these mutex routines.  An appropriate implementation
5146** is selected automatically at compile-time.  ^(The following
5147** implementations are available in the SQLite core:
5148**
5149** <ul>
5150** <li>   SQLITE_MUTEX_OS2
5151** <li>   SQLITE_MUTEX_PTHREAD
5152** <li>   SQLITE_MUTEX_W32
5153** <li>   SQLITE_MUTEX_NOOP
5154** </ul>)^
5155**
5156** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5157** that does no real locking and is appropriate for use in
5158** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5159** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5160** are appropriate for use on OS/2, Unix, and Windows.
5161**
5162** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5163** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5164** implementation is included with the library. In this case the
5165** application must supply a custom mutex implementation using the
5166** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5167** before calling sqlite3_initialize() or any other public sqlite3_
5168** function that calls sqlite3_initialize().)^
5169**
5170** ^The sqlite3_mutex_alloc() routine allocates a new
5171** mutex and returns a pointer to it. ^If it returns NULL
5172** that means that a mutex could not be allocated.  ^SQLite
5173** will unwind its stack and return an error.  ^(The argument
5174** to sqlite3_mutex_alloc() is one of these integer constants:
5175**
5176** <ul>
5177** <li>  SQLITE_MUTEX_FAST
5178** <li>  SQLITE_MUTEX_RECURSIVE
5179** <li>  SQLITE_MUTEX_STATIC_MASTER
5180** <li>  SQLITE_MUTEX_STATIC_MEM
5181** <li>  SQLITE_MUTEX_STATIC_MEM2
5182** <li>  SQLITE_MUTEX_STATIC_PRNG
5183** <li>  SQLITE_MUTEX_STATIC_LRU
5184** <li>  SQLITE_MUTEX_STATIC_LRU2
5185** </ul>)^
5186**
5187** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5188** cause sqlite3_mutex_alloc() to create
5189** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5190** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5191** The mutex implementation does not need to make a distinction
5192** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5193** not want to.  ^SQLite will only request a recursive mutex in
5194** cases where it really needs one.  ^If a faster non-recursive mutex
5195** implementation is available on the host platform, the mutex subsystem
5196** might return such a mutex in response to SQLITE_MUTEX_FAST.
5197**
5198** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5199** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5200** a pointer to a static preexisting mutex.  ^Six static mutexes are
5201** used by the current version of SQLite.  Future versions of SQLite
5202** may add additional static mutexes.  Static mutexes are for internal
5203** use by SQLite only.  Applications that use SQLite mutexes should
5204** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5205** SQLITE_MUTEX_RECURSIVE.
5206**
5207** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5208** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5209** returns a different mutex on every call.  ^But for the static
5210** mutex types, the same mutex is returned on every call that has
5211** the same type number.
5212**
5213** ^The sqlite3_mutex_free() routine deallocates a previously
5214** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5215** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5216** use when they are deallocated.  Attempting to deallocate a static
5217** mutex results in undefined behavior.  ^SQLite never deallocates
5218** a static mutex.
5219**
5220** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5221** to enter a mutex.  ^If another thread is already within the mutex,
5222** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5223** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5224** upon successful entry.  ^(Mutexes created using
5225** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5226** In such cases the,
5227** mutex must be exited an equal number of times before another thread
5228** can enter.)^  ^(If the same thread tries to enter any other
5229** kind of mutex more than once, the behavior is undefined.
5230** SQLite will never exhibit
5231** such behavior in its own use of mutexes.)^
5232**
5233** ^(Some systems (for example, Windows 95) do not support the operation
5234** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5235** will always return SQLITE_BUSY.  The SQLite core only ever uses
5236** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5237**
5238** ^The sqlite3_mutex_leave() routine exits a mutex that was
5239** previously entered by the same thread.   ^(The behavior
5240** is undefined if the mutex is not currently entered by the
5241** calling thread or is not currently allocated.  SQLite will
5242** never do either.)^
5243**
5244** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5245** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5246** behave as no-ops.
5247**
5248** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5249*/
5250SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5251SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5252SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5253SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5254SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5255
5256/*
5257** CAPI3REF: Mutex Methods Object
5258** EXPERIMENTAL
5259**
5260** An instance of this structure defines the low-level routines
5261** used to allocate and use mutexes.
5262**
5263** Usually, the default mutex implementations provided by SQLite are
5264** sufficient, however the user has the option of substituting a custom
5265** implementation for specialized deployments or systems for which SQLite
5266** does not provide a suitable implementation. In this case, the user
5267** creates and populates an instance of this structure to pass
5268** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5269** Additionally, an instance of this structure can be used as an
5270** output variable when querying the system for the current mutex
5271** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5272**
5273** ^The xMutexInit method defined by this structure is invoked as
5274** part of system initialization by the sqlite3_initialize() function.
5275** ^The xMutexInit routine is calle by SQLite exactly once for each
5276** effective call to [sqlite3_initialize()].
5277**
5278** ^The xMutexEnd method defined by this structure is invoked as
5279** part of system shutdown by the sqlite3_shutdown() function. The
5280** implementation of this method is expected to release all outstanding
5281** resources obtained by the mutex methods implementation, especially
5282** those obtained by the xMutexInit method.  ^The xMutexEnd()
5283** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5284**
5285** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5286** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5287** xMutexNotheld) implement the following interfaces (respectively):
5288**
5289** <ul>
5290**   <li>  [sqlite3_mutex_alloc()] </li>
5291**   <li>  [sqlite3_mutex_free()] </li>
5292**   <li>  [sqlite3_mutex_enter()] </li>
5293**   <li>  [sqlite3_mutex_try()] </li>
5294**   <li>  [sqlite3_mutex_leave()] </li>
5295**   <li>  [sqlite3_mutex_held()] </li>
5296**   <li>  [sqlite3_mutex_notheld()] </li>
5297** </ul>)^
5298**
5299** The only difference is that the public sqlite3_XXX functions enumerated
5300** above silently ignore any invocations that pass a NULL pointer instead
5301** of a valid mutex handle. The implementations of the methods defined
5302** by this structure are not required to handle this case, the results
5303** of passing a NULL pointer instead of a valid mutex handle are undefined
5304** (i.e. it is acceptable to provide an implementation that segfaults if
5305** it is passed a NULL pointer).
5306**
5307** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5308** invoke xMutexInit() mutiple times within the same process and without
5309** intervening calls to xMutexEnd().  Second and subsequent calls to
5310** xMutexInit() must be no-ops.
5311**
5312** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5313** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5314** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5315** memory allocation for a fast or recursive mutex.
5316**
5317** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5318** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5319** If xMutexInit fails in any way, it is expected to clean up after itself
5320** prior to returning.
5321*/
5322typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5323struct sqlite3_mutex_methods {
5324  int (*xMutexInit)(void);
5325  int (*xMutexEnd)(void);
5326  sqlite3_mutex *(*xMutexAlloc)(int);
5327  void (*xMutexFree)(sqlite3_mutex *);
5328  void (*xMutexEnter)(sqlite3_mutex *);
5329  int (*xMutexTry)(sqlite3_mutex *);
5330  void (*xMutexLeave)(sqlite3_mutex *);
5331  int (*xMutexHeld)(sqlite3_mutex *);
5332  int (*xMutexNotheld)(sqlite3_mutex *);
5333};
5334
5335/*
5336** CAPI3REF: Mutex Verification Routines
5337**
5338** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5339** are intended for use inside assert() statements.  ^The SQLite core
5340** never uses these routines except inside an assert() and applications
5341** are advised to follow the lead of the core.  ^The SQLite core only
5342** provides implementations for these routines when it is compiled
5343** with the SQLITE_DEBUG flag.  ^External mutex implementations
5344** are only required to provide these routines if SQLITE_DEBUG is
5345** defined and if NDEBUG is not defined.
5346**
5347** ^These routines should return true if the mutex in their argument
5348** is held or not held, respectively, by the calling thread.
5349**
5350** ^The implementation is not required to provided versions of these
5351** routines that actually work. If the implementation does not provide working
5352** versions of these routines, it should at least provide stubs that always
5353** return true so that one does not get spurious assertion failures.
5354**
5355** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5356** the routine should return 1.   This seems counter-intuitive since
5357** clearly the mutex cannot be held if it does not exist.  But the
5358** the reason the mutex does not exist is because the build is not
5359** using mutexes.  And we do not want the assert() containing the
5360** call to sqlite3_mutex_held() to fail, so a non-zero return is
5361** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5362** interface should also return 1 when given a NULL pointer.
5363*/
5364#ifndef NDEBUG
5365SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5366SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5367#endif
5368
5369/*
5370** CAPI3REF: Mutex Types
5371**
5372** The [sqlite3_mutex_alloc()] interface takes a single argument
5373** which is one of these integer constants.
5374**
5375** The set of static mutexes may change from one SQLite release to the
5376** next.  Applications that override the built-in mutex logic must be
5377** prepared to accommodate additional static mutexes.
5378*/
5379#define SQLITE_MUTEX_FAST             0
5380#define SQLITE_MUTEX_RECURSIVE        1
5381#define SQLITE_MUTEX_STATIC_MASTER    2
5382#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5383#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5384#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5385#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5386#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5387#define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
5388
5389/*
5390** CAPI3REF: Retrieve the mutex for a database connection
5391**
5392** ^This interface returns a pointer the [sqlite3_mutex] object that
5393** serializes access to the [database connection] given in the argument
5394** when the [threading mode] is Serialized.
5395** ^If the [threading mode] is Single-thread or Multi-thread then this
5396** routine returns a NULL pointer.
5397*/
5398SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5399
5400/*
5401** CAPI3REF: Low-Level Control Of Database Files
5402**
5403** ^The [sqlite3_file_control()] interface makes a direct call to the
5404** xFileControl method for the [sqlite3_io_methods] object associated
5405** with a particular database identified by the second argument. ^The
5406** name of the database "main" for the main database or "temp" for the
5407** TEMP database, or the name that appears after the AS keyword for
5408** databases that are added using the [ATTACH] SQL command.
5409** ^A NULL pointer can be used in place of "main" to refer to the
5410** main database file.
5411** ^The third and fourth parameters to this routine
5412** are passed directly through to the second and third parameters of
5413** the xFileControl method.  ^The return value of the xFileControl
5414** method becomes the return value of this routine.
5415**
5416** ^If the second parameter (zDbName) does not match the name of any
5417** open database file, then SQLITE_ERROR is returned.  ^This error
5418** code is not remembered and will not be recalled by [sqlite3_errcode()]
5419** or [sqlite3_errmsg()].  The underlying xFileControl method might
5420** also return SQLITE_ERROR.  There is no way to distinguish between
5421** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5422** xFileControl method.
5423**
5424** See also: [SQLITE_FCNTL_LOCKSTATE]
5425*/
5426SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5427
5428/*
5429** CAPI3REF: Testing Interface
5430**
5431** ^The sqlite3_test_control() interface is used to read out internal
5432** state of SQLite and to inject faults into SQLite for testing
5433** purposes.  ^The first parameter is an operation code that determines
5434** the number, meaning, and operation of all subsequent parameters.
5435**
5436** This interface is not for use by applications.  It exists solely
5437** for verifying the correct operation of the SQLite library.  Depending
5438** on how the SQLite library is compiled, this interface might not exist.
5439**
5440** The details of the operation codes, their meanings, the parameters
5441** they take, and what they do are all subject to change without notice.
5442** Unlike most of the SQLite API, this function is not guaranteed to
5443** operate consistently from one release to the next.
5444*/
5445SQLITE_API int sqlite3_test_control(int op, ...);
5446
5447/*
5448** CAPI3REF: Testing Interface Operation Codes
5449**
5450** These constants are the valid operation code parameters used
5451** as the first argument to [sqlite3_test_control()].
5452**
5453** These parameters and their meanings are subject to change
5454** without notice.  These values are for testing purposes only.
5455** Applications should not use any of these parameters or the
5456** [sqlite3_test_control()] interface.
5457*/
5458#define SQLITE_TESTCTRL_FIRST                    5
5459#define SQLITE_TESTCTRL_PRNG_SAVE                5
5460#define SQLITE_TESTCTRL_PRNG_RESTORE             6
5461#define SQLITE_TESTCTRL_PRNG_RESET               7
5462#define SQLITE_TESTCTRL_BITVEC_TEST              8
5463#define SQLITE_TESTCTRL_FAULT_INSTALL            9
5464#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5465#define SQLITE_TESTCTRL_PENDING_BYTE            11
5466#define SQLITE_TESTCTRL_ASSERT                  12
5467#define SQLITE_TESTCTRL_ALWAYS                  13
5468#define SQLITE_TESTCTRL_RESERVE                 14
5469#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5470#define SQLITE_TESTCTRL_ISKEYWORD               16
5471#define SQLITE_TESTCTRL_LAST                    16
5472
5473/*
5474** CAPI3REF: SQLite Runtime Status
5475** EXPERIMENTAL
5476**
5477** ^This interface is used to retrieve runtime status information
5478** about the preformance of SQLite, and optionally to reset various
5479** highwater marks.  ^The first argument is an integer code for
5480** the specific parameter to measure.  ^(Recognized integer codes
5481** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5482** ^The current value of the parameter is returned into *pCurrent.
5483** ^The highest recorded value is returned in *pHighwater.  ^If the
5484** resetFlag is true, then the highest record value is reset after
5485** *pHighwater is written.  ^(Some parameters do not record the highest
5486** value.  For those parameters
5487** nothing is written into *pHighwater and the resetFlag is ignored.)^
5488** ^(Other parameters record only the highwater mark and not the current
5489** value.  For these latter parameters nothing is written into *pCurrent.)^
5490**
5491** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5492** non-zero [error code] on failure.
5493**
5494** This routine is threadsafe but is not atomic.  This routine can be
5495** called while other threads are running the same or different SQLite
5496** interfaces.  However the values returned in *pCurrent and
5497** *pHighwater reflect the status of SQLite at different points in time
5498** and it is possible that another thread might change the parameter
5499** in between the times when *pCurrent and *pHighwater are written.
5500**
5501** See also: [sqlite3_db_status()]
5502*/
5503SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5504
5505
5506/*
5507** CAPI3REF: Status Parameters
5508** EXPERIMENTAL
5509**
5510** These integer constants designate various run-time status parameters
5511** that can be returned by [sqlite3_status()].
5512**
5513** <dl>
5514** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
5515** <dd>This parameter is the current amount of memory checked out
5516** using [sqlite3_malloc()], either directly or indirectly.  The
5517** figure includes calls made to [sqlite3_malloc()] by the application
5518** and internal memory usage by the SQLite library.  Scratch memory
5519** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
5520** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
5521** this parameter.  The amount returned is the sum of the allocation
5522** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
5523**
5524** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
5525** <dd>This parameter records the largest memory allocation request
5526** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
5527** internal equivalents).  Only the value returned in the
5528** *pHighwater parameter to [sqlite3_status()] is of interest.
5529** The value written into the *pCurrent parameter is undefined.</dd>)^
5530**
5531** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5532** <dd>This parameter returns the number of pages used out of the
5533** [pagecache memory allocator] that was configured using
5534** [SQLITE_CONFIG_PAGECACHE].  The
5535** value returned is in pages, not in bytes.</dd>)^
5536**
5537** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5538** <dd>This parameter returns the number of bytes of page cache
5539** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
5540** buffer and where forced to overflow to [sqlite3_malloc()].  The
5541** returned value includes allocations that overflowed because they
5542** where too large (they were larger than the "sz" parameter to
5543** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5544** no space was left in the page cache.</dd>)^
5545**
5546** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
5547** <dd>This parameter records the largest memory allocation request
5548** handed to [pagecache memory allocator].  Only the value returned in the
5549** *pHighwater parameter to [sqlite3_status()] is of interest.
5550** The value written into the *pCurrent parameter is undefined.</dd>)^
5551**
5552** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
5553** <dd>This parameter returns the number of allocations used out of the
5554** [scratch memory allocator] configured using
5555** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
5556** in bytes.  Since a single thread may only have one scratch allocation
5557** outstanding at time, this parameter also reports the number of threads
5558** using scratch memory at the same time.</dd>)^
5559**
5560** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5561** <dd>This parameter returns the number of bytes of scratch memory
5562** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
5563** buffer and where forced to overflow to [sqlite3_malloc()].  The values
5564** returned include overflows because the requested allocation was too
5565** larger (that is, because the requested allocation was larger than the
5566** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5567** slots were available.
5568** </dd>)^
5569**
5570** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
5571** <dd>This parameter records the largest memory allocation request
5572** handed to [scratch memory allocator].  Only the value returned in the
5573** *pHighwater parameter to [sqlite3_status()] is of interest.
5574** The value written into the *pCurrent parameter is undefined.</dd>)^
5575**
5576** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
5577** <dd>This parameter records the deepest parser stack.  It is only
5578** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
5579** </dl>
5580**
5581** New status parameters may be added from time to time.
5582*/
5583#define SQLITE_STATUS_MEMORY_USED          0
5584#define SQLITE_STATUS_PAGECACHE_USED       1
5585#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
5586#define SQLITE_STATUS_SCRATCH_USED         3
5587#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
5588#define SQLITE_STATUS_MALLOC_SIZE          5
5589#define SQLITE_STATUS_PARSER_STACK         6
5590#define SQLITE_STATUS_PAGECACHE_SIZE       7
5591#define SQLITE_STATUS_SCRATCH_SIZE         8
5592
5593/*
5594** CAPI3REF: Database Connection Status
5595** EXPERIMENTAL
5596**
5597** ^This interface is used to retrieve runtime status information
5598** about a single [database connection].  ^The first argument is the
5599** database connection object to be interrogated.  ^The second argument
5600** is the parameter to interrogate.  ^Currently, the only allowed value
5601** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
5602** Additional options will likely appear in future releases of SQLite.
5603**
5604** ^The current value of the requested parameter is written into *pCur
5605** and the highest instantaneous value is written into *pHiwtr.  ^If
5606** the resetFlg is true, then the highest instantaneous value is
5607** reset back down to the current value.
5608**
5609** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5610*/
5611SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5612
5613/*
5614** CAPI3REF: Status Parameters for database connections
5615** EXPERIMENTAL
5616**
5617** These constants are the available integer "verbs" that can be passed as
5618** the second argument to the [sqlite3_db_status()] interface.
5619**
5620** New verbs may be added in future releases of SQLite. Existing verbs
5621** might be discontinued. Applications should check the return code from
5622** [sqlite3_db_status()] to make sure that the call worked.
5623** The [sqlite3_db_status()] interface will return a non-zero error code
5624** if a discontinued or unsupported verb is invoked.
5625**
5626** <dl>
5627** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5628** <dd>This parameter returns the number of lookaside memory slots currently
5629** checked out.</dd>)^
5630** </dl>
5631*/
5632#define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5633
5634
5635/*
5636** CAPI3REF: Prepared Statement Status
5637** EXPERIMENTAL
5638**
5639** ^(Each prepared statement maintains various
5640** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
5641** of times it has performed specific operations.)^  These counters can
5642** be used to monitor the performance characteristics of the prepared
5643** statements.  For example, if the number of table steps greatly exceeds
5644** the number of table searches or result rows, that would tend to indicate
5645** that the prepared statement is using a full table scan rather than
5646** an index.
5647**
5648** ^(This interface is used to retrieve and reset counter values from
5649** a [prepared statement].  The first argument is the prepared statement
5650** object to be interrogated.  The second argument
5651** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
5652** to be interrogated.)^
5653** ^The current value of the requested counter is returned.
5654** ^If the resetFlg is true, then the counter is reset to zero after this
5655** interface call returns.
5656**
5657** See also: [sqlite3_status()] and [sqlite3_db_status()].
5658*/
5659SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
5660
5661/*
5662** CAPI3REF: Status Parameters for prepared statements
5663** EXPERIMENTAL
5664**
5665** These preprocessor macros define integer codes that name counter
5666** values associated with the [sqlite3_stmt_status()] interface.
5667** The meanings of the various counters are as follows:
5668**
5669** <dl>
5670** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
5671** <dd>^This is the number of times that SQLite has stepped forward in
5672** a table as part of a full table scan.  Large numbers for this counter
5673** may indicate opportunities for performance improvement through
5674** careful use of indices.</dd>
5675**
5676** <dt>SQLITE_STMTSTATUS_SORT</dt>
5677** <dd>^This is the number of sort operations that have occurred.
5678** A non-zero value in this counter may indicate an opportunity to
5679** improvement performance through careful use of indices.</dd>
5680**
5681** </dl>
5682*/
5683#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
5684#define SQLITE_STMTSTATUS_SORT              2
5685
5686/*
5687** CAPI3REF: Custom Page Cache Object
5688** EXPERIMENTAL
5689**
5690** The sqlite3_pcache type is opaque.  It is implemented by
5691** the pluggable module.  The SQLite core has no knowledge of
5692** its size or internal structure and never deals with the
5693** sqlite3_pcache object except by holding and passing pointers
5694** to the object.
5695**
5696** See [sqlite3_pcache_methods] for additional information.
5697*/
5698typedef struct sqlite3_pcache sqlite3_pcache;
5699
5700/*
5701** CAPI3REF: Application Defined Page Cache.
5702** KEYWORDS: {page cache}
5703** EXPERIMENTAL
5704**
5705** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5706** register an alternative page cache implementation by passing in an
5707** instance of the sqlite3_pcache_methods structure.)^ The majority of the
5708** heap memory used by SQLite is used by the page cache to cache data read
5709** from, or ready to be written to, the database file. By implementing a
5710** custom page cache using this API, an application can control more
5711** precisely the amount of memory consumed by SQLite, the way in which
5712** that memory is allocated and released, and the policies used to
5713** determine exactly which parts of a database file are cached and for
5714** how long.
5715**
5716** ^(The contents of the sqlite3_pcache_methods structure are copied to an
5717** internal buffer by SQLite within the call to [sqlite3_config].  Hence
5718** the application may discard the parameter after the call to
5719** [sqlite3_config()] returns.)^
5720**
5721** ^The xInit() method is called once for each call to [sqlite3_initialize()]
5722** (usually only once during the lifetime of the process). ^(The xInit()
5723** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5724** ^The xInit() method can set up up global structures and/or any mutexes
5725** required by the custom page cache implementation.
5726**
5727** ^The xShutdown() method is called from within [sqlite3_shutdown()],
5728** if the application invokes this API. It can be used to clean up
5729** any outstanding resources before process shutdown, if required.
5730**
5731** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
5732** the xInit method, so the xInit method need not be threadsafe.  ^The
5733** xShutdown method is only called from [sqlite3_shutdown()] so it does
5734** not need to be threadsafe either.  All other methods must be threadsafe
5735** in multithreaded applications.
5736**
5737** ^SQLite will never invoke xInit() more than once without an intervening
5738** call to xShutdown().
5739**
5740** ^The xCreate() method is used to construct a new cache instance.  SQLite
5741** will typically create one cache instance for each open database file,
5742** though this is not guaranteed. ^The
5743** first parameter, szPage, is the size in bytes of the pages that must
5744** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
5745** will the page size of the database file that is to be cached plus an
5746** increment (here called "R") of about 100 or 200.  ^SQLite will use the
5747** extra R bytes on each page to store metadata about the underlying
5748** database page on disk.  The value of R depends
5749** on the SQLite version, the target platform, and how SQLite was compiled.
5750** ^R is constant for a particular build of SQLite.  ^The second argument to
5751** xCreate(), bPurgeable, is true if the cache being created will
5752** be used to cache database pages of a file stored on disk, or
5753** false if it is used for an in-memory database. ^The cache implementation
5754** does not have to do anything special based with the value of bPurgeable;
5755** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
5756** never invoke xUnpin() except to deliberately delete a page.
5757** ^In other words, a cache created with bPurgeable set to false will
5758** never contain any unpinned pages.
5759**
5760** ^(The xCachesize() method may be called at any time by SQLite to set the
5761** suggested maximum cache-size (number of pages stored by) the cache
5762** instance passed as the first argument. This is the value configured using
5763** the SQLite "[PRAGMA cache_size]" command.)^  ^As with the bPurgeable
5764** parameter, the implementation is not required to do anything with this
5765** value; it is advisory only.
5766**
5767** ^The xPagecount() method should return the number of pages currently
5768** stored in the cache.
5769**
5770** ^The xFetch() method is used to fetch a page and return a pointer to it.
5771** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
5772** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
5773** mimimum key value is 1. After it has been retrieved using xFetch, the page
5774** is considered to be "pinned".
5775**
5776** ^If the requested page is already in the page cache, then the page cache
5777** implementation must return a pointer to the page buffer with its content
5778** intact.  ^(If the requested page is not already in the cache, then the
5779** behavior of the cache implementation is determined by the value of the
5780** createFlag parameter passed to xFetch, according to the following table:
5781**
5782** <table border=1 width=85% align=center>
5783** <tr><th> createFlag <th> Behaviour when page is not already in cache
5784** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
5785** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
5786**                 Otherwise return NULL.
5787** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
5788**                 NULL if allocating a new page is effectively impossible.
5789** </table>)^
5790**
5791** SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  If
5792** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
5793** attempt to unpin one or more cache pages by spilling the content of
5794** pinned pages to disk and synching the operating system disk cache. After
5795** attempting to unpin pages, the xFetch() method will be invoked again with
5796** a createFlag of 2.
5797**
5798** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
5799** as its second argument. ^(If the third parameter, discard, is non-zero,
5800** then the page should be evicted from the cache. In this case SQLite
5801** assumes that the next time the page is retrieved from the cache using
5802** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
5803** zero, then the page is considered to be unpinned. ^The cache implementation
5804** may choose to evict unpinned pages at any time.
5805**
5806** ^(The cache is not required to perform any reference counting. A single
5807** call to xUnpin() unpins the page regardless of the number of prior calls
5808** to xFetch().)^
5809**
5810** ^The xRekey() method is used to change the key value associated with the
5811** page passed as the second argument from oldKey to newKey. ^If the cache
5812** previously contains an entry associated with newKey, it should be
5813** discarded. ^Any prior cache entry associated with newKey is guaranteed not
5814** to be pinned.
5815**
5816** ^When SQLite calls the xTruncate() method, the cache must discard all
5817** existing cache entries with page numbers (keys) greater than or equal
5818** to the value of the iLimit parameter passed to xTruncate(). ^If any
5819** of these pages are pinned, they are implicitly unpinned, meaning that
5820** they can be safely discarded.
5821**
5822** ^The xDestroy() method is used to delete a cache allocated by xCreate().
5823** All resources associated with the specified cache should be freed. ^After
5824** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
5825** handle invalid, and will not use it with any other sqlite3_pcache_methods
5826** functions.
5827*/
5828typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
5829struct sqlite3_pcache_methods {
5830  void *pArg;
5831  int (*xInit)(void*);
5832  void (*xShutdown)(void*);
5833  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
5834  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
5835  int (*xPagecount)(sqlite3_pcache*);
5836  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
5837  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
5838  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
5839  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
5840  void (*xDestroy)(sqlite3_pcache*);
5841};
5842
5843/*
5844** CAPI3REF: Online Backup Object
5845** EXPERIMENTAL
5846**
5847** The sqlite3_backup object records state information about an ongoing
5848** online backup operation.  ^The sqlite3_backup object is created by
5849** a call to [sqlite3_backup_init()] and is destroyed by a call to
5850** [sqlite3_backup_finish()].
5851**
5852** See Also: [Using the SQLite Online Backup API]
5853*/
5854typedef struct sqlite3_backup sqlite3_backup;
5855
5856/*
5857** CAPI3REF: Online Backup API.
5858** EXPERIMENTAL
5859**
5860** The backup API copies the content of one database into another.
5861** It is useful either for creating backups of databases or
5862** for copying in-memory databases to or from persistent files.
5863**
5864** See Also: [Using the SQLite Online Backup API]
5865**
5866** ^Exclusive access is required to the destination database for the
5867** duration of the operation. ^However the source database is only
5868** read-locked while it is actually being read; it is not locked
5869** continuously for the entire backup operation. ^Thus, the backup may be
5870** performed on a live source database without preventing other users from
5871** reading or writing to the source database while the backup is underway.
5872**
5873** ^(To perform a backup operation:
5874**   <ol>
5875**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
5876**         backup,
5877**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
5878**         the data between the two databases, and finally
5879**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
5880**         associated with the backup operation.
5881**   </ol>)^
5882** There should be exactly one call to sqlite3_backup_finish() for each
5883** successful call to sqlite3_backup_init().
5884**
5885** <b>sqlite3_backup_init()</b>
5886**
5887** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
5888** [database connection] associated with the destination database
5889** and the database name, respectively.
5890** ^The database name is "main" for the main database, "temp" for the
5891** temporary database, or the name specified after the AS keyword in
5892** an [ATTACH] statement for an attached database.
5893** ^The S and M arguments passed to
5894** sqlite3_backup_init(D,N,S,M) identify the [database connection]
5895** and database name of the source database, respectively.
5896** ^The source and destination [database connections] (parameters S and D)
5897** must be different or else sqlite3_backup_init(D,N,S,M) will file with
5898** an error.
5899**
5900** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
5901** returned and an error code and error message are store3d in the
5902** destination [database connection] D.
5903** ^The error code and message for the failed call to sqlite3_backup_init()
5904** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
5905** [sqlite3_errmsg16()] functions.
5906** ^A successful call to sqlite3_backup_init() returns a pointer to an
5907** [sqlite3_backup] object.
5908** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
5909** sqlite3_backup_finish() functions to perform the specified backup
5910** operation.
5911**
5912** <b>sqlite3_backup_step()</b>
5913**
5914** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
5915** the source and destination databases specified by [sqlite3_backup] object B.
5916** ^If N is negative, all remaining source pages are copied.
5917** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
5918** are still more pages to be copied, then the function resturns [SQLITE_OK].
5919** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
5920** from source to destination, then it returns [SQLITE_DONE].
5921** ^If an error occurs while running sqlite3_backup_step(B,N),
5922** then an [error code] is returned. ^As well as [SQLITE_OK] and
5923** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
5924** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
5925** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
5926**
5927** ^The sqlite3_backup_step() might return [SQLITE_READONLY] if the destination
5928** database was opened read-only or if
5929** the destination is an in-memory database with a different page size
5930** from the source database.
5931**
5932** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
5933** the [sqlite3_busy_handler | busy-handler function]
5934** is invoked (if one is specified). ^If the
5935** busy-handler returns non-zero before the lock is available, then
5936** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
5937** sqlite3_backup_step() can be retried later. ^If the source
5938** [database connection]
5939** is being used to write to the source database when sqlite3_backup_step()
5940** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
5941** case the call to sqlite3_backup_step() can be retried later on. ^(If
5942** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
5943** [SQLITE_READONLY] is returned, then
5944** there is no point in retrying the call to sqlite3_backup_step(). These
5945** errors are considered fatal.)^  The application must accept
5946** that the backup operation has failed and pass the backup operation handle
5947** to the sqlite3_backup_finish() to release associated resources.
5948**
5949** ^The first call to sqlite3_backup_step() obtains an exclusive lock
5950** on the destination file. ^The exclusive lock is not released until either
5951** sqlite3_backup_finish() is called or the backup operation is complete
5952** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
5953** sqlite3_backup_step() obtains a [shared lock] on the source database that
5954** lasts for the duration of the sqlite3_backup_step() call.
5955** ^Because the source database is not locked between calls to
5956** sqlite3_backup_step(), the source database may be modified mid-way
5957** through the backup process.  ^If the source database is modified by an
5958** external process or via a database connection other than the one being
5959** used by the backup operation, then the backup will be automatically
5960** restarted by the next call to sqlite3_backup_step(). ^If the source
5961** database is modified by the using the same database connection as is used
5962** by the backup operation, then the backup database is automatically
5963** updated at the same time.
5964**
5965** <b>sqlite3_backup_finish()</b>
5966**
5967** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
5968** application wishes to abandon the backup operation, the application
5969** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
5970** ^The sqlite3_backup_finish() interfaces releases all
5971** resources associated with the [sqlite3_backup] object.
5972** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
5973** active write-transaction on the destination database is rolled back.
5974** The [sqlite3_backup] object is invalid
5975** and may not be used following a call to sqlite3_backup_finish().
5976**
5977** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
5978** sqlite3_backup_step() errors occurred, regardless or whether or not
5979** sqlite3_backup_step() completed.
5980** ^If an out-of-memory condition or IO error occurred during any prior
5981** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
5982** sqlite3_backup_finish() returns the corresponding [error code].
5983**
5984** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
5985** is not a permanent error and does not affect the return value of
5986** sqlite3_backup_finish().
5987**
5988** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
5989**
5990** ^Each call to sqlite3_backup_step() sets two values inside
5991** the [sqlite3_backup] object: the number of pages still to be backed
5992** up and the total number of pages in the source databae file.
5993** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
5994** retrieve these two values, respectively.
5995**
5996** ^The values returned by these functions are only updated by
5997** sqlite3_backup_step(). ^If the source database is modified during a backup
5998** operation, then the values are not updated to account for any extra
5999** pages that need to be updated or the size of the source database file
6000** changing.
6001**
6002** <b>Concurrent Usage of Database Handles</b>
6003**
6004** ^The source [database connection] may be used by the application for other
6005** purposes while a backup operation is underway or being initialized.
6006** ^If SQLite is compiled and configured to support threadsafe database
6007** connections, then the source database connection may be used concurrently
6008** from within other threads.
6009**
6010** However, the application must guarantee that the destination
6011** [database connection] is not passed to any other API (by any thread) after
6012** sqlite3_backup_init() is called and before the corresponding call to
6013** sqlite3_backup_finish().  SQLite does not currently check to see
6014** if the application incorrectly accesses the destination [database connection]
6015** and so no error code is reported, but the operations may malfunction
6016** nevertheless.  Use of the destination database connection while a
6017** backup is in progress might also also cause a mutex deadlock.
6018**
6019** If running in [shared cache mode], the application must
6020** guarantee that the shared cache used by the destination database
6021** is not accessed while the backup is running. In practice this means
6022** that the application must guarantee that the disk file being
6023** backed up to is not accessed by any connection within the process,
6024** not just the specific connection that was passed to sqlite3_backup_init().
6025**
6026** The [sqlite3_backup] object itself is partially threadsafe. Multiple
6027** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6028** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6029** APIs are not strictly speaking threadsafe. If they are invoked at the
6030** same time as another thread is invoking sqlite3_backup_step() it is
6031** possible that they return invalid values.
6032*/
6033SQLITE_API sqlite3_backup *sqlite3_backup_init(
6034  sqlite3 *pDest,                        /* Destination database handle */
6035  const char *zDestName,                 /* Destination database name */
6036  sqlite3 *pSource,                      /* Source database handle */
6037  const char *zSourceName                /* Source database name */
6038);
6039SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6040SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6041SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6042SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6043
6044/*
6045** CAPI3REF: Unlock Notification
6046** EXPERIMENTAL
6047**
6048** ^When running in shared-cache mode, a database operation may fail with
6049** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6050** individual tables within the shared-cache cannot be obtained. See
6051** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
6052** ^This API may be used to register a callback that SQLite will invoke
6053** when the connection currently holding the required lock relinquishes it.
6054** ^This API is only available if the library was compiled with the
6055** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6056**
6057** See Also: [Using the SQLite Unlock Notification Feature].
6058**
6059** ^Shared-cache locks are released when a database connection concludes
6060** its current transaction, either by committing it or rolling it back.
6061**
6062** ^When a connection (known as the blocked connection) fails to obtain a
6063** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6064** identity of the database connection (the blocking connection) that
6065** has locked the required resource is stored internally. ^After an
6066** application receives an SQLITE_LOCKED error, it may call the
6067** sqlite3_unlock_notify() method with the blocked connection handle as
6068** the first argument to register for a callback that will be invoked
6069** when the blocking connections current transaction is concluded. ^The
6070** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6071** call that concludes the blocking connections transaction.
6072**
6073** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6074** there is a chance that the blocking connection will have already
6075** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6076** If this happens, then the specified callback is invoked immediately,
6077** from within the call to sqlite3_unlock_notify().)^
6078**
6079** ^If the blocked connection is attempting to obtain a write-lock on a
6080** shared-cache table, and more than one other connection currently holds
6081** a read-lock on the same table, then SQLite arbitrarily selects one of
6082** the other connections to use as the blocking connection.
6083**
6084** ^(There may be at most one unlock-notify callback registered by a
6085** blocked connection. If sqlite3_unlock_notify() is called when the
6086** blocked connection already has a registered unlock-notify callback,
6087** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6088** called with a NULL pointer as its second argument, then any existing
6089** unlock-notify callback is cancelled. ^The blocked connections
6090** unlock-notify callback may also be canceled by closing the blocked
6091** connection using [sqlite3_close()].
6092**
6093** The unlock-notify callback is not reentrant. If an application invokes
6094** any sqlite3_xxx API functions from within an unlock-notify callback, a
6095** crash or deadlock may be the result.
6096**
6097** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6098** returns SQLITE_OK.
6099**
6100** <b>Callback Invocation Details</b>
6101**
6102** When an unlock-notify callback is registered, the application provides a
6103** single void* pointer that is passed to the callback when it is invoked.
6104** However, the signature of the callback function allows SQLite to pass
6105** it an array of void* context pointers. The first argument passed to
6106** an unlock-notify callback is a pointer to an array of void* pointers,
6107** and the second is the number of entries in the array.
6108**
6109** When a blocking connections transaction is concluded, there may be
6110** more than one blocked connection that has registered for an unlock-notify
6111** callback. ^If two or more such blocked connections have specified the
6112** same callback function, then instead of invoking the callback function
6113** multiple times, it is invoked once with the set of void* context pointers
6114** specified by the blocked connections bundled together into an array.
6115** This gives the application an opportunity to prioritize any actions
6116** related to the set of unblocked database connections.
6117**
6118** <b>Deadlock Detection</b>
6119**
6120** Assuming that after registering for an unlock-notify callback a
6121** database waits for the callback to be issued before taking any further
6122** action (a reasonable assumption), then using this API may cause the
6123** application to deadlock. For example, if connection X is waiting for
6124** connection Y's transaction to be concluded, and similarly connection
6125** Y is waiting on connection X's transaction, then neither connection
6126** will proceed and the system may remain deadlocked indefinitely.
6127**
6128** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6129** detection. ^If a given call to sqlite3_unlock_notify() would put the
6130** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6131** unlock-notify callback is registered. The system is said to be in
6132** a deadlocked state if connection A has registered for an unlock-notify
6133** callback on the conclusion of connection B's transaction, and connection
6134** B has itself registered for an unlock-notify callback when connection
6135** A's transaction is concluded. ^Indirect deadlock is also detected, so
6136** the system is also considered to be deadlocked if connection B has
6137** registered for an unlock-notify callback on the conclusion of connection
6138** C's transaction, where connection C is waiting on connection A. ^Any
6139** number of levels of indirection are allowed.
6140**
6141** <b>The "DROP TABLE" Exception</b>
6142**
6143** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
6144** always appropriate to call sqlite3_unlock_notify(). There is however,
6145** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6146** SQLite checks if there are any currently executing SELECT statements
6147** that belong to the same connection. If there are, SQLITE_LOCKED is
6148** returned. In this case there is no "blocking connection", so invoking
6149** sqlite3_unlock_notify() results in the unlock-notify callback being
6150** invoked immediately. If the application then re-attempts the "DROP TABLE"
6151** or "DROP INDEX" query, an infinite loop might be the result.
6152**
6153** One way around this problem is to check the extended error code returned
6154** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6155** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6156** the special "DROP TABLE/INDEX" case, the extended error code is just
6157** SQLITE_LOCKED.)^
6158*/
6159SQLITE_API int sqlite3_unlock_notify(
6160  sqlite3 *pBlocked,                          /* Waiting connection */
6161  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6162  void *pNotifyArg                            /* Argument to pass to xNotify */
6163);
6164
6165
6166/*
6167** CAPI3REF: String Comparison
6168** EXPERIMENTAL
6169**
6170** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6171** compare the contents of two buffers containing UTF-8 strings in a
6172** case-indendent fashion, using the same definition of case independence
6173** that SQLite uses internally when comparing identifiers.
6174*/
6175SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6176
6177/*
6178** Undo the hack that converts floating point types to integer for
6179** builds on processors without floating point support.
6180*/
6181#ifdef SQLITE_OMIT_FLOATING_POINT
6182# undef double
6183#endif
6184
6185#if 0
6186}  /* End of the 'extern "C"' block */
6187#endif
6188#endif
6189
6190
6191/************** End of sqlite3.h *********************************************/
6192/************** Continuing where we left off in sqliteInt.h ******************/
6193/************** Include hash.h in the middle of sqliteInt.h ******************/
6194/************** Begin file hash.h ********************************************/
6195/*
6196** 2001 September 22
6197**
6198** The author disclaims copyright to this source code.  In place of
6199** a legal notice, here is a blessing:
6200**
6201**    May you do good and not evil.
6202**    May you find forgiveness for yourself and forgive others.
6203**    May you share freely, never taking more than you give.
6204**
6205*************************************************************************
6206** This is the header file for the generic hash-table implemenation
6207** used in SQLite.
6208*/
6209#ifndef _SQLITE_HASH_H_
6210#define _SQLITE_HASH_H_
6211
6212/* Forward declarations of structures. */
6213typedef struct Hash Hash;
6214typedef struct HashElem HashElem;
6215
6216/* A complete hash table is an instance of the following structure.
6217** The internals of this structure are intended to be opaque -- client
6218** code should not attempt to access or modify the fields of this structure
6219** directly.  Change this structure only by using the routines below.
6220** However, some of the "procedures" and "functions" for modifying and
6221** accessing this structure are really macros, so we can't really make
6222** this structure opaque.
6223**
6224** All elements of the hash table are on a single doubly-linked list.
6225** Hash.first points to the head of this list.
6226**
6227** There are Hash.htsize buckets.  Each bucket points to a spot in
6228** the global doubly-linked list.  The contents of the bucket are the
6229** element pointed to plus the next _ht.count-1 elements in the list.
6230**
6231** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
6232** by a linear search of the global list.  For small tables, the
6233** Hash.ht table is never allocated because if there are few elements
6234** in the table, it is faster to do a linear search than to manage
6235** the hash table.
6236*/
6237struct Hash {
6238  unsigned int htsize;      /* Number of buckets in the hash table */
6239  unsigned int count;       /* Number of entries in this table */
6240  HashElem *first;          /* The first element of the array */
6241  struct _ht {              /* the hash table */
6242    int count;                 /* Number of entries with this hash */
6243    HashElem *chain;           /* Pointer to first entry with this hash */
6244  } *ht;
6245};
6246
6247/* Each element in the hash table is an instance of the following
6248** structure.  All elements are stored on a single doubly-linked list.
6249**
6250** Again, this structure is intended to be opaque, but it can't really
6251** be opaque because it is used by macros.
6252*/
6253struct HashElem {
6254  HashElem *next, *prev;       /* Next and previous elements in the table */
6255  void *data;                  /* Data associated with this element */
6256  const char *pKey; int nKey;  /* Key associated with this element */
6257};
6258
6259/*
6260** Access routines.  To delete, insert a NULL pointer.
6261*/
6262SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6263SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6264SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
6265SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6266
6267/*
6268** Macros for looping over all elements of a hash table.  The idiom is
6269** like this:
6270**
6271**   Hash h;
6272**   HashElem *p;
6273**   ...
6274**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6275**     SomeStructure *pData = sqliteHashData(p);
6276**     // do something with pData
6277**   }
6278*/
6279#define sqliteHashFirst(H)  ((H)->first)
6280#define sqliteHashNext(E)   ((E)->next)
6281#define sqliteHashData(E)   ((E)->data)
6282/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
6283/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
6284
6285/*
6286** Number of entries in a hash table
6287*/
6288/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
6289
6290#endif /* _SQLITE_HASH_H_ */
6291
6292/************** End of hash.h ************************************************/
6293/************** Continuing where we left off in sqliteInt.h ******************/
6294/************** Include parse.h in the middle of sqliteInt.h *****************/
6295/************** Begin file parse.h *******************************************/
6296#define TK_SEMI                            1
6297#define TK_EXPLAIN                         2
6298#define TK_QUERY                           3
6299#define TK_PLAN                            4
6300#define TK_BEGIN                           5
6301#define TK_TRANSACTION                     6
6302#define TK_DEFERRED                        7
6303#define TK_IMMEDIATE                       8
6304#define TK_EXCLUSIVE                       9
6305#define TK_COMMIT                         10
6306#define TK_END                            11
6307#define TK_ROLLBACK                       12
6308#define TK_SAVEPOINT                      13
6309#define TK_RELEASE                        14
6310#define TK_TO                             15
6311#define TK_TABLE                          16
6312#define TK_CREATE                         17
6313#define TK_IF                             18
6314#define TK_NOT                            19
6315#define TK_EXISTS                         20
6316#define TK_TEMP                           21
6317#define TK_LP                             22
6318#define TK_RP                             23
6319#define TK_AS                             24
6320#define TK_COMMA                          25
6321#define TK_ID                             26
6322#define TK_INDEXED                        27
6323#define TK_ABORT                          28
6324#define TK_ACTION                         29
6325#define TK_AFTER                          30
6326#define TK_ANALYZE                        31
6327#define TK_ASC                            32
6328#define TK_ATTACH                         33
6329#define TK_BEFORE                         34
6330#define TK_BY                             35
6331#define TK_CASCADE                        36
6332#define TK_CAST                           37
6333#define TK_COLUMNKW                       38
6334#define TK_CONFLICT                       39
6335#define TK_DATABASE                       40
6336#define TK_DESC                           41
6337#define TK_DETACH                         42
6338#define TK_EACH                           43
6339#define TK_FAIL                           44
6340#define TK_FOR                            45
6341#define TK_IGNORE                         46
6342#define TK_INITIALLY                      47
6343#define TK_INSTEAD                        48
6344#define TK_LIKE_KW                        49
6345#define TK_MATCH                          50
6346#define TK_NO                             51
6347#define TK_KEY                            52
6348#define TK_OF                             53
6349#define TK_OFFSET                         54
6350#define TK_PRAGMA                         55
6351#define TK_RAISE                          56
6352#define TK_REPLACE                        57
6353#define TK_RESTRICT                       58
6354#define TK_ROW                            59
6355#define TK_TRIGGER                        60
6356#define TK_VACUUM                         61
6357#define TK_VIEW                           62
6358#define TK_VIRTUAL                        63
6359#define TK_REINDEX                        64
6360#define TK_RENAME                         65
6361#define TK_CTIME_KW                       66
6362#define TK_ANY                            67
6363#define TK_OR                             68
6364#define TK_AND                            69
6365#define TK_IS                             70
6366#define TK_BETWEEN                        71
6367#define TK_IN                             72
6368#define TK_ISNULL                         73
6369#define TK_NOTNULL                        74
6370#define TK_NE                             75
6371#define TK_EQ                             76
6372#define TK_GT                             77
6373#define TK_LE                             78
6374#define TK_LT                             79
6375#define TK_GE                             80
6376#define TK_ESCAPE                         81
6377#define TK_BITAND                         82
6378#define TK_BITOR                          83
6379#define TK_LSHIFT                         84
6380#define TK_RSHIFT                         85
6381#define TK_PLUS                           86
6382#define TK_MINUS                          87
6383#define TK_STAR                           88
6384#define TK_SLASH                          89
6385#define TK_REM                            90
6386#define TK_CONCAT                         91
6387#define TK_COLLATE                        92
6388#define TK_BITNOT                         93
6389#define TK_STRING                         94
6390#define TK_JOIN_KW                        95
6391#define TK_CONSTRAINT                     96
6392#define TK_DEFAULT                        97
6393#define TK_NULL                           98
6394#define TK_PRIMARY                        99
6395#define TK_UNIQUE                         100
6396#define TK_CHECK                          101
6397#define TK_REFERENCES                     102
6398#define TK_AUTOINCR                       103
6399#define TK_ON                             104
6400#define TK_INSERT                         105
6401#define TK_DELETE                         106
6402#define TK_UPDATE                         107
6403#define TK_SET                            108
6404#define TK_DEFERRABLE                     109
6405#define TK_FOREIGN                        110
6406#define TK_DROP                           111
6407#define TK_UNION                          112
6408#define TK_ALL                            113
6409#define TK_EXCEPT                         114
6410#define TK_INTERSECT                      115
6411#define TK_SELECT                         116
6412#define TK_DISTINCT                       117
6413#define TK_DOT                            118
6414#define TK_FROM                           119
6415#define TK_JOIN                           120
6416#define TK_USING                          121
6417#define TK_ORDER                          122
6418#define TK_GROUP                          123
6419#define TK_HAVING                         124
6420#define TK_LIMIT                          125
6421#define TK_WHERE                          126
6422#define TK_INTO                           127
6423#define TK_VALUES                         128
6424#define TK_INTEGER                        129
6425#define TK_FLOAT                          130
6426#define TK_BLOB                           131
6427#define TK_REGISTER                       132
6428#define TK_VARIABLE                       133
6429#define TK_CASE                           134
6430#define TK_WHEN                           135
6431#define TK_THEN                           136
6432#define TK_ELSE                           137
6433#define TK_INDEX                          138
6434#define TK_ALTER                          139
6435#define TK_ADD                            140
6436#define TK_TO_TEXT                        141
6437#define TK_TO_BLOB                        142
6438#define TK_TO_NUMERIC                     143
6439#define TK_TO_INT                         144
6440#define TK_TO_REAL                        145
6441#define TK_ISNOT                          146
6442#define TK_END_OF_FILE                    147
6443#define TK_ILLEGAL                        148
6444#define TK_SPACE                          149
6445#define TK_UNCLOSED_STRING                150
6446#define TK_FUNCTION                       151
6447#define TK_COLUMN                         152
6448#define TK_AGG_FUNCTION                   153
6449#define TK_AGG_COLUMN                     154
6450#define TK_CONST_FUNC                     155
6451#define TK_UMINUS                         156
6452#define TK_UPLUS                          157
6453
6454/************** End of parse.h ***********************************************/
6455/************** Continuing where we left off in sqliteInt.h ******************/
6456#include <stdio.h>
6457#include <stdlib.h>
6458#include <string.h>
6459#include <assert.h>
6460#include <stddef.h>
6461
6462/*
6463** If compiling for a processor that lacks floating point support,
6464** substitute integer for floating-point
6465*/
6466#ifdef SQLITE_OMIT_FLOATING_POINT
6467# define double sqlite_int64
6468# define LONGDOUBLE_TYPE sqlite_int64
6469# ifndef SQLITE_BIG_DBL
6470#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
6471# endif
6472# define SQLITE_OMIT_DATETIME_FUNCS 1
6473# define SQLITE_OMIT_TRACE 1
6474# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
6475# undef SQLITE_HAVE_ISNAN
6476#endif
6477#ifndef SQLITE_BIG_DBL
6478# define SQLITE_BIG_DBL (1e99)
6479#endif
6480
6481/*
6482** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
6483** afterward. Having this macro allows us to cause the C compiler
6484** to omit code used by TEMP tables without messy #ifndef statements.
6485*/
6486#ifdef SQLITE_OMIT_TEMPDB
6487#define OMIT_TEMPDB 1
6488#else
6489#define OMIT_TEMPDB 0
6490#endif
6491
6492/*
6493** If the following macro is set to 1, then NULL values are considered
6494** distinct when determining whether or not two entries are the same
6495** in a UNIQUE index.  This is the way PostgreSQL, Oracle, DB2, MySQL,
6496** OCELOT, and Firebird all work.  The SQL92 spec explicitly says this
6497** is the way things are suppose to work.
6498**
6499** If the following macro is set to 0, the NULLs are indistinct for
6500** a UNIQUE index.  In this mode, you can only have a single NULL entry
6501** for a column declared UNIQUE.  This is the way Informix and SQL Server
6502** work.
6503*/
6504#define NULL_DISTINCT_FOR_UNIQUE 1
6505
6506/*
6507** The "file format" number is an integer that is incremented whenever
6508** the VDBE-level file format changes.  The following macros define the
6509** the default file format for new databases and the maximum file format
6510** that the library can read.
6511*/
6512#define SQLITE_MAX_FILE_FORMAT 4
6513#ifndef SQLITE_DEFAULT_FILE_FORMAT
6514# define SQLITE_DEFAULT_FILE_FORMAT 1
6515#endif
6516
6517#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
6518# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
6519#endif
6520
6521/*
6522** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
6523** on the command-line
6524*/
6525#ifndef SQLITE_TEMP_STORE
6526# define SQLITE_TEMP_STORE 1
6527#endif
6528
6529/*
6530** GCC does not define the offsetof() macro so we'll have to do it
6531** ourselves.
6532*/
6533#ifndef offsetof
6534#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
6535#endif
6536
6537/*
6538** Check to see if this machine uses EBCDIC.  (Yes, believe it or
6539** not, there are still machines out there that use EBCDIC.)
6540*/
6541#if 'A' == '\301'
6542# define SQLITE_EBCDIC 1
6543#else
6544# define SQLITE_ASCII 1
6545#endif
6546
6547/*
6548** Integers of known sizes.  These typedefs might change for architectures
6549** where the sizes very.  Preprocessor macros are available so that the
6550** types can be conveniently redefined at compile-type.  Like this:
6551**
6552**         cc '-DUINTPTR_TYPE=long long int' ...
6553*/
6554#ifndef UINT32_TYPE
6555# ifdef HAVE_UINT32_T
6556#  define UINT32_TYPE uint32_t
6557# else
6558#  define UINT32_TYPE unsigned int
6559# endif
6560#endif
6561#ifndef UINT16_TYPE
6562# ifdef HAVE_UINT16_T
6563#  define UINT16_TYPE uint16_t
6564# else
6565#  define UINT16_TYPE unsigned short int
6566# endif
6567#endif
6568#ifndef INT16_TYPE
6569# ifdef HAVE_INT16_T
6570#  define INT16_TYPE int16_t
6571# else
6572#  define INT16_TYPE short int
6573# endif
6574#endif
6575#ifndef UINT8_TYPE
6576# ifdef HAVE_UINT8_T
6577#  define UINT8_TYPE uint8_t
6578# else
6579#  define UINT8_TYPE unsigned char
6580# endif
6581#endif
6582#ifndef INT8_TYPE
6583# ifdef HAVE_INT8_T
6584#  define INT8_TYPE int8_t
6585# else
6586#  define INT8_TYPE signed char
6587# endif
6588#endif
6589#ifndef LONGDOUBLE_TYPE
6590# define LONGDOUBLE_TYPE long double
6591#endif
6592typedef sqlite_int64 i64;          /* 8-byte signed integer */
6593typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
6594typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6595typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6596typedef INT16_TYPE i16;            /* 2-byte signed integer */
6597typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
6598typedef INT8_TYPE i8;              /* 1-byte signed integer */
6599
6600/*
6601** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
6602** that can be stored in a u32 without loss of data.  The value
6603** is 0x00000000ffffffff.  But because of quirks of some compilers, we
6604** have to specify the value in the less intuitive manner shown:
6605*/
6606#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
6607
6608/*
6609** Macros to determine whether the machine is big or little endian,
6610** evaluated at runtime.
6611*/
6612#ifdef SQLITE_AMALGAMATION
6613SQLITE_PRIVATE const int sqlite3one = 1;
6614#else
6615SQLITE_PRIVATE const int sqlite3one;
6616#endif
6617#if defined(i386) || defined(__i386__) || defined(_M_IX86)\
6618                             || defined(__x86_64) || defined(__x86_64__)
6619# define SQLITE_BIGENDIAN    0
6620# define SQLITE_LITTLEENDIAN 1
6621# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
6622#else
6623# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
6624# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
6625# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
6626#endif
6627
6628/*
6629** Constants for the largest and smallest possible 64-bit signed integers.
6630** These macros are designed to work correctly on both 32-bit and 64-bit
6631** compilers.
6632*/
6633#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
6634#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
6635
6636/*
6637** Round up a number to the next larger multiple of 8.  This is used
6638** to force 8-byte alignment on 64-bit architectures.
6639*/
6640#define ROUND8(x)     (((x)+7)&~7)
6641
6642/*
6643** Round down to the nearest multiple of 8
6644*/
6645#define ROUNDDOWN8(x) ((x)&~7)
6646
6647/*
6648** Assert that the pointer X is aligned to an 8-byte boundary.  This
6649** macro is used only within assert() to verify that the code gets
6650** all alignment restrictions correct.
6651**
6652** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
6653** underlying malloc() implemention might return us 4-byte aligned
6654** pointers.  In that case, only verify 4-byte alignment.
6655*/
6656#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
6657# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
6658#else
6659# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
6660#endif
6661
6662
6663/*
6664** An instance of the following structure is used to store the busy-handler
6665** callback for a given sqlite handle.
6666**
6667** The sqlite.busyHandler member of the sqlite struct contains the busy
6668** callback for the database handle. Each pager opened via the sqlite
6669** handle is passed a pointer to sqlite.busyHandler. The busy-handler
6670** callback is currently invoked only from within pager.c.
6671*/
6672typedef struct BusyHandler BusyHandler;
6673struct BusyHandler {
6674  int (*xFunc)(void *,int);  /* The busy callback */
6675  void *pArg;                /* First arg to busy callback */
6676  int nBusy;                 /* Incremented with each busy call */
6677};
6678
6679/*
6680** Name of the master database table.  The master database table
6681** is a special table that holds the names and attributes of all
6682** user tables and indices.
6683*/
6684#define MASTER_NAME       "sqlite_master"
6685#define TEMP_MASTER_NAME  "sqlite_temp_master"
6686
6687/*
6688** The root-page of the master database table.
6689*/
6690#define MASTER_ROOT       1
6691
6692/*
6693** The name of the schema table.
6694*/
6695#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
6696
6697/*
6698** A convenience macro that returns the number of elements in
6699** an array.
6700*/
6701#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
6702
6703/*
6704** The following value as a destructor means to use sqlite3DbFree().
6705** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
6706*/
6707#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
6708
6709/*
6710** When SQLITE_OMIT_WSD is defined, it means that the target platform does
6711** not support Writable Static Data (WSD) such as global and static variables.
6712** All variables must either be on the stack or dynamically allocated from
6713** the heap.  When WSD is unsupported, the variable declarations scattered
6714** throughout the SQLite code must become constants instead.  The SQLITE_WSD
6715** macro is used for this purpose.  And instead of referencing the variable
6716** directly, we use its constant as a key to lookup the run-time allocated
6717** buffer that holds real variable.  The constant is also the initializer
6718** for the run-time allocated buffer.
6719**
6720** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
6721** macros become no-ops and have zero performance impact.
6722*/
6723#ifdef SQLITE_OMIT_WSD
6724  #define SQLITE_WSD const
6725  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
6726  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
6727SQLITE_API   int sqlite3_wsd_init(int N, int J);
6728SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
6729#else
6730  #define SQLITE_WSD
6731  #define GLOBAL(t,v) v
6732  #define sqlite3GlobalConfig sqlite3Config
6733#endif
6734
6735/*
6736** The following macros are used to suppress compiler warnings and to
6737** make it clear to human readers when a function parameter is deliberately
6738** left unused within the body of a function. This usually happens when
6739** a function is called via a function pointer. For example the
6740** implementation of an SQL aggregate step callback may not use the
6741** parameter indicating the number of arguments passed to the aggregate,
6742** if it knows that this is enforced elsewhere.
6743**
6744** When a function parameter is not used at all within the body of a function,
6745** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
6746** However, these macros may also be used to suppress warnings related to
6747** parameters that may or may not be used depending on compilation options.
6748** For example those parameters only used in assert() statements. In these
6749** cases the parameters are named as per the usual conventions.
6750*/
6751#define UNUSED_PARAMETER(x) (void)(x)
6752#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
6753
6754/*
6755** Forward references to structures
6756*/
6757typedef struct AggInfo AggInfo;
6758typedef struct AuthContext AuthContext;
6759typedef struct AutoincInfo AutoincInfo;
6760typedef struct Bitvec Bitvec;
6761typedef struct RowSet RowSet;
6762typedef struct CollSeq CollSeq;
6763typedef struct Column Column;
6764typedef struct Db Db;
6765typedef struct Schema Schema;
6766typedef struct Expr Expr;
6767typedef struct ExprList ExprList;
6768typedef struct ExprSpan ExprSpan;
6769typedef struct FKey FKey;
6770typedef struct FuncDef FuncDef;
6771typedef struct FuncDefHash FuncDefHash;
6772typedef struct IdList IdList;
6773typedef struct Index Index;
6774typedef struct IndexSample IndexSample;
6775typedef struct KeyClass KeyClass;
6776typedef struct KeyInfo KeyInfo;
6777typedef struct Lookaside Lookaside;
6778typedef struct LookasideSlot LookasideSlot;
6779typedef struct Module Module;
6780typedef struct NameContext NameContext;
6781typedef struct Parse Parse;
6782typedef struct Savepoint Savepoint;
6783typedef struct Select Select;
6784typedef struct SrcList SrcList;
6785typedef struct StrAccum StrAccum;
6786typedef struct Table Table;
6787typedef struct TableLock TableLock;
6788typedef struct Token Token;
6789typedef struct TriggerPrg TriggerPrg;
6790typedef struct TriggerStep TriggerStep;
6791typedef struct Trigger Trigger;
6792typedef struct UnpackedRecord UnpackedRecord;
6793typedef struct VTable VTable;
6794typedef struct Walker Walker;
6795typedef struct WherePlan WherePlan;
6796typedef struct WhereInfo WhereInfo;
6797typedef struct WhereLevel WhereLevel;
6798
6799/*
6800** Defer sourcing vdbe.h and btree.h until after the "u8" and
6801** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
6802** pointer types (i.e. FuncDef) defined above.
6803*/
6804/************** Include btree.h in the middle of sqliteInt.h *****************/
6805/************** Begin file btree.h *******************************************/
6806/*
6807** 2001 September 15
6808**
6809** The author disclaims copyright to this source code.  In place of
6810** a legal notice, here is a blessing:
6811**
6812**    May you do good and not evil.
6813**    May you find forgiveness for yourself and forgive others.
6814**    May you share freely, never taking more than you give.
6815**
6816*************************************************************************
6817** This header file defines the interface that the sqlite B-Tree file
6818** subsystem.  See comments in the source code for a detailed description
6819** of what each interface routine does.
6820*/
6821#ifndef _BTREE_H_
6822#define _BTREE_H_
6823
6824/* TODO: This definition is just included so other modules compile. It
6825** needs to be revisited.
6826*/
6827#define SQLITE_N_BTREE_META 10
6828
6829/*
6830** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
6831** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
6832*/
6833#ifndef SQLITE_DEFAULT_AUTOVACUUM
6834  #define SQLITE_DEFAULT_AUTOVACUUM 0
6835#endif
6836
6837#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
6838#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
6839#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
6840
6841/*
6842** Forward declarations of structure
6843*/
6844typedef struct Btree Btree;
6845typedef struct BtCursor BtCursor;
6846typedef struct BtShared BtShared;
6847typedef struct BtreeMutexArray BtreeMutexArray;
6848
6849/*
6850** This structure records all of the Btrees that need to hold
6851** a mutex before we enter sqlite3VdbeExec().  The Btrees are
6852** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
6853** we can always lock and unlock them all quickly.
6854*/
6855struct BtreeMutexArray {
6856  int nMutex;
6857  Btree *aBtree[SQLITE_MAX_ATTACHED+1];
6858};
6859
6860
6861SQLITE_PRIVATE int sqlite3BtreeOpen(
6862  const char *zFilename,   /* Name of database file to open */
6863  sqlite3 *db,             /* Associated database connection */
6864  Btree **ppBtree,         /* Return open Btree* here */
6865  int flags,               /* Flags */
6866  int vfsFlags             /* Flags passed through to VFS open */
6867);
6868
6869/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
6870** following values.
6871**
6872** NOTE:  These values must match the corresponding PAGER_ values in
6873** pager.h.
6874*/
6875#define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
6876#define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
6877#define BTREE_MEMORY        4  /* In-memory DB.  No argument */
6878#define BTREE_READONLY      8  /* Open the database in read-only mode */
6879#define BTREE_READWRITE    16  /* Open for both reading and writing */
6880#define BTREE_CREATE       32  /* Create the database if it does not exist */
6881
6882SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
6883SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
6884SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
6885SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
6886SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
6887SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
6888SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
6889SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
6890SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
6891SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
6892SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
6893SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
6894SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
6895SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
6896SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
6897SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
6898SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
6899SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
6900SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
6901SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
6902SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
6903SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
6904SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
6905SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
6906
6907SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
6908SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
6909SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
6910
6911SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
6912
6913/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
6914** of the following flags:
6915*/
6916#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
6917#define BTREE_ZERODATA   2    /* Table has keys only - no data */
6918#define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
6919
6920SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
6921SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
6922SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
6923
6924SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
6925SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
6926
6927/*
6928** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
6929** should be one of the following values. The integer values are assigned
6930** to constants so that the offset of the corresponding field in an
6931** SQLite database header may be found using the following formula:
6932**
6933**   offset = 36 + (idx * 4)
6934**
6935** For example, the free-page-count field is located at byte offset 36 of
6936** the database file header. The incr-vacuum-flag field is located at
6937** byte offset 64 (== 36+4*7).
6938*/
6939#define BTREE_FREE_PAGE_COUNT     0
6940#define BTREE_SCHEMA_VERSION      1
6941#define BTREE_FILE_FORMAT         2
6942#define BTREE_DEFAULT_CACHE_SIZE  3
6943#define BTREE_LARGEST_ROOT_PAGE   4
6944#define BTREE_TEXT_ENCODING       5
6945#define BTREE_USER_VERSION        6
6946#define BTREE_INCR_VACUUM         7
6947
6948SQLITE_PRIVATE int sqlite3BtreeCursor(
6949  Btree*,                              /* BTree containing table to open */
6950  int iTable,                          /* Index of root page */
6951  int wrFlag,                          /* 1 for writing.  0 for read-only */
6952  struct KeyInfo*,                     /* First argument to compare function */
6953  BtCursor *pCursor                    /* Space to write cursor structure */
6954);
6955SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
6956SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
6957
6958SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
6959SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
6960  BtCursor*,
6961  UnpackedRecord *pUnKey,
6962  i64 intKey,
6963  int bias,
6964  int *pRes
6965);
6966SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
6967SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
6968SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
6969                                  const void *pData, int nData,
6970                                  int nZero, int bias, int seekResult);
6971SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
6972SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
6973SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
6974SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
6975SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
6976SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
6977SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
6978SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
6979SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
6980SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
6981SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
6982SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
6983SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
6984
6985SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
6986SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
6987
6988SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
6989SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
6990SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
6991
6992#ifndef NDEBUG
6993SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
6994#endif
6995
6996#ifndef SQLITE_OMIT_BTREECOUNT
6997SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
6998#endif
6999
7000#ifdef SQLITE_TEST
7001SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7002SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7003#endif
7004
7005/*
7006** If we are not using shared cache, then there is no need to
7007** use mutexes to access the BtShared structures.  So make the
7008** Enter and Leave procedures no-ops.
7009*/
7010#ifndef SQLITE_OMIT_SHARED_CACHE
7011SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7012SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7013#else
7014# define sqlite3BtreeEnter(X)
7015# define sqlite3BtreeEnterAll(X)
7016#endif
7017
7018#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7019SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7020SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7021SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7022SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7023SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7024SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7025SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7026#ifndef NDEBUG
7027  /* These routines are used inside assert() statements only. */
7028SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7029SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7030#endif
7031#else
7032
7033# define sqlite3BtreeLeave(X)
7034# define sqlite3BtreeEnterCursor(X)
7035# define sqlite3BtreeLeaveCursor(X)
7036# define sqlite3BtreeLeaveAll(X)
7037# define sqlite3BtreeMutexArrayEnter(X)
7038# define sqlite3BtreeMutexArrayLeave(X)
7039# define sqlite3BtreeMutexArrayInsert(X,Y)
7040
7041# define sqlite3BtreeHoldsMutex(X) 1
7042# define sqlite3BtreeHoldsAllMutexes(X) 1
7043#endif
7044
7045
7046#endif /* _BTREE_H_ */
7047
7048/************** End of btree.h ***********************************************/
7049/************** Continuing where we left off in sqliteInt.h ******************/
7050/************** Include vdbe.h in the middle of sqliteInt.h ******************/
7051/************** Begin file vdbe.h ********************************************/
7052/*
7053** 2001 September 15
7054**
7055** The author disclaims copyright to this source code.  In place of
7056** a legal notice, here is a blessing:
7057**
7058**    May you do good and not evil.
7059**    May you find forgiveness for yourself and forgive others.
7060**    May you share freely, never taking more than you give.
7061**
7062*************************************************************************
7063** Header file for the Virtual DataBase Engine (VDBE)
7064**
7065** This header defines the interface to the virtual database engine
7066** or VDBE.  The VDBE implements an abstract machine that runs a
7067** simple program to access and modify the underlying database.
7068*/
7069#ifndef _SQLITE_VDBE_H_
7070#define _SQLITE_VDBE_H_
7071
7072/*
7073** A single VDBE is an opaque structure named "Vdbe".  Only routines
7074** in the source file sqliteVdbe.c are allowed to see the insides
7075** of this structure.
7076*/
7077typedef struct Vdbe Vdbe;
7078
7079/*
7080** The names of the following types declared in vdbeInt.h are required
7081** for the VdbeOp definition.
7082*/
7083typedef struct VdbeFunc VdbeFunc;
7084typedef struct Mem Mem;
7085typedef struct SubProgram SubProgram;
7086
7087/*
7088** A single instruction of the virtual machine has an opcode
7089** and as many as three operands.  The instruction is recorded
7090** as an instance of the following structure:
7091*/
7092struct VdbeOp {
7093  u8 opcode;          /* What operation to perform */
7094  signed char p4type; /* One of the P4_xxx constants for p4 */
7095  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7096  u8 p5;              /* Fifth parameter is an unsigned character */
7097  int p1;             /* First operand */
7098  int p2;             /* Second parameter (often the jump destination) */
7099  int p3;             /* The third parameter */
7100  union {             /* fourth parameter */
7101    int i;                 /* Integer value if p4type==P4_INT32 */
7102    void *p;               /* Generic pointer */
7103    char *z;               /* Pointer to data for string (char array) types */
7104    i64 *pI64;             /* Used when p4type is P4_INT64 */
7105    double *pReal;         /* Used when p4type is P4_REAL */
7106    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7107    VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7108    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7109    Mem *pMem;             /* Used when p4type is P4_MEM */
7110    VTable *pVtab;         /* Used when p4type is P4_VTAB */
7111    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7112    int *ai;               /* Used when p4type is P4_INTARRAY */
7113    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7114  } p4;
7115#ifdef SQLITE_DEBUG
7116  char *zComment;          /* Comment to improve readability */
7117#endif
7118#ifdef VDBE_PROFILE
7119  int cnt;                 /* Number of times this instruction was executed */
7120  u64 cycles;              /* Total time spent executing this instruction */
7121#endif
7122};
7123typedef struct VdbeOp VdbeOp;
7124
7125
7126/*
7127** A sub-routine used to implement a trigger program.
7128*/
7129struct SubProgram {
7130  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7131  int nOp;                      /* Elements in aOp[] */
7132  int nMem;                     /* Number of memory cells required */
7133  int nCsr;                     /* Number of cursors required */
7134  int nRef;                     /* Number of pointers to this structure */
7135  void *token;                  /* id that may be used to recursive triggers */
7136};
7137
7138/*
7139** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7140** it takes up less space.
7141*/
7142struct VdbeOpList {
7143  u8 opcode;          /* What operation to perform */
7144  signed char p1;     /* First operand */
7145  signed char p2;     /* Second parameter (often the jump destination) */
7146  signed char p3;     /* Third parameter */
7147};
7148typedef struct VdbeOpList VdbeOpList;
7149
7150/*
7151** Allowed values of VdbeOp.p4type
7152*/
7153#define P4_NOTUSED    0   /* The P4 parameter is not used */
7154#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7155#define P4_STATIC   (-2)  /* Pointer to a static string */
7156#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7157#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7158#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7159#define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7160#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7161#define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7162#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7163#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7164#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7165#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7166#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7167#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7168#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7169
7170/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7171** is made.  That copy is freed when the Vdbe is finalized.  But if the
7172** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7173** gets freed when the Vdbe is finalized so it still should be obtained
7174** from a single sqliteMalloc().  But no copy is made and the calling
7175** function should *not* try to free the KeyInfo.
7176*/
7177#define P4_KEYINFO_HANDOFF (-16)
7178#define P4_KEYINFO_STATIC  (-17)
7179
7180/*
7181** The Vdbe.aColName array contains 5n Mem structures, where n is the
7182** number of columns of data returned by the statement.
7183*/
7184#define COLNAME_NAME     0
7185#define COLNAME_DECLTYPE 1
7186#define COLNAME_DATABASE 2
7187#define COLNAME_TABLE    3
7188#define COLNAME_COLUMN   4
7189#ifdef SQLITE_ENABLE_COLUMN_METADATA
7190# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7191#else
7192# ifdef SQLITE_OMIT_DECLTYPE
7193#   define COLNAME_N      1      /* Store only the name */
7194# else
7195#   define COLNAME_N      2      /* Store the name and decltype */
7196# endif
7197#endif
7198
7199/*
7200** The following macro converts a relative address in the p2 field
7201** of a VdbeOp structure into a negative number so that
7202** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7203** the macro again restores the address.
7204*/
7205#define ADDR(X)  (-1-(X))
7206
7207/*
7208** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7209** header file that defines a number for each opcode used by the VDBE.
7210*/
7211/************** Include opcodes.h in the middle of vdbe.h ********************/
7212/************** Begin file opcodes.h *****************************************/
7213/* Automatically generated.  Do not edit */
7214/* See the mkopcodeh.awk script for details */
7215#define OP_Goto                                 1
7216#define OP_Gosub                                2
7217#define OP_Return                               3
7218#define OP_Yield                                4
7219#define OP_HaltIfNull                           5
7220#define OP_Halt                                 6
7221#define OP_Integer                              7
7222#define OP_Int64                                8
7223#define OP_Real                               130   /* same as TK_FLOAT    */
7224#define OP_String8                             94   /* same as TK_STRING   */
7225#define OP_String                               9
7226#define OP_Null                                10
7227#define OP_Blob                                11
7228#define OP_Variable                            12
7229#define OP_Move                                13
7230#define OP_Copy                                14
7231#define OP_SCopy                               15
7232#define OP_ResultRow                           16
7233#define OP_Concat                              91   /* same as TK_CONCAT   */
7234#define OP_Add                                 86   /* same as TK_PLUS     */
7235#define OP_Subtract                            87   /* same as TK_MINUS    */
7236#define OP_Multiply                            88   /* same as TK_STAR     */
7237#define OP_Divide                              89   /* same as TK_SLASH    */
7238#define OP_Remainder                           90   /* same as TK_REM      */
7239#define OP_CollSeq                             17
7240#define OP_Function                            18
7241#define OP_BitAnd                              82   /* same as TK_BITAND   */
7242#define OP_BitOr                               83   /* same as TK_BITOR    */
7243#define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
7244#define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
7245#define OP_AddImm                              20
7246#define OP_MustBeInt                           21
7247#define OP_RealAffinity                        22
7248#define OP_ToText                             141   /* same as TK_TO_TEXT  */
7249#define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
7250#define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
7251#define OP_ToInt                              144   /* same as TK_TO_INT   */
7252#define OP_ToReal                             145   /* same as TK_TO_REAL  */
7253#define OP_Eq                                  76   /* same as TK_EQ       */
7254#define OP_Ne                                  75   /* same as TK_NE       */
7255#define OP_Lt                                  79   /* same as TK_LT       */
7256#define OP_Le                                  78   /* same as TK_LE       */
7257#define OP_Gt                                  77   /* same as TK_GT       */
7258#define OP_Ge                                  80   /* same as TK_GE       */
7259#define OP_Permutation                         23
7260#define OP_Compare                             24
7261#define OP_Jump                                25
7262#define OP_And                                 69   /* same as TK_AND      */
7263#define OP_Or                                  68   /* same as TK_OR       */
7264#define OP_Not                                 19   /* same as TK_NOT      */
7265#define OP_BitNot                              93   /* same as TK_BITNOT   */
7266#define OP_If                                  26
7267#define OP_IfNot                               27
7268#define OP_IsNull                              73   /* same as TK_ISNULL   */
7269#define OP_NotNull                             74   /* same as TK_NOTNULL  */
7270#define OP_Column                              28
7271#define OP_Affinity                            29
7272#define OP_MakeRecord                          30
7273#define OP_Count                               31
7274#define OP_Savepoint                           32
7275#define OP_AutoCommit                          33
7276#define OP_Transaction                         34
7277#define OP_ReadCookie                          35
7278#define OP_SetCookie                           36
7279#define OP_VerifyCookie                        37
7280#define OP_OpenRead                            38
7281#define OP_OpenWrite                           39
7282#define OP_OpenEphemeral                       40
7283#define OP_OpenPseudo                          41
7284#define OP_Close                               42
7285#define OP_SeekLt                              43
7286#define OP_SeekLe                              44
7287#define OP_SeekGe                              45
7288#define OP_SeekGt                              46
7289#define OP_Seek                                47
7290#define OP_NotFound                            48
7291#define OP_Found                               49
7292#define OP_IsUnique                            50
7293#define OP_NotExists                           51
7294#define OP_Sequence                            52
7295#define OP_NewRowid                            53
7296#define OP_Insert                              54
7297#define OP_InsertInt                           55
7298#define OP_Delete                              56
7299#define OP_ResetCount                          57
7300#define OP_RowKey                              58
7301#define OP_RowData                             59
7302#define OP_Rowid                               60
7303#define OP_NullRow                             61
7304#define OP_Last                                62
7305#define OP_Sort                                63
7306#define OP_Rewind                              64
7307#define OP_Prev                                65
7308#define OP_Next                                66
7309#define OP_IdxInsert                           67
7310#define OP_IdxDelete                           70
7311#define OP_IdxRowid                            71
7312#define OP_IdxLT                               72
7313#define OP_IdxGE                               81
7314#define OP_Destroy                             92
7315#define OP_Clear                               95
7316#define OP_CreateIndex                         96
7317#define OP_CreateTable                         97
7318#define OP_ParseSchema                         98
7319#define OP_LoadAnalysis                        99
7320#define OP_DropTable                          100
7321#define OP_DropIndex                          101
7322#define OP_DropTrigger                        102
7323#define OP_IntegrityCk                        103
7324#define OP_RowSetAdd                          104
7325#define OP_RowSetRead                         105
7326#define OP_RowSetTest                         106
7327#define OP_Program                            107
7328#define OP_Param                              108
7329#define OP_FkCounter                          109
7330#define OP_FkIfZero                           110
7331#define OP_MemMax                             111
7332#define OP_IfPos                              112
7333#define OP_IfNeg                              113
7334#define OP_IfZero                             114
7335#define OP_AggStep                            115
7336#define OP_AggFinal                           116
7337#define OP_Vacuum                             117
7338#define OP_IncrVacuum                         118
7339#define OP_Expire                             119
7340#define OP_TableLock                          120
7341#define OP_VBegin                             121
7342#define OP_VCreate                            122
7343#define OP_VDestroy                           123
7344#define OP_VOpen                              124
7345#define OP_VFilter                            125
7346#define OP_VColumn                            126
7347#define OP_VNext                              127
7348#define OP_VRename                            128
7349#define OP_VUpdate                            129
7350#define OP_Pagecount                          131
7351#define OP_Trace                              132
7352#define OP_Noop                               133
7353#define OP_Explain                            134
7354
7355/* The following opcode values are never used */
7356#define OP_NotUsed_135                        135
7357#define OP_NotUsed_136                        136
7358#define OP_NotUsed_137                        137
7359#define OP_NotUsed_138                        138
7360#define OP_NotUsed_139                        139
7361#define OP_NotUsed_140                        140
7362
7363
7364/* Properties such as "out2" or "jump" that are specified in
7365** comments following the "case" for each opcode in the vdbe.c
7366** are encoded into bitvectors as follows:
7367*/
7368#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7369#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7370#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7371#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7372#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7373#define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
7374#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7375#define OPFLG_INITIALIZER {\
7376/*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7377/*   8 */ 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x24,\
7378/*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7379/*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7380/*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7381/*  40 */ 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x08,\
7382/*  48 */ 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, 0x00,\
7383/*  56 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x01,\
7384/*  64 */ 0x01, 0x01, 0x01, 0x08, 0x4c, 0x4c, 0x00, 0x02,\
7385/*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7386/*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
7387/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x02, 0x24, 0x02, 0x00,\
7388/*  96 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7389/* 104 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
7390/* 112 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00,\
7391/* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,\
7392/* 128 */ 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\
7393/* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7394/* 144 */ 0x04, 0x04,}
7395
7396/************** End of opcodes.h *********************************************/
7397/************** Continuing where we left off in vdbe.h ***********************/
7398
7399/*
7400** Prototypes for the VDBE interface.  See comments on the implementation
7401** for a description of what each of these routines does.
7402*/
7403SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7404SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7405SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7406SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7407SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7408SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7409SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
7410SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7411SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7412SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7413SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7414SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7415SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7416SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7417SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7418SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7419SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7420SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7421SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7422SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
7423SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7424SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7425SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7426#ifdef SQLITE_DEBUG
7427SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
7428SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7429#endif
7430SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7431SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
7432SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7433SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
7434SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7435SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7436SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
7437SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7438SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
7439SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
7440SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
7441SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
7442#ifndef SQLITE_OMIT_TRACE
7443SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
7444#endif
7445
7446SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
7447SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7448SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7449
7450
7451#ifndef NDEBUG
7452SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7453# define VdbeComment(X)  sqlite3VdbeComment X
7454SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
7455# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
7456#else
7457# define VdbeComment(X)
7458# define VdbeNoopComment(X)
7459#endif
7460
7461#endif
7462
7463/************** End of vdbe.h ************************************************/
7464/************** Continuing where we left off in sqliteInt.h ******************/
7465/************** Include pager.h in the middle of sqliteInt.h *****************/
7466/************** Begin file pager.h *******************************************/
7467/*
7468** 2001 September 15
7469**
7470** The author disclaims copyright to this source code.  In place of
7471** a legal notice, here is a blessing:
7472**
7473**    May you do good and not evil.
7474**    May you find forgiveness for yourself and forgive others.
7475**    May you share freely, never taking more than you give.
7476**
7477*************************************************************************
7478** This header file defines the interface that the sqlite page cache
7479** subsystem.  The page cache subsystem reads and writes a file a page
7480** at a time and provides a journal for rollback.
7481*/
7482
7483#ifndef _PAGER_H_
7484#define _PAGER_H_
7485
7486/*
7487** Default maximum size for persistent journal files. A negative
7488** value means no limit. This value may be overridden using the
7489** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
7490*/
7491#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
7492  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
7493#endif
7494
7495/*
7496** The type used to represent a page number.  The first page in a file
7497** is called page 1.  0 is used to represent "not a page".
7498*/
7499typedef u32 Pgno;
7500
7501/*
7502** Each open file is managed by a separate instance of the "Pager" structure.
7503*/
7504typedef struct Pager Pager;
7505
7506/*
7507** Handle type for pages.
7508*/
7509typedef struct PgHdr DbPage;
7510
7511/*
7512** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
7513** reserved for working around a windows/posix incompatibility). It is
7514** used in the journal to signify that the remainder of the journal file
7515** is devoted to storing a master journal name - there are no more pages to
7516** roll back. See comments for function writeMasterJournal() in pager.c
7517** for details.
7518*/
7519#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
7520
7521/*
7522** Allowed values for the flags parameter to sqlite3PagerOpen().
7523**
7524** NOTE: These values must match the corresponding BTREE_ values in btree.h.
7525*/
7526#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
7527#define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
7528
7529/*
7530** Valid values for the second argument to sqlite3PagerLockingMode().
7531*/
7532#define PAGER_LOCKINGMODE_QUERY      -1
7533#define PAGER_LOCKINGMODE_NORMAL      0
7534#define PAGER_LOCKINGMODE_EXCLUSIVE   1
7535
7536/*
7537** Valid values for the second argument to sqlite3PagerJournalMode().
7538*/
7539#define PAGER_JOURNALMODE_QUERY      -1
7540#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7541#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7542#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7543#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
7544#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
7545
7546/*
7547** The remainder of this file contains the declarations of the functions
7548** that make up the Pager sub-system API. See source code comments for
7549** a detailed description of each routine.
7550*/
7551
7552/* Open and close a Pager connection. */
7553SQLITE_PRIVATE int sqlite3PagerOpen(
7554  sqlite3_vfs*,
7555  Pager **ppPager,
7556  const char*,
7557  int,
7558  int,
7559  int,
7560  void(*)(DbPage*)
7561);
7562SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
7563SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
7564
7565/* Functions used to configure a Pager object. */
7566SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
7567SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int);
7568SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7569SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7570SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7571SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7572SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
7573SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
7574SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
7575
7576/* Functions used to obtain and release page references. */
7577SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
7578#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
7579SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
7580SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
7581SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
7582
7583/* Operations on page references. */
7584SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
7585SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
7586SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
7587SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
7588SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
7589SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
7590
7591/* Functions used to manage pager transactions and savepoints. */
7592SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7593SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
7594SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7595SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7596SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7597SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7598SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
7599SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
7600SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
7601
7602/* Functions used to query pager state and configuration. */
7603SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
7604SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7605SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7606SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7607SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7608SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
7609SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
7610SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
7611SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
7612
7613/* Functions used to truncate the database file. */
7614SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
7615
7616/* Functions to support testing and debugging. */
7617#if !defined(NDEBUG) || defined(SQLITE_TEST)
7618SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7619SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
7620#endif
7621#ifdef SQLITE_TEST
7622SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
7623SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
7624  void disable_simulated_io_errors(void);
7625  void enable_simulated_io_errors(void);
7626#else
7627# define disable_simulated_io_errors()
7628# define enable_simulated_io_errors()
7629#endif
7630
7631#endif /* _PAGER_H_ */
7632
7633/************** End of pager.h ***********************************************/
7634/************** Continuing where we left off in sqliteInt.h ******************/
7635/************** Include pcache.h in the middle of sqliteInt.h ****************/
7636/************** Begin file pcache.h ******************************************/
7637/*
7638** 2008 August 05
7639**
7640** The author disclaims copyright to this source code.  In place of
7641** a legal notice, here is a blessing:
7642**
7643**    May you do good and not evil.
7644**    May you find forgiveness for yourself and forgive others.
7645**    May you share freely, never taking more than you give.
7646**
7647*************************************************************************
7648** This header file defines the interface that the sqlite page cache
7649** subsystem.
7650*/
7651
7652#ifndef _PCACHE_H_
7653
7654typedef struct PgHdr PgHdr;
7655typedef struct PCache PCache;
7656
7657/*
7658** Every page in the cache is controlled by an instance of the following
7659** structure.
7660*/
7661struct PgHdr {
7662  void *pData;                   /* Content of this page */
7663  void *pExtra;                  /* Extra content */
7664  PgHdr *pDirty;                 /* Transient list of dirty pages */
7665  Pgno pgno;                     /* Page number for this page */
7666  Pager *pPager;                 /* The pager this page is part of */
7667#ifdef SQLITE_CHECK_PAGES
7668  u32 pageHash;                  /* Hash of page content */
7669#endif
7670  u16 flags;                     /* PGHDR flags defined below */
7671
7672  /**********************************************************************
7673  ** Elements above are public.  All that follows is private to pcache.c
7674  ** and should not be accessed by other modules.
7675  */
7676  i16 nRef;                      /* Number of users of this page */
7677  PCache *pCache;                /* Cache that owns this page */
7678
7679  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
7680  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
7681};
7682
7683/* Bit values for PgHdr.flags */
7684#define PGHDR_DIRTY             0x002  /* Page has changed */
7685#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
7686                                       ** writing this page to the database */
7687#define PGHDR_NEED_READ         0x008  /* Content is unread */
7688#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
7689#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
7690
7691/* Initialize and shutdown the page cache subsystem */
7692SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
7693SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
7694
7695/* Page cache buffer management:
7696** These routines implement SQLITE_CONFIG_PAGECACHE.
7697*/
7698SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
7699
7700/* Create a new pager cache.
7701** Under memory stress, invoke xStress to try to make pages clean.
7702** Only clean and unpinned pages can be reclaimed.
7703*/
7704SQLITE_PRIVATE void sqlite3PcacheOpen(
7705  int szPage,                    /* Size of every page */
7706  int szExtra,                   /* Extra space associated with each page */
7707  int bPurgeable,                /* True if pages are on backing store */
7708  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
7709  void *pStress,                 /* Argument to xStress */
7710  PCache *pToInit                /* Preallocated space for the PCache */
7711);
7712
7713/* Modify the page-size after the cache has been created. */
7714SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
7715
7716/* Return the size in bytes of a PCache object.  Used to preallocate
7717** storage space.
7718*/
7719SQLITE_PRIVATE int sqlite3PcacheSize(void);
7720
7721/* One release per successful fetch.  Page is pinned until released.
7722** Reference counted.
7723*/
7724SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
7725SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
7726
7727SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
7728SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
7729SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
7730SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
7731
7732/* Change a page number.  Used by incr-vacuum. */
7733SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
7734
7735/* Remove all pages with pgno>x.  Reset the cache if x==0 */
7736SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
7737
7738/* Get a list of all dirty pages in the cache, sorted by page number */
7739SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
7740
7741/* Reset and close the cache object */
7742SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
7743
7744/* Clear flags from pages of the page cache */
7745SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
7746
7747/* Discard the contents of the cache */
7748SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
7749
7750/* Return the total number of outstanding page references */
7751SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
7752
7753/* Increment the reference count of an existing page */
7754SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
7755
7756SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
7757
7758/* Return the total number of pages stored in the cache */
7759SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
7760
7761#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
7762/* Iterate through all dirty pages currently stored in the cache. This
7763** interface is only available if SQLITE_CHECK_PAGES is defined when the
7764** library is built.
7765*/
7766SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
7767#endif
7768
7769/* Set and get the suggested cache-size for the specified pager-cache.
7770**
7771** If no global maximum is configured, then the system attempts to limit
7772** the total number of pages cached by purgeable pager-caches to the sum
7773** of the suggested cache-sizes.
7774*/
7775SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
7776#ifdef SQLITE_TEST
7777SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
7778#endif
7779
7780#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
7781/* Try to return memory used by the pcache module to the main memory heap */
7782SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
7783#endif
7784
7785#ifdef SQLITE_TEST
7786SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
7787#endif
7788
7789SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
7790
7791#endif /* _PCACHE_H_ */
7792
7793/************** End of pcache.h **********************************************/
7794/************** Continuing where we left off in sqliteInt.h ******************/
7795
7796/************** Include os.h in the middle of sqliteInt.h ********************/
7797/************** Begin file os.h **********************************************/
7798/*
7799** 2001 September 16
7800**
7801** The author disclaims copyright to this source code.  In place of
7802** a legal notice, here is a blessing:
7803**
7804**    May you do good and not evil.
7805**    May you find forgiveness for yourself and forgive others.
7806**    May you share freely, never taking more than you give.
7807**
7808******************************************************************************
7809**
7810** This header file (together with is companion C source-code file
7811** "os.c") attempt to abstract the underlying operating system so that
7812** the SQLite library will work on both POSIX and windows systems.
7813**
7814** This header file is #include-ed by sqliteInt.h and thus ends up
7815** being included by every source file.
7816*/
7817#ifndef _SQLITE_OS_H_
7818#define _SQLITE_OS_H_
7819
7820/*
7821** Figure out if we are dealing with Unix, Windows, or some other
7822** operating system.  After the following block of preprocess macros,
7823** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
7824** will defined to either 1 or 0.  One of the four will be 1.  The other
7825** three will be 0.
7826*/
7827#if defined(SQLITE_OS_OTHER)
7828# if SQLITE_OS_OTHER==1
7829#   undef SQLITE_OS_UNIX
7830#   define SQLITE_OS_UNIX 0
7831#   undef SQLITE_OS_WIN
7832#   define SQLITE_OS_WIN 0
7833#   undef SQLITE_OS_OS2
7834#   define SQLITE_OS_OS2 0
7835# else
7836#   undef SQLITE_OS_OTHER
7837# endif
7838#endif
7839#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
7840# define SQLITE_OS_OTHER 0
7841# ifndef SQLITE_OS_WIN
7842#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
7843#     define SQLITE_OS_WIN 1
7844#     define SQLITE_OS_UNIX 0
7845#     define SQLITE_OS_OS2 0
7846#   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
7847#     define SQLITE_OS_WIN 0
7848#     define SQLITE_OS_UNIX 0
7849#     define SQLITE_OS_OS2 1
7850#   else
7851#     define SQLITE_OS_WIN 0
7852#     define SQLITE_OS_UNIX 1
7853#     define SQLITE_OS_OS2 0
7854#  endif
7855# else
7856#  define SQLITE_OS_UNIX 0
7857#  define SQLITE_OS_OS2 0
7858# endif
7859#else
7860# ifndef SQLITE_OS_WIN
7861#  define SQLITE_OS_WIN 0
7862# endif
7863#endif
7864
7865/*
7866** Determine if we are dealing with WindowsCE - which has a much
7867** reduced API.
7868*/
7869#if defined(_WIN32_WCE)
7870# define SQLITE_OS_WINCE 1
7871#else
7872# define SQLITE_OS_WINCE 0
7873#endif
7874
7875
7876/*
7877** Define the maximum size of a temporary filename
7878*/
7879#if SQLITE_OS_WIN
7880# include <windows.h>
7881# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
7882#elif SQLITE_OS_OS2
7883# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
7884#  include <os2safe.h> /* has to be included before os2.h for linking to work */
7885# endif
7886# define INCL_DOSDATETIME
7887# define INCL_DOSFILEMGR
7888# define INCL_DOSERRORS
7889# define INCL_DOSMISC
7890# define INCL_DOSPROCESS
7891# define INCL_DOSMODULEMGR
7892# define INCL_DOSSEMAPHORES
7893# include <os2.h>
7894# include <uconv.h>
7895# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
7896#else
7897# define SQLITE_TEMPNAME_SIZE 200
7898#endif
7899
7900/* If the SET_FULLSYNC macro is not defined above, then make it
7901** a no-op
7902*/
7903#ifndef SET_FULLSYNC
7904# define SET_FULLSYNC(x,y)
7905#endif
7906
7907/*
7908** The default size of a disk sector
7909*/
7910#ifndef SQLITE_DEFAULT_SECTOR_SIZE
7911# define SQLITE_DEFAULT_SECTOR_SIZE 512
7912#endif
7913
7914/*
7915** Temporary files are named starting with this prefix followed by 16 random
7916** alphanumeric characters, and no file extension. They are stored in the
7917** OS's standard temporary file directory, and are deleted prior to exit.
7918** If sqlite is being embedded in another program, you may wish to change the
7919** prefix to reflect your program's name, so that if your program exits
7920** prematurely, old temporary files can be easily identified. This can be done
7921** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
7922**
7923** 2006-10-31:  The default prefix used to be "sqlite_".  But then
7924** Mcafee started using SQLite in their anti-virus product and it
7925** started putting files with the "sqlite" name in the c:/temp folder.
7926** This annoyed many windows users.  Those users would then do a
7927** Google search for "sqlite", find the telephone numbers of the
7928** developers and call to wake them up at night and complain.
7929** For this reason, the default name prefix is changed to be "sqlite"
7930** spelled backwards.  So the temp files are still identified, but
7931** anybody smart enough to figure out the code is also likely smart
7932** enough to know that calling the developer will not help get rid
7933** of the file.
7934*/
7935#ifndef SQLITE_TEMP_FILE_PREFIX
7936# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
7937#endif
7938
7939/*
7940** The following values may be passed as the second argument to
7941** sqlite3OsLock(). The various locks exhibit the following semantics:
7942**
7943** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
7944** RESERVED:  A single process may hold a RESERVED lock on a file at
7945**            any time. Other processes may hold and obtain new SHARED locks.
7946** PENDING:   A single process may hold a PENDING lock on a file at
7947**            any one time. Existing SHARED locks may persist, but no new
7948**            SHARED locks may be obtained by other processes.
7949** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
7950**
7951** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
7952** process that requests an EXCLUSIVE lock may actually obtain a PENDING
7953** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
7954** sqlite3OsLock().
7955*/
7956#define NO_LOCK         0
7957#define SHARED_LOCK     1
7958#define RESERVED_LOCK   2
7959#define PENDING_LOCK    3
7960#define EXCLUSIVE_LOCK  4
7961
7962/*
7963** File Locking Notes:  (Mostly about windows but also some info for Unix)
7964**
7965** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
7966** those functions are not available.  So we use only LockFile() and
7967** UnlockFile().
7968**
7969** LockFile() prevents not just writing but also reading by other processes.
7970** A SHARED_LOCK is obtained by locking a single randomly-chosen
7971** byte out of a specific range of bytes. The lock byte is obtained at
7972** random so two separate readers can probably access the file at the
7973** same time, unless they are unlucky and choose the same lock byte.
7974** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
7975** There can only be one writer.  A RESERVED_LOCK is obtained by locking
7976** a single byte of the file that is designated as the reserved lock byte.
7977** A PENDING_LOCK is obtained by locking a designated byte different from
7978** the RESERVED_LOCK byte.
7979**
7980** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
7981** which means we can use reader/writer locks.  When reader/writer locks
7982** are used, the lock is placed on the same range of bytes that is used
7983** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
7984** will support two or more Win95 readers or two or more WinNT readers.
7985** But a single Win95 reader will lock out all WinNT readers and a single
7986** WinNT reader will lock out all other Win95 readers.
7987**
7988** The following #defines specify the range of bytes used for locking.
7989** SHARED_SIZE is the number of bytes available in the pool from which
7990** a random byte is selected for a shared lock.  The pool of bytes for
7991** shared locks begins at SHARED_FIRST.
7992**
7993** The same locking strategy and
7994** byte ranges are used for Unix.  This leaves open the possiblity of having
7995** clients on win95, winNT, and unix all talking to the same shared file
7996** and all locking correctly.  To do so would require that samba (or whatever
7997** tool is being used for file sharing) implements locks correctly between
7998** windows and unix.  I'm guessing that isn't likely to happen, but by
7999** using the same locking range we are at least open to the possibility.
8000**
8001** Locking in windows is manditory.  For this reason, we cannot store
8002** actual data in the bytes used for locking.  The pager never allocates
8003** the pages involved in locking therefore.  SHARED_SIZE is selected so
8004** that all locks will fit on a single page even at the minimum page size.
8005** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8006** is set high so that we don't have to allocate an unused page except
8007** for very large databases.  But one should test the page skipping logic
8008** by setting PENDING_BYTE low and running the entire regression suite.
8009**
8010** Changing the value of PENDING_BYTE results in a subtly incompatible
8011** file format.  Depending on how it is changed, you might not notice
8012** the incompatibility right away, even running a full regression test.
8013** The default location of PENDING_BYTE is the first byte past the
8014** 1GB boundary.
8015**
8016*/
8017#define PENDING_BYTE      sqlite3PendingByte
8018#define RESERVED_BYTE     (PENDING_BYTE+1)
8019#define SHARED_FIRST      (PENDING_BYTE+2)
8020#define SHARED_SIZE       510
8021
8022/*
8023** Wrapper around OS specific sqlite3_os_init() function.
8024*/
8025SQLITE_PRIVATE int sqlite3OsInit(void);
8026
8027/*
8028** Functions for accessing sqlite3_file methods
8029*/
8030SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8031SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8032SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8033SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8034SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8035SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8036SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8037SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8038SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8039SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8040#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8041SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8042SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8043
8044/*
8045** Functions for accessing sqlite3_vfs methods
8046*/
8047SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8048SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8049SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8050SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8051#ifndef SQLITE_OMIT_LOAD_EXTENSION
8052SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8053SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8054SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8055SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8056#endif /* SQLITE_OMIT_LOAD_EXTENSION */
8057SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8058SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8059SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
8060
8061/*
8062** Convenience functions for opening and closing files using
8063** sqlite3_malloc() to obtain space for the file-handle structure.
8064*/
8065SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8066SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8067
8068#endif /* _SQLITE_OS_H_ */
8069
8070/************** End of os.h **************************************************/
8071/************** Continuing where we left off in sqliteInt.h ******************/
8072/************** Include mutex.h in the middle of sqliteInt.h *****************/
8073/************** Begin file mutex.h *******************************************/
8074/*
8075** 2007 August 28
8076**
8077** The author disclaims copyright to this source code.  In place of
8078** a legal notice, here is a blessing:
8079**
8080**    May you do good and not evil.
8081**    May you find forgiveness for yourself and forgive others.
8082**    May you share freely, never taking more than you give.
8083**
8084*************************************************************************
8085**
8086** This file contains the common header for all mutex implementations.
8087** The sqliteInt.h header #includes this file so that it is available
8088** to all source files.  We break it out in an effort to keep the code
8089** better organized.
8090**
8091** NOTE:  source files should *not* #include this header file directly.
8092** Source files should #include the sqliteInt.h file and let that file
8093** include this one indirectly.
8094*/
8095
8096
8097/*
8098** Figure out what version of the code to use.  The choices are
8099**
8100**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8101**                             mutexes implemention cannot be overridden
8102**                             at start-time.
8103**
8104**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8105**                             mutual exclusion is provided.  But this
8106**                             implementation can be overridden at
8107**                             start-time.
8108**
8109**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8110**
8111**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8112**
8113**   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8114*/
8115#if !SQLITE_THREADSAFE
8116# define SQLITE_MUTEX_OMIT
8117#endif
8118#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8119#  if SQLITE_OS_UNIX
8120#    define SQLITE_MUTEX_PTHREADS
8121#  elif SQLITE_OS_WIN
8122#    define SQLITE_MUTEX_W32
8123#  elif SQLITE_OS_OS2
8124#    define SQLITE_MUTEX_OS2
8125#  else
8126#    define SQLITE_MUTEX_NOOP
8127#  endif
8128#endif
8129
8130#ifdef SQLITE_MUTEX_OMIT
8131/*
8132** If this is a no-op implementation, implement everything as macros.
8133*/
8134#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8135#define sqlite3_mutex_free(X)
8136#define sqlite3_mutex_enter(X)
8137#define sqlite3_mutex_try(X)      SQLITE_OK
8138#define sqlite3_mutex_leave(X)
8139#define sqlite3_mutex_held(X)     1
8140#define sqlite3_mutex_notheld(X)  1
8141#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8142#define sqlite3MutexInit()        SQLITE_OK
8143#define sqlite3MutexEnd()
8144#endif /* defined(SQLITE_MUTEX_OMIT) */
8145
8146/************** End of mutex.h ***********************************************/
8147/************** Continuing where we left off in sqliteInt.h ******************/
8148
8149
8150/*
8151** Each database file to be accessed by the system is an instance
8152** of the following structure.  There are normally two of these structures
8153** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8154** aDb[1] is the database file used to hold temporary tables.  Additional
8155** databases may be attached.
8156*/
8157struct Db {
8158  char *zName;         /* Name of this database */
8159  Btree *pBt;          /* The B*Tree structure for this database file */
8160  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8161  u8 safety_level;     /* How aggressive at syncing data to disk */
8162  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8163};
8164
8165/*
8166** An instance of the following structure stores a database schema.
8167**
8168** If there are no virtual tables configured in this schema, the
8169** Schema.db variable is set to NULL. After the first virtual table
8170** has been added, it is set to point to the database connection
8171** used to create the connection. Once a virtual table has been
8172** added to the Schema structure and the Schema.db variable populated,
8173** only that database connection may use the Schema to prepare
8174** statements.
8175*/
8176struct Schema {
8177  int schema_cookie;   /* Database schema version number for this file */
8178  Hash tblHash;        /* All tables indexed by name */
8179  Hash idxHash;        /* All (named) indices indexed by name */
8180  Hash trigHash;       /* All triggers indexed by name */
8181  Hash fkeyHash;       /* All foreign keys by referenced table name */
8182  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8183  u8 file_format;      /* Schema format version for this file */
8184  u8 enc;              /* Text encoding used by this database */
8185  u16 flags;           /* Flags associated with this schema */
8186  int cache_size;      /* Number of pages to use in the cache */
8187#ifndef SQLITE_OMIT_VIRTUALTABLE
8188  sqlite3 *db;         /* "Owner" connection. See comment above */
8189#endif
8190};
8191
8192/*
8193** These macros can be used to test, set, or clear bits in the
8194** Db.flags field.
8195*/
8196#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8197#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8198#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8199#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8200
8201/*
8202** Allowed values for the DB.flags field.
8203**
8204** The DB_SchemaLoaded flag is set after the database schema has been
8205** read into internal hash tables.
8206**
8207** DB_UnresetViews means that one or more views have column names that
8208** have been filled out.  If the schema changes, these column names might
8209** changes and so the view will need to be reset.
8210*/
8211#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8212#define DB_UnresetViews    0x0002  /* Some views have defined column names */
8213#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8214
8215/*
8216** The number of different kinds of things that can be limited
8217** using the sqlite3_limit() interface.
8218*/
8219#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
8220
8221/*
8222** Lookaside malloc is a set of fixed-size buffers that can be used
8223** to satisfy small transient memory allocation requests for objects
8224** associated with a particular database connection.  The use of
8225** lookaside malloc provides a significant performance enhancement
8226** (approx 10%) by avoiding numerous malloc/free requests while parsing
8227** SQL statements.
8228**
8229** The Lookaside structure holds configuration information about the
8230** lookaside malloc subsystem.  Each available memory allocation in
8231** the lookaside subsystem is stored on a linked list of LookasideSlot
8232** objects.
8233**
8234** Lookaside allocations are only allowed for objects that are associated
8235** with a particular database connection.  Hence, schema information cannot
8236** be stored in lookaside because in shared cache mode the schema information
8237** is shared by multiple database connections.  Therefore, while parsing
8238** schema information, the Lookaside.bEnabled flag is cleared so that
8239** lookaside allocations are not used to construct the schema objects.
8240*/
8241struct Lookaside {
8242  u16 sz;                 /* Size of each buffer in bytes */
8243  u8 bEnabled;            /* False to disable new lookaside allocations */
8244  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8245  int nOut;               /* Number of buffers currently checked out */
8246  int mxOut;              /* Highwater mark for nOut */
8247  LookasideSlot *pFree;   /* List of available buffers */
8248  void *pStart;           /* First byte of available memory space */
8249  void *pEnd;             /* First byte past end of available space */
8250};
8251struct LookasideSlot {
8252  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8253};
8254
8255/*
8256** A hash table for function definitions.
8257**
8258** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8259** Collisions are on the FuncDef.pHash chain.
8260*/
8261struct FuncDefHash {
8262  FuncDef *a[23];       /* Hash table for functions */
8263};
8264
8265/*
8266** Each database is an instance of the following structure.
8267**
8268** The sqlite.lastRowid records the last insert rowid generated by an
8269** insert statement.  Inserts on views do not affect its value.  Each
8270** trigger has its own context, so that lastRowid can be updated inside
8271** triggers as usual.  The previous value will be restored once the trigger
8272** exits.  Upon entering a before or instead of trigger, lastRowid is no
8273** longer (since after version 2.8.12) reset to -1.
8274**
8275** The sqlite.nChange does not count changes within triggers and keeps no
8276** context.  It is reset at start of sqlite3_exec.
8277** The sqlite.lsChange represents the number of changes made by the last
8278** insert, update, or delete statement.  It remains constant throughout the
8279** length of a statement and is then updated by OP_SetCounts.  It keeps a
8280** context stack just like lastRowid so that the count of changes
8281** within a trigger is not seen outside the trigger.  Changes to views do not
8282** affect the value of lsChange.
8283** The sqlite.csChange keeps track of the number of current changes (since
8284** the last statement) and is used to update sqlite_lsChange.
8285**
8286** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8287** store the most recent error code and, if applicable, string. The
8288** internal function sqlite3Error() is used to set these variables
8289** consistently.
8290*/
8291struct sqlite3 {
8292  sqlite3_vfs *pVfs;            /* OS Interface */
8293  int nDb;                      /* Number of backends currently in use */
8294  Db *aDb;                      /* All backends */
8295  int flags;                    /* Miscellaneous flags. See below */
8296  int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8297  int errCode;                  /* Most recent error code (SQLITE_*) */
8298  int errMask;                  /* & result codes with this before returning */
8299  u8 autoCommit;                /* The auto-commit flag. */
8300  u8 temp_store;                /* 1: file 2: memory 0: default */
8301  u8 mallocFailed;              /* True if we have seen a malloc failure */
8302  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8303  u8 dfltJournalMode;           /* Default journal mode for attached dbs */
8304  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8305  int nextPagesize;             /* Pagesize after VACUUM if >0 */
8306  int nTable;                   /* Number of tables in the database */
8307  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8308  i64 lastRowid;                /* ROWID of most recent insert (see above) */
8309  u32 magic;                    /* Magic number for detect library misuse */
8310  int nChange;                  /* Value returned by sqlite3_changes() */
8311  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8312  sqlite3_mutex *mutex;         /* Connection mutex */
8313  int aLimit[SQLITE_N_LIMIT];   /* Limits */
8314  struct sqlite3InitInfo {      /* Information used during initialization */
8315    int iDb;                    /* When back is being initialized */
8316    int newTnum;                /* Rootpage of table being initialized */
8317    u8 busy;                    /* TRUE if currently initializing */
8318    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
8319  } init;
8320  int nExtension;               /* Number of loaded extensions */
8321  void **aExtension;            /* Array of shared library handles */
8322  struct Vdbe *pVdbe;           /* List of active virtual machines */
8323  int activeVdbeCnt;            /* Number of VDBEs currently executing */
8324  int writeVdbeCnt;             /* Number of active VDBEs that are writing */
8325  void (*xTrace)(void*,const char*);        /* Trace function */
8326  void *pTraceArg;                          /* Argument to the trace function */
8327  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8328  void *pProfileArg;                        /* Argument to profile function */
8329  void *pCommitArg;                 /* Argument to xCommitCallback() */
8330  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8331  void *pRollbackArg;               /* Argument to xRollbackCallback() */
8332  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8333  void *pUpdateArg;
8334  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8335  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8336  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8337  void *pCollNeededArg;
8338  sqlite3_value *pErr;          /* Most recent error message */
8339  char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8340  char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8341  union {
8342    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
8343    double notUsed1;            /* Spacer */
8344  } u1;
8345  Lookaside lookaside;          /* Lookaside malloc configuration */
8346#ifndef SQLITE_OMIT_AUTHORIZATION
8347  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8348                                /* Access authorization function */
8349  void *pAuthArg;               /* 1st argument to the access auth function */
8350#endif
8351#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8352  int (*xProgress)(void *);     /* The progress callback */
8353  void *pProgressArg;           /* Argument to the progress callback */
8354  int nProgressOps;             /* Number of opcodes for progress callback */
8355#endif
8356#ifndef SQLITE_OMIT_VIRTUALTABLE
8357  Hash aModule;                 /* populated by sqlite3_create_module() */
8358  Table *pVTab;                 /* vtab with active Connect/Create method */
8359  VTable **aVTrans;             /* Virtual tables with open transactions */
8360  int nVTrans;                  /* Allocated size of aVTrans */
8361  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
8362#endif
8363  FuncDefHash aFunc;            /* Hash table of connection functions */
8364  Hash aCollSeq;                /* All collating sequences */
8365  BusyHandler busyHandler;      /* Busy callback */
8366  int busyTimeout;              /* Busy handler timeout, in msec */
8367  Db aDbStatic[2];              /* Static space for the 2 default backends */
8368  Savepoint *pSavepoint;        /* List of active savepoints */
8369  int nSavepoint;               /* Number of non-transaction savepoints */
8370  int nStatement;               /* Number of nested statement-transactions  */
8371  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
8372  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
8373
8374#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
8375  /* The following variables are all protected by the STATIC_MASTER
8376  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
8377  **
8378  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
8379  ** unlock so that it can proceed.
8380  **
8381  ** When X.pBlockingConnection==Y, that means that something that X tried
8382  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
8383  ** held by Y.
8384  */
8385  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
8386  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
8387  void *pUnlockArg;                     /* Argument to xUnlockNotify */
8388  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
8389  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
8390#endif
8391};
8392
8393/*
8394** A macro to discover the encoding of a database.
8395*/
8396#define ENC(db) ((db)->aDb[0].pSchema->enc)
8397
8398/*
8399** Possible values for the sqlite3.flags.
8400*/
8401#define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
8402#define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
8403#define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
8404#define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
8405#define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
8406                                          /*   DELETE, or UPDATE and return */
8407                                          /*   the count using a callback. */
8408#define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
8409                                          /*   result set is empty */
8410#define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
8411#define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
8412#define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
8413#define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when
8414                                          ** accessing read-only databases */
8415#define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
8416#define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
8417#define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
8418#define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
8419#define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
8420#define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
8421#define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
8422#define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
8423#define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
8424
8425/*
8426** Bits of the sqlite3.flags field that are used by the
8427** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
8428** These must be the low-order bits of the flags field.
8429*/
8430#define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
8431#define SQLITE_ColumnCache    0x02        /* Disable the column cache */
8432#define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
8433#define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
8434#define SQLITE_IndexCover     0x10        /* Disable index covering table */
8435#define SQLITE_OptMask        0x1f        /* Mask of all disablable opts */
8436
8437/*
8438** Possible values for the sqlite.magic field.
8439** The numbers are obtained at random and have no special meaning, other
8440** than being distinct from one another.
8441*/
8442#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
8443#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
8444#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
8445#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
8446#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
8447
8448/*
8449** Each SQL function is defined by an instance of the following
8450** structure.  A pointer to this structure is stored in the sqlite.aFunc
8451** hash table.  When multiple functions have the same name, the hash table
8452** points to a linked list of these structures.
8453*/
8454struct FuncDef {
8455  i16 nArg;            /* Number of arguments.  -1 means unlimited */
8456  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
8457  u8 flags;            /* Some combination of SQLITE_FUNC_* */
8458  void *pUserData;     /* User data parameter */
8459  FuncDef *pNext;      /* Next function with same name */
8460  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
8461  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
8462  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
8463  char *zName;         /* SQL name of the function. */
8464  FuncDef *pHash;      /* Next with a different name but the same hash */
8465};
8466
8467/*
8468** Possible values for FuncDef.flags
8469*/
8470#define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
8471#define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
8472#define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
8473#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
8474#define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
8475#define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
8476#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
8477
8478/*
8479** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
8480** used to create the initializers for the FuncDef structures.
8481**
8482**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
8483**     Used to create a scalar function definition of a function zName
8484**     implemented by C function xFunc that accepts nArg arguments. The
8485**     value passed as iArg is cast to a (void*) and made available
8486**     as the user-data (sqlite3_user_data()) for the function. If
8487**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
8488**
8489**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
8490**     Used to create an aggregate function definition implemented by
8491**     the C functions xStep and xFinal. The first four parameters
8492**     are interpreted in the same way as the first 4 parameters to
8493**     FUNCTION().
8494**
8495**   LIKEFUNC(zName, nArg, pArg, flags)
8496**     Used to create a scalar function definition of a function zName
8497**     that accepts nArg arguments and is implemented by a call to C
8498**     function likeFunc. Argument pArg is cast to a (void *) and made
8499**     available as the function user-data (sqlite3_user_data()). The
8500**     FuncDef.flags variable is set to the value passed as the flags
8501**     parameter.
8502*/
8503#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
8504  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8505   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
8506#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
8507  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8508   pArg, 0, xFunc, 0, 0, #zName, 0}
8509#define LIKEFUNC(zName, nArg, arg, flags) \
8510  {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
8511#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
8512  {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
8513   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
8514
8515/*
8516** All current savepoints are stored in a linked list starting at
8517** sqlite3.pSavepoint. The first element in the list is the most recently
8518** opened savepoint. Savepoints are added to the list by the vdbe
8519** OP_Savepoint instruction.
8520*/
8521struct Savepoint {
8522  char *zName;                        /* Savepoint name (nul-terminated) */
8523  i64 nDeferredCons;                  /* Number of deferred fk violations */
8524  Savepoint *pNext;                   /* Parent savepoint (if any) */
8525};
8526
8527/*
8528** The following are used as the second parameter to sqlite3Savepoint(),
8529** and as the P1 argument to the OP_Savepoint instruction.
8530*/
8531#define SAVEPOINT_BEGIN      0
8532#define SAVEPOINT_RELEASE    1
8533#define SAVEPOINT_ROLLBACK   2
8534
8535
8536/*
8537** Each SQLite module (virtual table definition) is defined by an
8538** instance of the following structure, stored in the sqlite3.aModule
8539** hash table.
8540*/
8541struct Module {
8542  const sqlite3_module *pModule;       /* Callback pointers */
8543  const char *zName;                   /* Name passed to create_module() */
8544  void *pAux;                          /* pAux passed to create_module() */
8545  void (*xDestroy)(void *);            /* Module destructor function */
8546};
8547
8548/*
8549** information about each column of an SQL table is held in an instance
8550** of this structure.
8551*/
8552struct Column {
8553  char *zName;     /* Name of this column */
8554  Expr *pDflt;     /* Default value of this column */
8555  char *zDflt;     /* Original text of the default value */
8556  char *zType;     /* Data type for this column */
8557  char *zColl;     /* Collating sequence.  If NULL, use the default */
8558  u8 notNull;      /* True if there is a NOT NULL constraint */
8559  u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
8560  char affinity;   /* One of the SQLITE_AFF_... values */
8561#ifndef SQLITE_OMIT_VIRTUALTABLE
8562  u8 isHidden;     /* True if this column is 'hidden' */
8563#endif
8564};
8565
8566/*
8567** A "Collating Sequence" is defined by an instance of the following
8568** structure. Conceptually, a collating sequence consists of a name and
8569** a comparison routine that defines the order of that sequence.
8570**
8571** There may two separate implementations of the collation function, one
8572** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
8573** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
8574** native byte order. When a collation sequence is invoked, SQLite selects
8575** the version that will require the least expensive encoding
8576** translations, if any.
8577**
8578** The CollSeq.pUser member variable is an extra parameter that passed in
8579** as the first argument to the UTF-8 comparison function, xCmp.
8580** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
8581** xCmp16.
8582**
8583** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
8584** collating sequence is undefined.  Indices built on an undefined
8585** collating sequence may not be read or written.
8586*/
8587struct CollSeq {
8588  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
8589  u8 enc;               /* Text encoding handled by xCmp() */
8590  u8 type;              /* One of the SQLITE_COLL_... values below */
8591  void *pUser;          /* First argument to xCmp() */
8592  int (*xCmp)(void*,int, const void*, int, const void*);
8593  void (*xDel)(void*);  /* Destructor for pUser */
8594};
8595
8596/*
8597** Allowed values of CollSeq.type:
8598*/
8599#define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
8600#define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
8601#define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
8602#define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
8603
8604/*
8605** A sort order can be either ASC or DESC.
8606*/
8607#define SQLITE_SO_ASC       0  /* Sort in ascending order */
8608#define SQLITE_SO_DESC      1  /* Sort in ascending order */
8609
8610/*
8611** Column affinity types.
8612**
8613** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
8614** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
8615** the speed a little by numbering the values consecutively.
8616**
8617** But rather than start with 0 or 1, we begin with 'a'.  That way,
8618** when multiple affinity types are concatenated into a string and
8619** used as the P4 operand, they will be more readable.
8620**
8621** Note also that the numeric types are grouped together so that testing
8622** for a numeric type is a single comparison.
8623*/
8624#define SQLITE_AFF_TEXT     'a'
8625#define SQLITE_AFF_NONE     'b'
8626#define SQLITE_AFF_NUMERIC  'c'
8627#define SQLITE_AFF_INTEGER  'd'
8628#define SQLITE_AFF_REAL     'e'
8629
8630#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
8631
8632/*
8633** The SQLITE_AFF_MASK values masks off the significant bits of an
8634** affinity value.
8635*/
8636#define SQLITE_AFF_MASK     0x67
8637
8638/*
8639** Additional bit values that can be ORed with an affinity without
8640** changing the affinity.
8641*/
8642#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
8643#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
8644#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
8645
8646/*
8647** An object of this type is created for each virtual table present in
8648** the database schema.
8649**
8650** If the database schema is shared, then there is one instance of this
8651** structure for each database connection (sqlite3*) that uses the shared
8652** schema. This is because each database connection requires its own unique
8653** instance of the sqlite3_vtab* handle used to access the virtual table
8654** implementation. sqlite3_vtab* handles can not be shared between
8655** database connections, even when the rest of the in-memory database
8656** schema is shared, as the implementation often stores the database
8657** connection handle passed to it via the xConnect() or xCreate() method
8658** during initialization internally. This database connection handle may
8659** then used by the virtual table implementation to access real tables
8660** within the database. So that they appear as part of the callers
8661** transaction, these accesses need to be made via the same database
8662** connection as that used to execute SQL operations on the virtual table.
8663**
8664** All VTable objects that correspond to a single table in a shared
8665** database schema are initially stored in a linked-list pointed to by
8666** the Table.pVTable member variable of the corresponding Table object.
8667** When an sqlite3_prepare() operation is required to access the virtual
8668** table, it searches the list for the VTable that corresponds to the
8669** database connection doing the preparing so as to use the correct
8670** sqlite3_vtab* handle in the compiled query.
8671**
8672** When an in-memory Table object is deleted (for example when the
8673** schema is being reloaded for some reason), the VTable objects are not
8674** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
8675** immediately. Instead, they are moved from the Table.pVTable list to
8676** another linked list headed by the sqlite3.pDisconnect member of the
8677** corresponding sqlite3 structure. They are then deleted/xDisconnected
8678** next time a statement is prepared using said sqlite3*. This is done
8679** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
8680** Refer to comments above function sqlite3VtabUnlockList() for an
8681** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
8682** list without holding the corresponding sqlite3.mutex mutex.
8683**
8684** The memory for objects of this type is always allocated by
8685** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
8686** the first argument.
8687*/
8688struct VTable {
8689  sqlite3 *db;              /* Database connection associated with this table */
8690  Module *pMod;             /* Pointer to module implementation */
8691  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
8692  int nRef;                 /* Number of pointers to this structure */
8693  VTable *pNext;            /* Next in linked list (see above) */
8694};
8695
8696/*
8697** Each SQL table is represented in memory by an instance of the
8698** following structure.
8699**
8700** Table.zName is the name of the table.  The case of the original
8701** CREATE TABLE statement is stored, but case is not significant for
8702** comparisons.
8703**
8704** Table.nCol is the number of columns in this table.  Table.aCol is a
8705** pointer to an array of Column structures, one for each column.
8706**
8707** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
8708** the column that is that key.   Otherwise Table.iPKey is negative.  Note
8709** that the datatype of the PRIMARY KEY must be INTEGER for this field to
8710** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
8711** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
8712** is generated for each row of the table.  TF_HasPrimaryKey is set if
8713** the table has any PRIMARY KEY, INTEGER or otherwise.
8714**
8715** Table.tnum is the page number for the root BTree page of the table in the
8716** database file.  If Table.iDb is the index of the database table backend
8717** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
8718** holds temporary tables and indices.  If TF_Ephemeral is set
8719** then the table is stored in a file that is automatically deleted
8720** when the VDBE cursor to the table is closed.  In this case Table.tnum
8721** refers VDBE cursor number that holds the table open, not to the root
8722** page number.  Transient tables are used to hold the results of a
8723** sub-query that appears instead of a real table name in the FROM clause
8724** of a SELECT statement.
8725*/
8726struct Table {
8727  sqlite3 *dbMem;      /* DB connection used for lookaside allocations. */
8728  char *zName;         /* Name of the table or view */
8729  int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
8730  int nCol;            /* Number of columns in this table */
8731  Column *aCol;        /* Information about each column */
8732  Index *pIndex;       /* List of SQL indexes on this table. */
8733  int tnum;            /* Root BTree node for this table (see note above) */
8734  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
8735  u16 nRef;            /* Number of pointers to this Table */
8736  u8 tabFlags;         /* Mask of TF_* values */
8737  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
8738  FKey *pFKey;         /* Linked list of all foreign keys in this table */
8739  char *zColAff;       /* String defining the affinity of each column */
8740#ifndef SQLITE_OMIT_CHECK
8741  Expr *pCheck;        /* The AND of all CHECK constraints */
8742#endif
8743#ifndef SQLITE_OMIT_ALTERTABLE
8744  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
8745#endif
8746#ifndef SQLITE_OMIT_VIRTUALTABLE
8747  VTable *pVTable;     /* List of VTable objects. */
8748  int nModuleArg;      /* Number of arguments to the module */
8749  char **azModuleArg;  /* Text of all module args. [0] is module name */
8750#endif
8751  Trigger *pTrigger;   /* List of triggers stored in pSchema */
8752  Schema *pSchema;     /* Schema that contains this table */
8753  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
8754};
8755
8756/*
8757** Allowed values for Tabe.tabFlags.
8758*/
8759#define TF_Readonly        0x01    /* Read-only system table */
8760#define TF_Ephemeral       0x02    /* An ephemeral table */
8761#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
8762#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
8763#define TF_Virtual         0x10    /* Is a virtual table */
8764#define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
8765
8766
8767
8768/*
8769** Test to see whether or not a table is a virtual table.  This is
8770** done as a macro so that it will be optimized out when virtual
8771** table support is omitted from the build.
8772*/
8773#ifndef SQLITE_OMIT_VIRTUALTABLE
8774#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
8775#  define IsHiddenColumn(X) ((X)->isHidden)
8776#else
8777#  define IsVirtual(X)      0
8778#  define IsHiddenColumn(X) 0
8779#endif
8780
8781/*
8782** Each foreign key constraint is an instance of the following structure.
8783**
8784** A foreign key is associated with two tables.  The "from" table is
8785** the table that contains the REFERENCES clause that creates the foreign
8786** key.  The "to" table is the table that is named in the REFERENCES clause.
8787** Consider this example:
8788**
8789**     CREATE TABLE ex1(
8790**       a INTEGER PRIMARY KEY,
8791**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
8792**     );
8793**
8794** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
8795**
8796** Each REFERENCES clause generates an instance of the following structure
8797** which is attached to the from-table.  The to-table need not exist when
8798** the from-table is created.  The existence of the to-table is not checked.
8799*/
8800struct FKey {
8801  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
8802  FKey *pNextFrom;  /* Next foreign key in pFrom */
8803  char *zTo;        /* Name of table that the key points to (aka: Parent) */
8804  FKey *pNextTo;    /* Next foreign key on table named zTo */
8805  FKey *pPrevTo;    /* Previous foreign key on table named zTo */
8806  int nCol;         /* Number of columns in this key */
8807  /* EV: R-30323-21917 */
8808  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
8809  u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
8810  Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
8811  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
8812    int iFrom;         /* Index of column in pFrom */
8813    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
8814  } aCol[1];        /* One entry for each of nCol column s */
8815};
8816
8817/*
8818** SQLite supports many different ways to resolve a constraint
8819** error.  ROLLBACK processing means that a constraint violation
8820** causes the operation in process to fail and for the current transaction
8821** to be rolled back.  ABORT processing means the operation in process
8822** fails and any prior changes from that one operation are backed out,
8823** but the transaction is not rolled back.  FAIL processing means that
8824** the operation in progress stops and returns an error code.  But prior
8825** changes due to the same operation are not backed out and no rollback
8826** occurs.  IGNORE means that the particular row that caused the constraint
8827** error is not inserted or updated.  Processing continues and no error
8828** is returned.  REPLACE means that preexisting database rows that caused
8829** a UNIQUE constraint violation are removed so that the new insert or
8830** update can proceed.  Processing continues and no error is reported.
8831**
8832** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
8833** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
8834** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
8835** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
8836** referenced table row is propagated into the row that holds the
8837** foreign key.
8838**
8839** The following symbolic values are used to record which type
8840** of action to take.
8841*/
8842#define OE_None     0   /* There is no constraint to check */
8843#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
8844#define OE_Abort    2   /* Back out changes but do no rollback transaction */
8845#define OE_Fail     3   /* Stop the operation but leave all prior changes */
8846#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
8847#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
8848
8849#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
8850#define OE_SetNull  7   /* Set the foreign key value to NULL */
8851#define OE_SetDflt  8   /* Set the foreign key value to its default */
8852#define OE_Cascade  9   /* Cascade the changes */
8853
8854#define OE_Default  99  /* Do whatever the default action is */
8855
8856
8857/*
8858** An instance of the following structure is passed as the first
8859** argument to sqlite3VdbeKeyCompare and is used to control the
8860** comparison of the two index keys.
8861*/
8862struct KeyInfo {
8863  sqlite3 *db;        /* The database connection */
8864  u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
8865  u16 nField;         /* Number of entries in aColl[] */
8866  u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
8867  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
8868};
8869
8870/*
8871** An instance of the following structure holds information about a
8872** single index record that has already been parsed out into individual
8873** values.
8874**
8875** A record is an object that contains one or more fields of data.
8876** Records are used to store the content of a table row and to store
8877** the key of an index.  A blob encoding of a record is created by
8878** the OP_MakeRecord opcode of the VDBE and is disassembled by the
8879** OP_Column opcode.
8880**
8881** This structure holds a record that has already been disassembled
8882** into its constituent fields.
8883*/
8884struct UnpackedRecord {
8885  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
8886  u16 nField;         /* Number of entries in apMem[] */
8887  u16 flags;          /* Boolean settings.  UNPACKED_... below */
8888  i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
8889  Mem *aMem;          /* Values */
8890};
8891
8892/*
8893** Allowed values of UnpackedRecord.flags
8894*/
8895#define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
8896#define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
8897#define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
8898#define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
8899#define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
8900#define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
8901
8902/*
8903** Each SQL index is represented in memory by an
8904** instance of the following structure.
8905**
8906** The columns of the table that are to be indexed are described
8907** by the aiColumn[] field of this structure.  For example, suppose
8908** we have the following table and index:
8909**
8910**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
8911**     CREATE INDEX Ex2 ON Ex1(c3,c1);
8912**
8913** In the Table structure describing Ex1, nCol==3 because there are
8914** three columns in the table.  In the Index structure describing
8915** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
8916** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
8917** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
8918** The second column to be indexed (c1) has an index of 0 in
8919** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
8920**
8921** The Index.onError field determines whether or not the indexed columns
8922** must be unique and what to do if they are not.  When Index.onError=OE_None,
8923** it means this is not a unique index.  Otherwise it is a unique index
8924** and the value of Index.onError indicate the which conflict resolution
8925** algorithm to employ whenever an attempt is made to insert a non-unique
8926** element.
8927*/
8928struct Index {
8929  char *zName;     /* Name of this index */
8930  int nColumn;     /* Number of columns in the table used by this index */
8931  int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
8932  unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
8933  Table *pTable;   /* The SQL table being indexed */
8934  int tnum;        /* Page containing root of this index in database file */
8935  u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
8936  u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
8937  char *zColAff;   /* String defining the affinity of each column */
8938  Index *pNext;    /* The next index associated with the same table */
8939  Schema *pSchema; /* Schema containing this index */
8940  u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
8941  char **azColl;   /* Array of collation sequence names for index */
8942  IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
8943};
8944
8945/*
8946** Each sample stored in the sqlite_stat2 table is represented in memory
8947** using a structure of this type.
8948*/
8949struct IndexSample {
8950  union {
8951    char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
8952    double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
8953  } u;
8954  u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
8955  u8 nByte;         /* Size in byte of text or blob. */
8956};
8957
8958/*
8959** Each token coming out of the lexer is an instance of
8960** this structure.  Tokens are also used as part of an expression.
8961**
8962** Note if Token.z==0 then Token.dyn and Token.n are undefined and
8963** may contain random values.  Do not make any assumptions about Token.dyn
8964** and Token.n when Token.z==0.
8965*/
8966struct Token {
8967  const char *z;     /* Text of the token.  Not NULL-terminated! */
8968  unsigned int n;    /* Number of characters in this token */
8969};
8970
8971/*
8972** An instance of this structure contains information needed to generate
8973** code for a SELECT that contains aggregate functions.
8974**
8975** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
8976** pointer to this structure.  The Expr.iColumn field is the index in
8977** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
8978** code for that node.
8979**
8980** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
8981** original Select structure that describes the SELECT statement.  These
8982** fields do not need to be freed when deallocating the AggInfo structure.
8983*/
8984struct AggInfo {
8985  u8 directMode;          /* Direct rendering mode means take data directly
8986                          ** from source tables rather than from accumulators */
8987  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
8988                          ** than the source table */
8989  int sortingIdx;         /* Cursor number of the sorting index */
8990  ExprList *pGroupBy;     /* The group by clause */
8991  int nSortingColumn;     /* Number of columns in the sorting index */
8992  struct AggInfo_col {    /* For each column used in source tables */
8993    Table *pTab;             /* Source table */
8994    int iTable;              /* Cursor number of the source table */
8995    int iColumn;             /* Column number within the source table */
8996    int iSorterColumn;       /* Column number in the sorting index */
8997    int iMem;                /* Memory location that acts as accumulator */
8998    Expr *pExpr;             /* The original expression */
8999  } *aCol;
9000  int nColumn;            /* Number of used entries in aCol[] */
9001  int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9002  int nAccumulator;       /* Number of columns that show through to the output.
9003                          ** Additional columns are used only as parameters to
9004                          ** aggregate functions */
9005  struct AggInfo_func {   /* For each aggregate function */
9006    Expr *pExpr;             /* Expression encoding the function */
9007    FuncDef *pFunc;          /* The aggregate function implementation */
9008    int iMem;                /* Memory location that acts as accumulator */
9009    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9010  } *aFunc;
9011  int nFunc;              /* Number of entries in aFunc[] */
9012  int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9013};
9014
9015/*
9016** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9017** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9018** than 32767 we have to make it 32-bit.  16-bit is preferred because
9019** it uses less memory in the Expr object, which is a big memory user
9020** in systems with lots of prepared statements.  And few applications
9021** need more than about 10 or 20 variables.  But some extreme users want
9022** to have prepared statements with over 32767 variables, and for them
9023** the option is available (at compile-time).
9024*/
9025#if SQLITE_MAX_VARIABLE_NUMBER<=32767
9026typedef i16 ynVar;
9027#else
9028typedef int ynVar;
9029#endif
9030
9031/*
9032** Each node of an expression in the parse tree is an instance
9033** of this structure.
9034**
9035** Expr.op is the opcode. The integer parser token codes are reused
9036** as opcodes here. For example, the parser defines TK_GE to be an integer
9037** code representing the ">=" operator. This same integer code is reused
9038** to represent the greater-than-or-equal-to operator in the expression
9039** tree.
9040**
9041** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
9042** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9043** the expression is a variable (TK_VARIABLE), then Expr.token contains the
9044** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9045** then Expr.token contains the name of the function.
9046**
9047** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9048** binary operator. Either or both may be NULL.
9049**
9050** Expr.x.pList is a list of arguments if the expression is an SQL function,
9051** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9052** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9053** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9054** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
9055** valid.
9056**
9057** An expression of the form ID or ID.ID refers to a column in a table.
9058** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9059** the integer cursor number of a VDBE cursor pointing to that table and
9060** Expr.iColumn is the column number for the specific column.  If the
9061** expression is used as a result in an aggregate SELECT, then the
9062** value is also stored in the Expr.iAgg column in the aggregate so that
9063** it can be accessed after all aggregates are computed.
9064**
9065** If the expression is an unbound variable marker (a question mark
9066** character '?' in the original SQL) then the Expr.iTable holds the index
9067** number for that variable.
9068**
9069** If the expression is a subquery then Expr.iColumn holds an integer
9070** register number containing the result of the subquery.  If the
9071** subquery gives a constant result, then iTable is -1.  If the subquery
9072** gives a different answer at different times during statement processing
9073** then iTable is the address of a subroutine that computes the subquery.
9074**
9075** If the Expr is of type OP_Column, and the table it is selecting from
9076** is a disk table or the "old.*" pseudo-table, then pTab points to the
9077** corresponding table definition.
9078**
9079** ALLOCATION NOTES:
9080**
9081** Expr objects can use a lot of memory space in database schema.  To
9082** help reduce memory requirements, sometimes an Expr object will be
9083** truncated.  And to reduce the number of memory allocations, sometimes
9084** two or more Expr objects will be stored in a single memory allocation,
9085** together with Expr.zToken strings.
9086**
9087** If the EP_Reduced and EP_TokenOnly flags are set when
9088** an Expr object is truncated.  When EP_Reduced is set, then all
9089** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9090** are contained within the same memory allocation.  Note, however, that
9091** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9092** allocated, regardless of whether or not EP_Reduced is set.
9093*/
9094struct Expr {
9095  u8 op;                 /* Operation performed by this node */
9096  char affinity;         /* The affinity of the column or 0 if not a column */
9097  u16 flags;             /* Various flags.  EP_* See below */
9098  union {
9099    char *zToken;          /* Token value. Zero terminated and dequoted */
9100    int iValue;            /* Integer value if EP_IntValue */
9101  } u;
9102
9103  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9104  ** space is allocated for the fields below this point. An attempt to
9105  ** access them will result in a segfault or malfunction.
9106  *********************************************************************/
9107
9108  Expr *pLeft;           /* Left subnode */
9109  Expr *pRight;          /* Right subnode */
9110  union {
9111    ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9112    Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9113  } x;
9114  CollSeq *pColl;        /* The collation type of the column or 0 */
9115
9116  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9117  ** space is allocated for the fields below this point. An attempt to
9118  ** access them will result in a segfault or malfunction.
9119  *********************************************************************/
9120
9121  int iTable;            /* TK_COLUMN: cursor number of table holding column
9122                         ** TK_REGISTER: register number
9123                         ** TK_TRIGGER: 1 -> new, 0 -> old */
9124  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
9125                         ** TK_VARIABLE: variable number (always >= 1). */
9126  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9127  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9128  u8 flags2;             /* Second set of flags.  EP2_... */
9129  u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
9130  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9131  Table *pTab;           /* Table for TK_COLUMN expressions. */
9132#if SQLITE_MAX_EXPR_DEPTH>0
9133  int nHeight;           /* Height of the tree headed by this node */
9134#endif
9135};
9136
9137/*
9138** The following are the meanings of bits in the Expr.flags field.
9139*/
9140#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9141#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9142#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9143#define EP_Error      0x0008  /* Expression contains one or more errors */
9144#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9145#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9146#define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
9147#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9148#define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9149#define EP_FixedDest  0x0200  /* Result needed in a specific register */
9150#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
9151#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
9152
9153#define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
9154#define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
9155#define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
9156
9157/*
9158** The following are the meanings of bits in the Expr.flags2 field.
9159*/
9160#define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
9161#define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
9162
9163/*
9164** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
9165** flag on an expression structure.  This flag is used for VV&A only.  The
9166** routine is implemented as a macro that only works when in debugging mode,
9167** so as not to burden production code.
9168*/
9169#ifdef SQLITE_DEBUG
9170# define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
9171#else
9172# define ExprSetIrreducible(X)
9173#endif
9174
9175/*
9176** These macros can be used to test, set, or clear bits in the
9177** Expr.flags field.
9178*/
9179#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9180#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9181#define ExprSetProperty(E,P)     (E)->flags|=(P)
9182#define ExprClearProperty(E,P)   (E)->flags&=~(P)
9183
9184/*
9185** Macros to determine the number of bytes required by a normal Expr
9186** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
9187** and an Expr struct with the EP_TokenOnly flag set.
9188*/
9189#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
9190#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
9191#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
9192
9193/*
9194** Flags passed to the sqlite3ExprDup() function. See the header comment
9195** above sqlite3ExprDup() for details.
9196*/
9197#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
9198
9199/*
9200** A list of expressions.  Each expression may optionally have a
9201** name.  An expr/name combination can be used in several ways, such
9202** as the list of "expr AS ID" fields following a "SELECT" or in the
9203** list of "ID = expr" items in an UPDATE.  A list of expressions can
9204** also be used as the argument to a function, in which case the a.zName
9205** field is not used.
9206*/
9207struct ExprList {
9208  int nExpr;             /* Number of expressions on the list */
9209  int nAlloc;            /* Number of entries allocated below */
9210  int iECursor;          /* VDBE Cursor associated with this ExprList */
9211  struct ExprList_item {
9212    Expr *pExpr;           /* The list of expressions */
9213    char *zName;           /* Token associated with this expression */
9214    char *zSpan;           /* Original text of the expression */
9215    u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9216    u8 done;               /* A flag to indicate when processing is finished */
9217    u16 iCol;              /* For ORDER BY, column number in result set */
9218    u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9219  } *a;                  /* One entry for each expression */
9220};
9221
9222/*
9223** An instance of this structure is used by the parser to record both
9224** the parse tree for an expression and the span of input text for an
9225** expression.
9226*/
9227struct ExprSpan {
9228  Expr *pExpr;          /* The expression parse tree */
9229  const char *zStart;   /* First character of input text */
9230  const char *zEnd;     /* One character past the end of input text */
9231};
9232
9233/*
9234** An instance of this structure can hold a simple list of identifiers,
9235** such as the list "a,b,c" in the following statements:
9236**
9237**      INSERT INTO t(a,b,c) VALUES ...;
9238**      CREATE INDEX idx ON t(a,b,c);
9239**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9240**
9241** The IdList.a.idx field is used when the IdList represents the list of
9242** column names after a table name in an INSERT statement.  In the statement
9243**
9244**     INSERT INTO t(a,b,c) ...
9245**
9246** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9247*/
9248struct IdList {
9249  struct IdList_item {
9250    char *zName;      /* Name of the identifier */
9251    int idx;          /* Index in some Table.aCol[] of a column named zName */
9252  } *a;
9253  int nId;         /* Number of identifiers on the list */
9254  int nAlloc;      /* Number of entries allocated for a[] below */
9255};
9256
9257/*
9258** The bitmask datatype defined below is used for various optimizations.
9259**
9260** Changing this from a 64-bit to a 32-bit type limits the number of
9261** tables in a join to 32 instead of 64.  But it also reduces the size
9262** of the library by 738 bytes on ix86.
9263*/
9264typedef u64 Bitmask;
9265
9266/*
9267** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
9268*/
9269#define BMS  ((int)(sizeof(Bitmask)*8))
9270
9271/*
9272** The following structure describes the FROM clause of a SELECT statement.
9273** Each table or subquery in the FROM clause is a separate element of
9274** the SrcList.a[] array.
9275**
9276** With the addition of multiple database support, the following structure
9277** can also be used to describe a particular table such as the table that
9278** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9279** such a table must be a simple name: ID.  But in SQLite, the table can
9280** now be identified by a database name, a dot, then the table name: ID.ID.
9281**
9282** The jointype starts out showing the join type between the current table
9283** and the next table on the list.  The parser builds the list this way.
9284** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9285** jointype expresses the join between the table and the previous table.
9286*/
9287struct SrcList {
9288  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9289  i16 nAlloc;      /* Number of entries allocated in a[] below */
9290  struct SrcList_item {
9291    char *zDatabase;  /* Name of database holding this table */
9292    char *zName;      /* Name of the table */
9293    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9294    Table *pTab;      /* An SQL table corresponding to zName */
9295    Select *pSelect;  /* A SELECT statement used in place of a table name */
9296    u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9297    u8 jointype;      /* Type of join between this able and the previous */
9298    u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9299    int iCursor;      /* The VDBE cursor number used to access this table */
9300    Expr *pOn;        /* The ON clause of a join */
9301    IdList *pUsing;   /* The USING clause of a join */
9302    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
9303    char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9304    Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9305  } a[1];             /* One entry for each identifier on the list */
9306};
9307
9308/*
9309** Permitted values of the SrcList.a.jointype field
9310*/
9311#define JT_INNER     0x0001    /* Any kind of inner or cross join */
9312#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9313#define JT_NATURAL   0x0004    /* True for a "natural" join */
9314#define JT_LEFT      0x0008    /* Left outer join */
9315#define JT_RIGHT     0x0010    /* Right outer join */
9316#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9317#define JT_ERROR     0x0040    /* unknown or unsupported join type */
9318
9319
9320/*
9321** A WherePlan object holds information that describes a lookup
9322** strategy.
9323**
9324** This object is intended to be opaque outside of the where.c module.
9325** It is included here only so that that compiler will know how big it
9326** is.  None of the fields in this object should be used outside of
9327** the where.c module.
9328**
9329** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
9330** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
9331** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
9332** case that more than one of these conditions is true.
9333*/
9334struct WherePlan {
9335  u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
9336  u32 nEq;                       /* Number of == constraints */
9337  union {
9338    Index *pIdx;                   /* Index when WHERE_INDEXED is true */
9339    struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
9340    sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
9341  } u;
9342};
9343
9344/*
9345** For each nested loop in a WHERE clause implementation, the WhereInfo
9346** structure contains a single instance of this structure.  This structure
9347** is intended to be private the the where.c module and should not be
9348** access or modified by other modules.
9349**
9350** The pIdxInfo field is used to help pick the best index on a
9351** virtual table.  The pIdxInfo pointer contains indexing
9352** information for the i-th table in the FROM clause before reordering.
9353** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9354** All other information in the i-th WhereLevel object for the i-th table
9355** after FROM clause ordering.
9356*/
9357struct WhereLevel {
9358  WherePlan plan;       /* query plan for this element of the FROM clause */
9359  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9360  int iTabCur;          /* The VDBE cursor used to access the table */
9361  int iIdxCur;          /* The VDBE cursor used to access pIdx */
9362  int addrBrk;          /* Jump here to break out of the loop */
9363  int addrNxt;          /* Jump here to start the next IN combination */
9364  int addrCont;         /* Jump here to continue with the next loop cycle */
9365  int addrFirst;        /* First instruction of interior of the loop */
9366  u8 iFrom;             /* Which entry in the FROM clause */
9367  u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
9368  int p1, p2;           /* Operands of the opcode used to ends the loop */
9369  union {               /* Information that depends on plan.wsFlags */
9370    struct {
9371      int nIn;              /* Number of entries in aInLoop[] */
9372      struct InLoop {
9373        int iCur;              /* The VDBE cursor used by this IN operator */
9374        int addrInTop;         /* Top of the IN loop */
9375      } *aInLoop;           /* Information about each nested IN operator */
9376    } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
9377  } u;
9378
9379  /* The following field is really not part of the current level.  But
9380  ** we need a place to cache virtual table index information for each
9381  ** virtual table in the FROM clause and the WhereLevel structure is
9382  ** a convenient place since there is one WhereLevel for each FROM clause
9383  ** element.
9384  */
9385  sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9386};
9387
9388/*
9389** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
9390** and the WhereInfo.wctrlFlags member.
9391*/
9392#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
9393#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
9394#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
9395#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
9396#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
9397#define WHERE_OMIT_OPEN        0x0010 /* Table cursor are already open */
9398#define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
9399#define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
9400#define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
9401
9402/*
9403** The WHERE clause processing routine has two halves.  The
9404** first part does the start of the WHERE loop and the second
9405** half does the tail of the WHERE loop.  An instance of
9406** this structure is returned by the first half and passed
9407** into the second half to give some continuity.
9408*/
9409struct WhereInfo {
9410  Parse *pParse;       /* Parsing and code generating context */
9411  u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
9412  u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
9413  u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
9414  SrcList *pTabList;             /* List of tables in the join */
9415  int iTop;                      /* The very beginning of the WHERE loop */
9416  int iContinue;                 /* Jump here to continue with next record */
9417  int iBreak;                    /* Jump here to break out of the loop */
9418  int nLevel;                    /* Number of nested loop */
9419  struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
9420  WhereLevel a[1];               /* Information about each nest loop in WHERE */
9421};
9422
9423/*
9424** A NameContext defines a context in which to resolve table and column
9425** names.  The context consists of a list of tables (the pSrcList) field and
9426** a list of named expression (pEList).  The named expression list may
9427** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
9428** to the table being operated on by INSERT, UPDATE, or DELETE.  The
9429** pEList corresponds to the result set of a SELECT and is NULL for
9430** other statements.
9431**
9432** NameContexts can be nested.  When resolving names, the inner-most
9433** context is searched first.  If no match is found, the next outer
9434** context is checked.  If there is still no match, the next context
9435** is checked.  This process continues until either a match is found
9436** or all contexts are check.  When a match is found, the nRef member of
9437** the context containing the match is incremented.
9438**
9439** Each subquery gets a new NameContext.  The pNext field points to the
9440** NameContext in the parent query.  Thus the process of scanning the
9441** NameContext list corresponds to searching through successively outer
9442** subqueries looking for a match.
9443*/
9444struct NameContext {
9445  Parse *pParse;       /* The parser */
9446  SrcList *pSrcList;   /* One or more tables used to resolve names */
9447  ExprList *pEList;    /* Optional list of named expressions */
9448  int nRef;            /* Number of names resolved by this context */
9449  int nErr;            /* Number of errors encountered while resolving names */
9450  u8 allowAgg;         /* Aggregate functions allowed here */
9451  u8 hasAgg;           /* True if aggregates are seen */
9452  u8 isCheck;          /* True if resolving names in a CHECK constraint */
9453  int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
9454  AggInfo *pAggInfo;   /* Information about aggregates at this level */
9455  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
9456};
9457
9458/*
9459** An instance of the following structure contains all information
9460** needed to generate code for a single SELECT statement.
9461**
9462** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
9463** If there is a LIMIT clause, the parser sets nLimit to the value of the
9464** limit and nOffset to the value of the offset (or 0 if there is not
9465** offset).  But later on, nLimit and nOffset become the memory locations
9466** in the VDBE that record the limit and offset counters.
9467**
9468** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
9469** These addresses must be stored so that we can go back and fill in
9470** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
9471** the number of columns in P2 can be computed at the same time
9472** as the OP_OpenEphm instruction is coded because not
9473** enough information about the compound query is known at that point.
9474** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
9475** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
9476** sequences for the ORDER BY clause.
9477*/
9478struct Select {
9479  ExprList *pEList;      /* The fields of the result */
9480  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
9481  char affinity;         /* MakeRecord with this affinity for SRT_Set */
9482  u16 selFlags;          /* Various SF_* values */
9483  SrcList *pSrc;         /* The FROM clause */
9484  Expr *pWhere;          /* The WHERE clause */
9485  ExprList *pGroupBy;    /* The GROUP BY clause */
9486  Expr *pHaving;         /* The HAVING clause */
9487  ExprList *pOrderBy;    /* The ORDER BY clause */
9488  Select *pPrior;        /* Prior select in a compound select statement */
9489  Select *pNext;         /* Next select to the left in a compound */
9490  Select *pRightmost;    /* Right-most select in a compound select statement */
9491  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
9492  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
9493  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
9494  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
9495};
9496
9497/*
9498** Allowed values for Select.selFlags.  The "SF" prefix stands for
9499** "Select Flag".
9500*/
9501#define SF_Distinct        0x0001  /* Output should be DISTINCT */
9502#define SF_Resolved        0x0002  /* Identifiers have been resolved */
9503#define SF_Aggregate       0x0004  /* Contains aggregate functions */
9504#define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
9505#define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
9506#define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
9507
9508
9509/*
9510** The results of a select can be distributed in several ways.  The
9511** "SRT" prefix means "SELECT Result Type".
9512*/
9513#define SRT_Union        1  /* Store result as keys in an index */
9514#define SRT_Except       2  /* Remove result from a UNION index */
9515#define SRT_Exists       3  /* Store 1 if the result is not empty */
9516#define SRT_Discard      4  /* Do not save the results anywhere */
9517
9518/* The ORDER BY clause is ignored for all of the above */
9519#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
9520
9521#define SRT_Output       5  /* Output each row of result */
9522#define SRT_Mem          6  /* Store result in a memory cell */
9523#define SRT_Set          7  /* Store results as keys in an index */
9524#define SRT_Table        8  /* Store result as data with an automatic rowid */
9525#define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
9526#define SRT_Coroutine   10  /* Generate a single row of result */
9527
9528/*
9529** A structure used to customize the behavior of sqlite3Select(). See
9530** comments above sqlite3Select() for details.
9531*/
9532typedef struct SelectDest SelectDest;
9533struct SelectDest {
9534  u8 eDest;         /* How to dispose of the results */
9535  u8 affinity;      /* Affinity used when eDest==SRT_Set */
9536  int iParm;        /* A parameter used by the eDest disposal method */
9537  int iMem;         /* Base register where results are written */
9538  int nMem;         /* Number of registers allocated */
9539};
9540
9541/*
9542** During code generation of statements that do inserts into AUTOINCREMENT
9543** tables, the following information is attached to the Table.u.autoInc.p
9544** pointer of each autoincrement table to record some side information that
9545** the code generator needs.  We have to keep per-table autoincrement
9546** information in case inserts are down within triggers.  Triggers do not
9547** normally coordinate their activities, but we do need to coordinate the
9548** loading and saving of autoincrement information.
9549*/
9550struct AutoincInfo {
9551  AutoincInfo *pNext;   /* Next info block in a list of them all */
9552  Table *pTab;          /* Table this info block refers to */
9553  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
9554  int regCtr;           /* Memory register holding the rowid counter */
9555};
9556
9557/*
9558** Size of the column cache
9559*/
9560#ifndef SQLITE_N_COLCACHE
9561# define SQLITE_N_COLCACHE 10
9562#endif
9563
9564/*
9565** At least one instance of the following structure is created for each
9566** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
9567** statement. All such objects are stored in the linked list headed at
9568** Parse.pTriggerPrg and deleted once statement compilation has been
9569** completed.
9570**
9571** A Vdbe sub-program that implements the body and WHEN clause of trigger
9572** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
9573** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
9574** The Parse.pTriggerPrg list never contains two entries with the same
9575** values for both pTrigger and orconf.
9576**
9577** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
9578** accessed (or set to 0 for triggers fired as a result of INSERT
9579** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
9580** a mask of new.* columns used by the program.
9581*/
9582struct TriggerPrg {
9583  Trigger *pTrigger;      /* Trigger this program was coded from */
9584  int orconf;             /* Default ON CONFLICT policy */
9585  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
9586  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
9587  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
9588};
9589
9590/*
9591** An SQL parser context.  A copy of this structure is passed through
9592** the parser and down into all the parser action routine in order to
9593** carry around information that is global to the entire parse.
9594**
9595** The structure is divided into two parts.  When the parser and code
9596** generate call themselves recursively, the first part of the structure
9597** is constant but the second part is reset at the beginning and end of
9598** each recursion.
9599**
9600** The nTableLock and aTableLock variables are only used if the shared-cache
9601** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
9602** used to store the set of table-locks required by the statement being
9603** compiled. Function sqlite3TableLock() is used to add entries to the
9604** list.
9605*/
9606struct Parse {
9607  sqlite3 *db;         /* The main database structure */
9608  int rc;              /* Return code from execution */
9609  char *zErrMsg;       /* An error message */
9610  Vdbe *pVdbe;         /* An engine for executing database bytecode */
9611  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
9612  u8 nameClash;        /* A permanent table name clashes with temp table name */
9613  u8 checkSchema;      /* Causes schema cookie check after an error */
9614  u8 nested;           /* Number of nested calls to the parser/code generator */
9615  u8 parseError;       /* True after a parsing error.  Ticket #1794 */
9616  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
9617  u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
9618  int aTempReg[8];     /* Holding area for temporary registers */
9619  int nRangeReg;       /* Size of the temporary register block */
9620  int iRangeReg;       /* First register in temporary register block */
9621  int nErr;            /* Number of errors seen */
9622  int nTab;            /* Number of previously allocated VDBE cursors */
9623  int nMem;            /* Number of memory cells used so far */
9624  int nSet;            /* Number of sets used so far */
9625  int ckBase;          /* Base register of data during check constraints */
9626  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
9627  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
9628  u8 nColCache;        /* Number of entries in the column cache */
9629  u8 iColCache;        /* Next entry of the cache to replace */
9630  struct yColCache {
9631    int iTable;           /* Table cursor number */
9632    int iColumn;          /* Table column number */
9633    u8 tempReg;           /* iReg is a temp register that needs to be freed */
9634    int iLevel;           /* Nesting level */
9635    int iReg;             /* Reg with value of this column. 0 means none. */
9636    int lru;              /* Least recently used entry has the smallest value */
9637  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
9638  u32 writeMask;       /* Start a write transaction on these databases */
9639  u32 cookieMask;      /* Bitmask of schema verified databases */
9640  u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
9641  u8 mayAbort;         /* True if statement may throw an ABORT exception */
9642  int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
9643  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
9644#ifndef SQLITE_OMIT_SHARED_CACHE
9645  int nTableLock;        /* Number of locks in aTableLock */
9646  TableLock *aTableLock; /* Required table locks for shared-cache mode */
9647#endif
9648  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
9649  int regRoot;         /* Register holding root page number for new objects */
9650  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
9651  int nMaxArg;         /* Max args passed to user function by sub-program */
9652
9653  /* Information used while coding trigger programs. */
9654  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
9655  Table *pTriggerTab;  /* Table triggers are being coded for */
9656  u32 oldmask;         /* Mask of old.* columns referenced */
9657  u32 newmask;         /* Mask of new.* columns referenced */
9658  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
9659  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
9660  u8 disableTriggers;  /* True to disable triggers */
9661
9662  /* Above is constant between recursions.  Below is reset before and after
9663  ** each recursion */
9664
9665  int nVar;            /* Number of '?' variables seen in the SQL so far */
9666  int nVarExpr;        /* Number of used slots in apVarExpr[] */
9667  int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
9668  Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
9669  Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
9670  int nAlias;          /* Number of aliased result set columns */
9671  int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
9672  int *aAlias;         /* Register used to hold aliased result */
9673  u8 explain;          /* True if the EXPLAIN flag is found on the query */
9674  Token sNameToken;    /* Token with unqualified schema object name */
9675  Token sLastToken;    /* The last token parsed */
9676  const char *zTail;   /* All SQL text past the last semicolon parsed */
9677  Table *pNewTable;    /* A table being constructed by CREATE TABLE */
9678  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
9679  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
9680#ifndef SQLITE_OMIT_VIRTUALTABLE
9681  Token sArg;                /* Complete text of a module argument */
9682  u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
9683  int nVtabLock;             /* Number of virtual tables to lock */
9684  Table **apVtabLock;        /* Pointer to virtual tables needing locking */
9685#endif
9686  int nHeight;            /* Expression tree height of current sub-select */
9687  Table *pZombieTab;      /* List of Table objects to delete after code gen */
9688  TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
9689};
9690
9691#ifdef SQLITE_OMIT_VIRTUALTABLE
9692  #define IN_DECLARE_VTAB 0
9693#else
9694  #define IN_DECLARE_VTAB (pParse->declareVtab)
9695#endif
9696
9697/*
9698** An instance of the following structure can be declared on a stack and used
9699** to save the Parse.zAuthContext value so that it can be restored later.
9700*/
9701struct AuthContext {
9702  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
9703  Parse *pParse;              /* The Parse structure */
9704};
9705
9706/*
9707** Bitfield flags for P5 value in OP_Insert and OP_Delete
9708*/
9709#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
9710#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
9711#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
9712#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
9713#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
9714#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
9715
9716/*
9717 * Each trigger present in the database schema is stored as an instance of
9718 * struct Trigger.
9719 *
9720 * Pointers to instances of struct Trigger are stored in two ways.
9721 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
9722 *    database). This allows Trigger structures to be retrieved by name.
9723 * 2. All triggers associated with a single table form a linked list, using the
9724 *    pNext member of struct Trigger. A pointer to the first element of the
9725 *    linked list is stored as the "pTrigger" member of the associated
9726 *    struct Table.
9727 *
9728 * The "step_list" member points to the first element of a linked list
9729 * containing the SQL statements specified as the trigger program.
9730 */
9731struct Trigger {
9732  char *zName;            /* The name of the trigger                        */
9733  char *table;            /* The table or view to which the trigger applies */
9734  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
9735  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
9736  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
9737  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
9738                             the <column-list> is stored here */
9739  Schema *pSchema;        /* Schema containing the trigger */
9740  Schema *pTabSchema;     /* Schema containing the table */
9741  TriggerStep *step_list; /* Link list of trigger program steps             */
9742  Trigger *pNext;         /* Next trigger associated with the table */
9743};
9744
9745/*
9746** A trigger is either a BEFORE or an AFTER trigger.  The following constants
9747** determine which.
9748**
9749** If there are multiple triggers, you might of some BEFORE and some AFTER.
9750** In that cases, the constants below can be ORed together.
9751*/
9752#define TRIGGER_BEFORE  1
9753#define TRIGGER_AFTER   2
9754
9755/*
9756 * An instance of struct TriggerStep is used to store a single SQL statement
9757 * that is a part of a trigger-program.
9758 *
9759 * Instances of struct TriggerStep are stored in a singly linked list (linked
9760 * using the "pNext" member) referenced by the "step_list" member of the
9761 * associated struct Trigger instance. The first element of the linked list is
9762 * the first step of the trigger-program.
9763 *
9764 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
9765 * "SELECT" statement. The meanings of the other members is determined by the
9766 * value of "op" as follows:
9767 *
9768 * (op == TK_INSERT)
9769 * orconf    -> stores the ON CONFLICT algorithm
9770 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
9771 *              this stores a pointer to the SELECT statement. Otherwise NULL.
9772 * target    -> A token holding the quoted name of the table to insert into.
9773 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
9774 *              this stores values to be inserted. Otherwise NULL.
9775 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
9776 *              statement, then this stores the column-names to be
9777 *              inserted into.
9778 *
9779 * (op == TK_DELETE)
9780 * target    -> A token holding the quoted name of the table to delete from.
9781 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
9782 *              Otherwise NULL.
9783 *
9784 * (op == TK_UPDATE)
9785 * target    -> A token holding the quoted name of the table to update rows of.
9786 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
9787 *              Otherwise NULL.
9788 * pExprList -> A list of the columns to update and the expressions to update
9789 *              them to. See sqlite3Update() documentation of "pChanges"
9790 *              argument.
9791 *
9792 */
9793struct TriggerStep {
9794  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
9795  u8 orconf;           /* OE_Rollback etc. */
9796  Trigger *pTrig;      /* The trigger that this step is a part of */
9797  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
9798  Token target;        /* Target table for DELETE, UPDATE, INSERT */
9799  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
9800  ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
9801  IdList *pIdList;     /* Column names for INSERT */
9802  TriggerStep *pNext;  /* Next in the link-list */
9803  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
9804};
9805
9806/*
9807** The following structure contains information used by the sqliteFix...
9808** routines as they walk the parse tree to make database references
9809** explicit.
9810*/
9811typedef struct DbFixer DbFixer;
9812struct DbFixer {
9813  Parse *pParse;      /* The parsing context.  Error messages written here */
9814  const char *zDb;    /* Make sure all objects are contained in this database */
9815  const char *zType;  /* Type of the container - used for error messages */
9816  const Token *pName; /* Name of the container - used for error messages */
9817};
9818
9819/*
9820** An objected used to accumulate the text of a string where we
9821** do not necessarily know how big the string will be in the end.
9822*/
9823struct StrAccum {
9824  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
9825  char *zBase;         /* A base allocation.  Not from malloc. */
9826  char *zText;         /* The string collected so far */
9827  int  nChar;          /* Length of the string so far */
9828  int  nAlloc;         /* Amount of space allocated in zText */
9829  int  mxAlloc;        /* Maximum allowed string length */
9830  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
9831  u8   useMalloc;      /* True if zText is enlargeable using realloc */
9832  u8   tooBig;         /* Becomes true if string size exceeds limits */
9833};
9834
9835/*
9836** A pointer to this structure is used to communicate information
9837** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
9838*/
9839typedef struct {
9840  sqlite3 *db;        /* The database being initialized */
9841  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
9842  char **pzErrMsg;    /* Error message stored here */
9843  int rc;             /* Result code stored here */
9844} InitData;
9845
9846/*
9847** Structure containing global configuration data for the SQLite library.
9848**
9849** This structure also contains some state information.
9850*/
9851struct Sqlite3Config {
9852  int bMemstat;                     /* True to enable memory status */
9853  int bCoreMutex;                   /* True to enable core mutexing */
9854  int bFullMutex;                   /* True to enable full mutexing */
9855  int mxStrlen;                     /* Maximum string length */
9856  int szLookaside;                  /* Default lookaside buffer size */
9857  int nLookaside;                   /* Default lookaside buffer count */
9858  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
9859  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
9860  sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
9861  void *pHeap;                      /* Heap storage space */
9862  int nHeap;                        /* Size of pHeap[] */
9863  int mnReq, mxReq;                 /* Min and max heap requests sizes */
9864  void *pScratch;                   /* Scratch memory */
9865  int szScratch;                    /* Size of each scratch buffer */
9866  int nScratch;                     /* Number of scratch buffers */
9867  void *pPage;                      /* Page cache memory */
9868  int szPage;                       /* Size of each page in pPage[] */
9869  int nPage;                        /* Number of pages in pPage[] */
9870  int mxParserStack;                /* maximum depth of the parser stack */
9871  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
9872  /* The above might be initialized to non-zero.  The following need to always
9873  ** initially be zero, however. */
9874  int isInit;                       /* True after initialization has finished */
9875  int inProgress;                   /* True while initialization in progress */
9876  int isMutexInit;                  /* True after mutexes are initialized */
9877  int isMallocInit;                 /* True after malloc is initialized */
9878  int isPCacheInit;                 /* True after malloc is initialized */
9879  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
9880  int nRefInitMutex;                /* Number of users of pInitMutex */
9881};
9882
9883/*
9884** Context pointer passed down through the tree-walk.
9885*/
9886struct Walker {
9887  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
9888  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
9889  Parse *pParse;                            /* Parser context.  */
9890  union {                                   /* Extra data for callback */
9891    NameContext *pNC;                          /* Naming context */
9892    int i;                                     /* Integer value */
9893  } u;
9894};
9895
9896/* Forward declarations */
9897SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
9898SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
9899SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
9900SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
9901SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
9902
9903/*
9904** Return code from the parse-tree walking primitives and their
9905** callbacks.
9906*/
9907#define WRC_Continue    0   /* Continue down into children */
9908#define WRC_Prune       1   /* Omit children but continue walking siblings */
9909#define WRC_Abort       2   /* Abandon the tree walk */
9910
9911/*
9912** Assuming zIn points to the first byte of a UTF-8 character,
9913** advance zIn to point to the first byte of the next UTF-8 character.
9914*/
9915#define SQLITE_SKIP_UTF8(zIn) {                        \
9916  if( (*(zIn++))>=0xc0 ){                              \
9917    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
9918  }                                                    \
9919}
9920
9921/*
9922** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
9923** builds) or a function call (for debugging).  If it is a function call,
9924** it allows the operator to set a breakpoint at the spot where database
9925** corruption is first detected.
9926*/
9927#ifdef SQLITE_DEBUG
9928SQLITE_PRIVATE   int sqlite3Corrupt(void);
9929# define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
9930#else
9931# define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
9932#endif
9933
9934/*
9935** The ctype.h header is needed for non-ASCII systems.  It is also
9936** needed by FTS3 when FTS3 is included in the amalgamation.
9937*/
9938#if !defined(SQLITE_ASCII) || \
9939    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
9940# include <ctype.h>
9941#endif
9942
9943/*
9944** The following macros mimic the standard library functions toupper(),
9945** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
9946** sqlite versions only work for ASCII characters, regardless of locale.
9947*/
9948#ifdef SQLITE_ASCII
9949# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
9950# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
9951# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
9952# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
9953# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
9954# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
9955# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
9956#else
9957# define sqlite3Toupper(x)   toupper((unsigned char)(x))
9958# define sqlite3Isspace(x)   isspace((unsigned char)(x))
9959# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
9960# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
9961# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
9962# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
9963# define sqlite3Tolower(x)   tolower((unsigned char)(x))
9964#endif
9965
9966/*
9967** Internal function prototypes
9968*/
9969SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
9970SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
9971SQLITE_PRIVATE int sqlite3Strlen30(const char*);
9972#define sqlite3StrNICmp sqlite3_strnicmp
9973
9974SQLITE_PRIVATE int sqlite3MallocInit(void);
9975SQLITE_PRIVATE void sqlite3MallocEnd(void);
9976SQLITE_PRIVATE void *sqlite3Malloc(int);
9977SQLITE_PRIVATE void *sqlite3MallocZero(int);
9978SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
9979SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
9980SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
9981SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
9982SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
9983SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
9984SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
9985SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
9986SQLITE_PRIVATE int sqlite3MallocSize(void*);
9987SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
9988SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
9989SQLITE_PRIVATE void sqlite3ScratchFree(void*);
9990SQLITE_PRIVATE void *sqlite3PageMalloc(int);
9991SQLITE_PRIVATE void sqlite3PageFree(void*);
9992SQLITE_PRIVATE void sqlite3MemSetDefault(void);
9993SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
9994SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
9995
9996/*
9997** On systems with ample stack space and that support alloca(), make
9998** use of alloca() to obtain space for large automatic objects.  By default,
9999** obtain space from malloc().
10000**
10001** The alloca() routine never returns NULL.  This will cause code paths
10002** that deal with sqlite3StackAlloc() failures to be unreachable.
10003*/
10004#ifdef SQLITE_USE_ALLOCA
10005# define sqlite3StackAllocRaw(D,N)   alloca(N)
10006# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10007# define sqlite3StackFree(D,P)
10008#else
10009# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10010# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10011# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10012#endif
10013
10014#ifdef SQLITE_ENABLE_MEMSYS3
10015SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10016#endif
10017#ifdef SQLITE_ENABLE_MEMSYS5
10018SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10019#endif
10020
10021
10022#ifndef SQLITE_MUTEX_OMIT
10023SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
10024SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10025SQLITE_PRIVATE   int sqlite3MutexInit(void);
10026SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10027#endif
10028
10029SQLITE_PRIVATE int sqlite3StatusValue(int);
10030SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10031SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10032
10033SQLITE_PRIVATE int sqlite3IsNaN(double);
10034
10035SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10036#ifndef SQLITE_OMIT_TRACE
10037SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10038#endif
10039SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10040SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10041SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10042#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10043SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10044#endif
10045#if defined(SQLITE_TEST)
10046SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10047#endif
10048SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10049SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10050SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
10051SQLITE_PRIVATE int sqlite3Dequote(char*);
10052SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10053SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10054SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10055SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10056SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10057SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10058SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10059SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10060SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10061SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10062SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10063SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10064SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10065SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10066SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10067SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10068SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10069SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10070SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10071SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10072SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10073SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10074SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10075SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10076SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10077SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10078SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10079SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10080SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10081SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10082SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10083SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10084SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10085SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
10086SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10087SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10088
10089SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10090SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10091SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10092SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
10093SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10094SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10095SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10096
10097SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
10098SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
10099SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
10100SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
10101SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
10102
10103SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10104
10105#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10106SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10107#else
10108# define sqlite3ViewGetColumnNames(A,B) 0
10109#endif
10110
10111SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10112SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
10113#ifndef SQLITE_OMIT_AUTOINCREMENT
10114SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10115SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10116#else
10117# define sqlite3AutoincrementBegin(X)
10118# define sqlite3AutoincrementEnd(X)
10119#endif
10120SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10121SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10122SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10123SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10124SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10125SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10126SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10127                                      Token*, Select*, Expr*, IdList*);
10128SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10129SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10130SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10131SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10132SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10133SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10134SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10135                        Token*, int, int);
10136SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10137SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10138SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10139                         Expr*,ExprList*,int,Expr*,Expr*);
10140SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10141SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10142SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10143SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10144#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10145SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10146#endif
10147SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10148SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10149SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10150SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10151SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10152SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10153SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10154SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10155SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10156SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10157SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10158SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10159SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10160SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10161SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10162SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10163SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10164SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10165SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10166SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10167SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10168SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10169SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10170SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10171SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10172SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10173SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10174SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10175SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10176SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10177SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10178SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10179SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10180SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10181SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10182SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10183SQLITE_PRIVATE void sqlite3PrngResetState(void);
10184SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10185SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10186SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10187SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10188SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10189SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
10190SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
10191SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10192SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10193SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10194SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10195SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
10196SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
10197SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
10198SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10199SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
10200SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10201SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10202SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10203                                     int*,int,int,int,int,int*);
10204SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10205SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10206SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10207SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
10208SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
10209SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
10210SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
10211SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
10212SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
10213SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10214SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
10215SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10216SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10217SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10218SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10219SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10220#ifdef SQLITE_DEBUG
10221SQLITE_PRIVATE   int sqlite3SafetyOn(sqlite3*);
10222SQLITE_PRIVATE   int sqlite3SafetyOff(sqlite3*);
10223#else
10224# define sqlite3SafetyOn(A) 0
10225# define sqlite3SafetyOff(A) 0
10226#endif
10227SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10228SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10229SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10230
10231#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10232SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10233#endif
10234
10235#ifndef SQLITE_OMIT_TRIGGER
10236SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10237                           Expr*,int, int);
10238SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10239SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10240SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10241SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
10242SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
10243SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
10244                            int, int, int);
10245SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
10246  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10247SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10248SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10249SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10250                                        ExprList*,Select*,u8);
10251SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
10252SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10253SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10254SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10255SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
10256# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
10257#else
10258# define sqlite3TriggersExist(B,C,D,E,F) 0
10259# define sqlite3DeleteTrigger(A,B)
10260# define sqlite3DropTriggerPtr(A,B)
10261# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10262# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
10263# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
10264# define sqlite3TriggerList(X, Y) 0
10265# define sqlite3ParseToplevel(p) p
10266# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
10267#endif
10268
10269SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10270SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10271SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10272#ifndef SQLITE_OMIT_AUTHORIZATION
10273SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10274SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10275SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10276SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10277SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
10278#else
10279# define sqlite3AuthRead(a,b,c,d)
10280# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10281# define sqlite3AuthContextPush(a,b,c)
10282# define sqlite3AuthContextPop(a)  ((void)(a))
10283#endif
10284SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10285SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10286SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
10287                       int omitJournal, int nCache, int flags, Btree **ppBtree);
10288SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10289SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10290SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10291SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10292SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10293SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10294SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10295SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10296SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10297SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10298SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10299SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
10300
10301/*
10302** Routines to read and write variable-length integers.  These used to
10303** be defined locally, but now we use the varint routines in the util.c
10304** file.  Code should use the MACRO forms below, as the Varint32 versions
10305** are coded to assume the single byte case is already handled (which
10306** the MACRO form does).
10307*/
10308SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10309SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10310SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
10311SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
10312SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10313
10314/*
10315** The header of a record consists of a sequence variable-length integers.
10316** These integers are almost always small and are encoded as a single byte.
10317** The following macros take advantage this fact to provide a fast encode
10318** and decode of the integers in a record header.  It is faster for the common
10319** case where the integer is a single byte.  It is a little slower when the
10320** integer is two or more bytes.  But overall it is faster.
10321**
10322** The following expressions are equivalent:
10323**
10324**     x = sqlite3GetVarint32( A, &B );
10325**     x = sqlite3PutVarint32( A, B );
10326**
10327**     x = getVarint32( A, B );
10328**     x = putVarint32( A, B );
10329**
10330*/
10331#define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
10332#define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10333#define getVarint    sqlite3GetVarint
10334#define putVarint    sqlite3PutVarint
10335
10336
10337SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
10338SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10339SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10340SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10341SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10342SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10343SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10344SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10345SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10346SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10347SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10348SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
10349SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
10350SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10351SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10352SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10353SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10354SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10355
10356SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10357SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10358SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
10359                        void(*)(void*));
10360SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10361SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10362SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
10363#ifdef SQLITE_ENABLE_STAT2
10364SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
10365#endif
10366SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10367SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10368#ifndef SQLITE_AMALGAMATION
10369SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
10370SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10371SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
10372SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10373SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10374SQLITE_PRIVATE int sqlite3PendingByte;
10375#endif
10376SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10377SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10378SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
10379SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10380SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10381SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10382SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10383SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
10384SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10385SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10386SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10387SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10388SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
10389SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10390SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10391SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
10392SQLITE_PRIVATE char sqlite3AffinityType(const char*);
10393SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10394SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10395SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10396SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
10397SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10398SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index*);
10399SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10400SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10401SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10402SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10403SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10404SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10405SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10406SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10407SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
10408  void (*)(sqlite3_context*,int,sqlite3_value **),
10409  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10410SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10411SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10412
10413SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10414SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10415SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10416SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10417SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10418SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
10419
10420SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
10421SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
10422
10423/*
10424** The interface to the LEMON-generated parser
10425*/
10426SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10427SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10428SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10429#ifdef YYTRACKMAXSTACKDEPTH
10430SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10431#endif
10432
10433SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
10434#ifndef SQLITE_OMIT_LOAD_EXTENSION
10435SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10436#else
10437# define sqlite3CloseExtensions(X)
10438#endif
10439
10440#ifndef SQLITE_OMIT_SHARED_CACHE
10441SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10442#else
10443  #define sqlite3TableLock(v,w,x,y,z)
10444#endif
10445
10446#ifdef SQLITE_TEST
10447SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10448#endif
10449
10450#ifdef SQLITE_OMIT_VIRTUALTABLE
10451#  define sqlite3VtabClear(Y)
10452#  define sqlite3VtabSync(X,Y) SQLITE_OK
10453#  define sqlite3VtabRollback(X)
10454#  define sqlite3VtabCommit(X)
10455#  define sqlite3VtabInSync(db) 0
10456#  define sqlite3VtabLock(X)
10457#  define sqlite3VtabUnlock(X)
10458#  define sqlite3VtabUnlockList(X)
10459#else
10460SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10461SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10462SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10463SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10464SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
10465SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
10466SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
10467#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
10468#endif
10469SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10470SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10471SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10472SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10473SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10474SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10475SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10476SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10477SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
10478SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10479SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10480SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
10481SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10482SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10483SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10484SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10485SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10486SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
10487
10488/* Declarations for functions in fkey.c. All of these are replaced by
10489** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
10490** key functionality is available. If OMIT_TRIGGER is defined but
10491** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
10492** this case foreign keys are parsed, but no other functionality is
10493** provided (enforcement of FK constraints requires the triggers sub-system).
10494*/
10495#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
10496SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
10497SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
10498SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
10499SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
10500SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
10501SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
10502#else
10503  #define sqlite3FkActions(a,b,c,d)
10504  #define sqlite3FkCheck(a,b,c,d)
10505  #define sqlite3FkDropTable(a,b,c)
10506  #define sqlite3FkOldmask(a,b)      0
10507  #define sqlite3FkRequired(a,b,c,d) 0
10508#endif
10509#ifndef SQLITE_OMIT_FOREIGN_KEY
10510SQLITE_PRIVATE   void sqlite3FkDelete(Table*);
10511#else
10512  #define sqlite3FkDelete(a)
10513#endif
10514
10515
10516/*
10517** Available fault injectors.  Should be numbered beginning with 0.
10518*/
10519#define SQLITE_FAULTINJECTOR_MALLOC     0
10520#define SQLITE_FAULTINJECTOR_COUNT      1
10521
10522/*
10523** The interface to the code in fault.c used for identifying "benign"
10524** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10525** is not defined.
10526*/
10527#ifndef SQLITE_OMIT_BUILTIN_TEST
10528SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10529SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10530#else
10531  #define sqlite3BeginBenignMalloc()
10532  #define sqlite3EndBenignMalloc()
10533#endif
10534
10535#define IN_INDEX_ROWID           1
10536#define IN_INDEX_EPH             2
10537#define IN_INDEX_INDEX           3
10538SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
10539
10540#ifdef SQLITE_ENABLE_ATOMIC_WRITE
10541SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
10542SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
10543SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
10544#else
10545  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
10546#endif
10547
10548SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
10549SQLITE_PRIVATE int sqlite3MemJournalSize(void);
10550SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
10551
10552#if SQLITE_MAX_EXPR_DEPTH>0
10553SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
10554SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
10555SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
10556#else
10557  #define sqlite3ExprSetHeight(x,y)
10558  #define sqlite3SelectExprHeight(x) 0
10559  #define sqlite3ExprCheckHeight(x,y)
10560#endif
10561
10562SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
10563SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
10564
10565#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10566SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
10567SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
10568SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
10569#else
10570  #define sqlite3ConnectionBlocked(x,y)
10571  #define sqlite3ConnectionUnlocked(x)
10572  #define sqlite3ConnectionClosed(x)
10573#endif
10574
10575#ifdef SQLITE_DEBUG
10576SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
10577#endif
10578
10579/*
10580** If the SQLITE_ENABLE IOTRACE exists then the global variable
10581** sqlite3IoTrace is a pointer to a printf-like routine used to
10582** print I/O tracing messages.
10583*/
10584#ifdef SQLITE_ENABLE_IOTRACE
10585# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
10586SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
10587SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
10588#else
10589# define IOTRACE(A)
10590# define sqlite3VdbeIOTraceSql(X)
10591#endif
10592
10593#endif
10594
10595/************** End of sqliteInt.h *******************************************/
10596/************** Begin file global.c ******************************************/
10597/*
10598** 2008 June 13
10599**
10600** The author disclaims copyright to this source code.  In place of
10601** a legal notice, here is a blessing:
10602**
10603**    May you do good and not evil.
10604**    May you find forgiveness for yourself and forgive others.
10605**    May you share freely, never taking more than you give.
10606**
10607*************************************************************************
10608**
10609** This file contains definitions of global variables and contants.
10610*/
10611
10612/* An array to map all upper-case characters into their corresponding
10613** lower-case character.
10614**
10615** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
10616** handle case conversions for the UTF character set since the tables
10617** involved are nearly as big or bigger than SQLite itself.
10618*/
10619SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
10620#ifdef SQLITE_ASCII
10621      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
10622     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
10623     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
10624     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
10625    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
10626    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
10627    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
10628    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
10629    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
10630    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
10631    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
10632    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
10633    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
10634    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
10635    252,253,254,255
10636#endif
10637#ifdef SQLITE_EBCDIC
10638      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
10639     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
10640     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
10641     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
10642     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
10643     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
10644     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
10645    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
10646    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
10647    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
10648    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
10649    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
10650    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
10651    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
10652    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
10653    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
10654#endif
10655};
10656
10657/*
10658** The following 256 byte lookup table is used to support SQLites built-in
10659** equivalents to the following standard library functions:
10660**
10661**   isspace()                        0x01
10662**   isalpha()                        0x02
10663**   isdigit()                        0x04
10664**   isalnum()                        0x06
10665**   isxdigit()                       0x08
10666**   toupper()                        0x20
10667**   SQLite identifier character      0x40
10668**
10669** Bit 0x20 is set if the mapped character requires translation to upper
10670** case. i.e. if the character is a lower-case ASCII character.
10671** If x is a lower-case ASCII character, then its upper-case equivalent
10672** is (x - 0x20). Therefore toupper() can be implemented as:
10673**
10674**   (x & ~(map[x]&0x20))
10675**
10676** Standard function tolower() is implemented using the sqlite3UpperToLower[]
10677** array. tolower() is used more often than toupper() by SQLite.
10678**
10679** Bit 0x40 is set if the character non-alphanumeric and can be used in an
10680** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
10681** non-ASCII UTF character. Hence the test for whether or not a character is
10682** part of an identifier is 0x46.
10683**
10684** SQLite's versions are identical to the standard versions assuming a
10685** locale of "C". They are implemented as macros in sqliteInt.h.
10686*/
10687#ifdef SQLITE_ASCII
10688SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
10689  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
10690  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
10691  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
10692  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
10693  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
10694  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
10695  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
10696  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
10697
10698  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
10699  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
10700  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
10701  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
10702  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
10703  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
10704  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
10705  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
10706
10707  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
10708  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
10709  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
10710  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
10711  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
10712  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
10713  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
10714  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
10715
10716  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
10717  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
10718  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
10719  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
10720  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
10721  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
10722  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
10723  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
10724};
10725#endif
10726
10727
10728
10729/*
10730** The following singleton contains the global configuration for
10731** the SQLite library.
10732*/
10733SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
10734   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
10735   1,                         /* bCoreMutex */
10736   SQLITE_THREADSAFE==1,      /* bFullMutex */
10737   0x7ffffffe,                /* mxStrlen */
10738   100,                       /* szLookaside */
10739   500,                       /* nLookaside */
10740   {0,0,0,0,0,0,0,0},         /* m */
10741   {0,0,0,0,0,0,0,0,0},       /* mutex */
10742   {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
10743   (void*)0,                  /* pHeap */
10744   0,                         /* nHeap */
10745   0, 0,                      /* mnHeap, mxHeap */
10746   (void*)0,                  /* pScratch */
10747   0,                         /* szScratch */
10748   0,                         /* nScratch */
10749   (void*)0,                  /* pPage */
10750   0,                         /* szPage */
10751   0,                         /* nPage */
10752   0,                         /* mxParserStack */
10753   0,                         /* sharedCacheEnabled */
10754   /* All the rest should always be initialized to zero */
10755   0,                         /* isInit */
10756   0,                         /* inProgress */
10757   0,                         /* isMutexInit */
10758   0,                         /* isMallocInit */
10759   0,                         /* isPCacheInit */
10760   0,                         /* pInitMutex */
10761   0,                         /* nRefInitMutex */
10762};
10763
10764
10765/*
10766** Hash table for global functions - functions common to all
10767** database connections.  After initialization, this table is
10768** read-only.
10769*/
10770SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10771
10772/*
10773** The value of the "pending" byte must be 0x40000000 (1 byte past the
10774** 1-gibabyte boundary) in a compatible database.  SQLite never uses
10775** the database page that contains the pending byte.  It never attempts
10776** to read or write that page.  The pending byte page is set assign
10777** for use by the VFS layers as space for managing file locks.
10778**
10779** During testing, it is often desirable to move the pending byte to
10780** a different position in the file.  This allows code that has to
10781** deal with the pending byte to run on files that are much smaller
10782** than 1 GiB.  The sqlite3_test_control() interface can be used to
10783** move the pending byte.
10784**
10785** IMPORTANT:  Changing the pending byte to any value other than
10786** 0x40000000 results in an incompatible database file format!
10787** Changing the pending byte during operating results in undefined
10788** and dileterious behavior.
10789*/
10790SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
10791
10792/*
10793** Properties of opcodes.  The OPFLG_INITIALIZER macro is
10794** created by mkopcodeh.awk during compilation.  Data is obtained
10795** from the comments following the "case OP_xxxx:" statements in
10796** the vdbe.c file.
10797*/
10798SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
10799
10800/************** End of global.c **********************************************/
10801/************** Begin file status.c ******************************************/
10802/*
10803** 2008 June 18
10804**
10805** The author disclaims copyright to this source code.  In place of
10806** a legal notice, here is a blessing:
10807**
10808**    May you do good and not evil.
10809**    May you find forgiveness for yourself and forgive others.
10810**    May you share freely, never taking more than you give.
10811**
10812*************************************************************************
10813**
10814** This module implements the sqlite3_status() interface and related
10815** functionality.
10816*/
10817
10818/*
10819** Variables in which to record status information.
10820*/
10821typedef struct sqlite3StatType sqlite3StatType;
10822static SQLITE_WSD struct sqlite3StatType {
10823  int nowValue[9];         /* Current value */
10824  int mxValue[9];          /* Maximum value */
10825} sqlite3Stat = { {0,}, {0,} };
10826
10827
10828/* The "wsdStat" macro will resolve to the status information
10829** state vector.  If writable static data is unsupported on the target,
10830** we have to locate the state vector at run-time.  In the more common
10831** case where writable static data is supported, wsdStat can refer directly
10832** to the "sqlite3Stat" state vector declared above.
10833*/
10834#ifdef SQLITE_OMIT_WSD
10835# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
10836# define wsdStat x[0]
10837#else
10838# define wsdStatInit
10839# define wsdStat sqlite3Stat
10840#endif
10841
10842/*
10843** Return the current value of a status parameter.
10844*/
10845SQLITE_PRIVATE int sqlite3StatusValue(int op){
10846  wsdStatInit;
10847  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10848  return wsdStat.nowValue[op];
10849}
10850
10851/*
10852** Add N to the value of a status record.  It is assumed that the
10853** caller holds appropriate locks.
10854*/
10855SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
10856  wsdStatInit;
10857  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10858  wsdStat.nowValue[op] += N;
10859  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
10860    wsdStat.mxValue[op] = wsdStat.nowValue[op];
10861  }
10862}
10863
10864/*
10865** Set the value of a status to X.
10866*/
10867SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
10868  wsdStatInit;
10869  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
10870  wsdStat.nowValue[op] = X;
10871  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
10872    wsdStat.mxValue[op] = wsdStat.nowValue[op];
10873  }
10874}
10875
10876/*
10877** Query status information.
10878**
10879** This implementation assumes that reading or writing an aligned
10880** 32-bit integer is an atomic operation.  If that assumption is not true,
10881** then this routine is not threadsafe.
10882*/
10883SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
10884  wsdStatInit;
10885  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
10886    return SQLITE_MISUSE;
10887  }
10888  *pCurrent = wsdStat.nowValue[op];
10889  *pHighwater = wsdStat.mxValue[op];
10890  if( resetFlag ){
10891    wsdStat.mxValue[op] = wsdStat.nowValue[op];
10892  }
10893  return SQLITE_OK;
10894}
10895
10896/*
10897** Query status information for a single database connection
10898*/
10899SQLITE_API int sqlite3_db_status(
10900  sqlite3 *db,          /* The database connection whose status is desired */
10901  int op,               /* Status verb */
10902  int *pCurrent,        /* Write current value here */
10903  int *pHighwater,      /* Write high-water mark here */
10904  int resetFlag         /* Reset high-water mark if true */
10905){
10906  switch( op ){
10907    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
10908      *pCurrent = db->lookaside.nOut;
10909      *pHighwater = db->lookaside.mxOut;
10910      if( resetFlag ){
10911        db->lookaside.mxOut = db->lookaside.nOut;
10912      }
10913      break;
10914    }
10915    default: {
10916      return SQLITE_ERROR;
10917    }
10918  }
10919  return SQLITE_OK;
10920}
10921
10922/************** End of status.c **********************************************/
10923/************** Begin file date.c ********************************************/
10924/*
10925** 2003 October 31
10926**
10927** The author disclaims copyright to this source code.  In place of
10928** a legal notice, here is a blessing:
10929**
10930**    May you do good and not evil.
10931**    May you find forgiveness for yourself and forgive others.
10932**    May you share freely, never taking more than you give.
10933**
10934*************************************************************************
10935** This file contains the C functions that implement date and time
10936** functions for SQLite.
10937**
10938** There is only one exported symbol in this file - the function
10939** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
10940** All other code has file scope.
10941**
10942** SQLite processes all times and dates as Julian Day numbers.  The
10943** dates and times are stored as the number of days since noon
10944** in Greenwich on November 24, 4714 B.C. according to the Gregorian
10945** calendar system.
10946**
10947** 1970-01-01 00:00:00 is JD 2440587.5
10948** 2000-01-01 00:00:00 is JD 2451544.5
10949**
10950** This implemention requires years to be expressed as a 4-digit number
10951** which means that only dates between 0000-01-01 and 9999-12-31 can
10952** be represented, even though julian day numbers allow a much wider
10953** range of dates.
10954**
10955** The Gregorian calendar system is used for all dates and times,
10956** even those that predate the Gregorian calendar.  Historians usually
10957** use the Julian calendar for dates prior to 1582-10-15 and for some
10958** dates afterwards, depending on locale.  Beware of this difference.
10959**
10960** The conversion algorithms are implemented based on descriptions
10961** in the following text:
10962**
10963**      Jean Meeus
10964**      Astronomical Algorithms, 2nd Edition, 1998
10965**      ISBM 0-943396-61-1
10966**      Willmann-Bell, Inc
10967**      Richmond, Virginia (USA)
10968*/
10969#include <time.h>
10970
10971#ifndef SQLITE_OMIT_DATETIME_FUNCS
10972
10973/*
10974** On recent Windows platforms, the localtime_s() function is available
10975** as part of the "Secure CRT". It is essentially equivalent to
10976** localtime_r() available under most POSIX platforms, except that the
10977** order of the parameters is reversed.
10978**
10979** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
10980**
10981** If the user has not indicated to use localtime_r() or localtime_s()
10982** already, check for an MSVC build environment that provides
10983** localtime_s().
10984*/
10985#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
10986     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
10987#define HAVE_LOCALTIME_S 1
10988#endif
10989
10990/*
10991** A structure for holding a single date and time.
10992*/
10993typedef struct DateTime DateTime;
10994struct DateTime {
10995  sqlite3_int64 iJD; /* The julian day number times 86400000 */
10996  int Y, M, D;       /* Year, month, and day */
10997  int h, m;          /* Hour and minutes */
10998  int tz;            /* Timezone offset in minutes */
10999  double s;          /* Seconds */
11000  char validYMD;     /* True (1) if Y,M,D are valid */
11001  char validHMS;     /* True (1) if h,m,s are valid */
11002  char validJD;      /* True (1) if iJD is valid */
11003  char validTZ;      /* True (1) if tz is valid */
11004};
11005
11006
11007/*
11008** Convert zDate into one or more integers.  Additional arguments
11009** come in groups of 5 as follows:
11010**
11011**       N       number of digits in the integer
11012**       min     minimum allowed value of the integer
11013**       max     maximum allowed value of the integer
11014**       nextC   first character after the integer
11015**       pVal    where to write the integers value.
11016**
11017** Conversions continue until one with nextC==0 is encountered.
11018** The function returns the number of successful conversions.
11019*/
11020static int getDigits(const char *zDate, ...){
11021  va_list ap;
11022  int val;
11023  int N;
11024  int min;
11025  int max;
11026  int nextC;
11027  int *pVal;
11028  int cnt = 0;
11029  va_start(ap, zDate);
11030  do{
11031    N = va_arg(ap, int);
11032    min = va_arg(ap, int);
11033    max = va_arg(ap, int);
11034    nextC = va_arg(ap, int);
11035    pVal = va_arg(ap, int*);
11036    val = 0;
11037    while( N-- ){
11038      if( !sqlite3Isdigit(*zDate) ){
11039        goto end_getDigits;
11040      }
11041      val = val*10 + *zDate - '0';
11042      zDate++;
11043    }
11044    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11045      goto end_getDigits;
11046    }
11047    *pVal = val;
11048    zDate++;
11049    cnt++;
11050  }while( nextC );
11051end_getDigits:
11052  va_end(ap);
11053  return cnt;
11054}
11055
11056/*
11057** Read text from z[] and convert into a floating point number.  Return
11058** the number of digits converted.
11059*/
11060#define getValue sqlite3AtoF
11061
11062/*
11063** Parse a timezone extension on the end of a date-time.
11064** The extension is of the form:
11065**
11066**        (+/-)HH:MM
11067**
11068** Or the "zulu" notation:
11069**
11070**        Z
11071**
11072** If the parse is successful, write the number of minutes
11073** of change in p->tz and return 0.  If a parser error occurs,
11074** return non-zero.
11075**
11076** A missing specifier is not considered an error.
11077*/
11078static int parseTimezone(const char *zDate, DateTime *p){
11079  int sgn = 0;
11080  int nHr, nMn;
11081  int c;
11082  while( sqlite3Isspace(*zDate) ){ zDate++; }
11083  p->tz = 0;
11084  c = *zDate;
11085  if( c=='-' ){
11086    sgn = -1;
11087  }else if( c=='+' ){
11088    sgn = +1;
11089  }else if( c=='Z' || c=='z' ){
11090    zDate++;
11091    goto zulu_time;
11092  }else{
11093    return c!=0;
11094  }
11095  zDate++;
11096  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11097    return 1;
11098  }
11099  zDate += 5;
11100  p->tz = sgn*(nMn + nHr*60);
11101zulu_time:
11102  while( sqlite3Isspace(*zDate) ){ zDate++; }
11103  return *zDate!=0;
11104}
11105
11106/*
11107** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11108** The HH, MM, and SS must each be exactly 2 digits.  The
11109** fractional seconds FFFF can be one or more digits.
11110**
11111** Return 1 if there is a parsing error and 0 on success.
11112*/
11113static int parseHhMmSs(const char *zDate, DateTime *p){
11114  int h, m, s;
11115  double ms = 0.0;
11116  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11117    return 1;
11118  }
11119  zDate += 5;
11120  if( *zDate==':' ){
11121    zDate++;
11122    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11123      return 1;
11124    }
11125    zDate += 2;
11126    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
11127      double rScale = 1.0;
11128      zDate++;
11129      while( sqlite3Isdigit(*zDate) ){
11130        ms = ms*10.0 + *zDate - '0';
11131        rScale *= 10.0;
11132        zDate++;
11133      }
11134      ms /= rScale;
11135    }
11136  }else{
11137    s = 0;
11138  }
11139  p->validJD = 0;
11140  p->validHMS = 1;
11141  p->h = h;
11142  p->m = m;
11143  p->s = s + ms;
11144  if( parseTimezone(zDate, p) ) return 1;
11145  p->validTZ = (p->tz!=0)?1:0;
11146  return 0;
11147}
11148
11149/*
11150** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11151** that the YYYY-MM-DD is according to the Gregorian calendar.
11152**
11153** Reference:  Meeus page 61
11154*/
11155static void computeJD(DateTime *p){
11156  int Y, M, D, A, B, X1, X2;
11157
11158  if( p->validJD ) return;
11159  if( p->validYMD ){
11160    Y = p->Y;
11161    M = p->M;
11162    D = p->D;
11163  }else{
11164    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11165    M = 1;
11166    D = 1;
11167  }
11168  if( M<=2 ){
11169    Y--;
11170    M += 12;
11171  }
11172  A = Y/100;
11173  B = 2 - A + (A/4);
11174  X1 = 36525*(Y+4716)/100;
11175  X2 = 306001*(M+1)/10000;
11176  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
11177  p->validJD = 1;
11178  if( p->validHMS ){
11179    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
11180    if( p->validTZ ){
11181      p->iJD -= p->tz*60000;
11182      p->validYMD = 0;
11183      p->validHMS = 0;
11184      p->validTZ = 0;
11185    }
11186  }
11187}
11188
11189/*
11190** Parse dates of the form
11191**
11192**     YYYY-MM-DD HH:MM:SS.FFF
11193**     YYYY-MM-DD HH:MM:SS
11194**     YYYY-MM-DD HH:MM
11195**     YYYY-MM-DD
11196**
11197** Write the result into the DateTime structure and return 0
11198** on success and 1 if the input string is not a well-formed
11199** date.
11200*/
11201static int parseYyyyMmDd(const char *zDate, DateTime *p){
11202  int Y, M, D, neg;
11203
11204  if( zDate[0]=='-' ){
11205    zDate++;
11206    neg = 1;
11207  }else{
11208    neg = 0;
11209  }
11210  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
11211    return 1;
11212  }
11213  zDate += 10;
11214  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
11215  if( parseHhMmSs(zDate, p)==0 ){
11216    /* We got the time */
11217  }else if( *zDate==0 ){
11218    p->validHMS = 0;
11219  }else{
11220    return 1;
11221  }
11222  p->validJD = 0;
11223  p->validYMD = 1;
11224  p->Y = neg ? -Y : Y;
11225  p->M = M;
11226  p->D = D;
11227  if( p->validTZ ){
11228    computeJD(p);
11229  }
11230  return 0;
11231}
11232
11233/*
11234** Set the time to the current time reported by the VFS
11235*/
11236static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
11237  double r;
11238  sqlite3 *db = sqlite3_context_db_handle(context);
11239  sqlite3OsCurrentTime(db->pVfs, &r);
11240  p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11241  p->validJD = 1;
11242}
11243
11244/*
11245** Attempt to parse the given string into a Julian Day Number.  Return
11246** the number of errors.
11247**
11248** The following are acceptable forms for the input string:
11249**
11250**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
11251**      DDDD.DD
11252**      now
11253**
11254** In the first form, the +/-HH:MM is always optional.  The fractional
11255** seconds extension (the ".FFF") is optional.  The seconds portion
11256** (":SS.FFF") is option.  The year and date can be omitted as long
11257** as there is a time string.  The time string can be omitted as long
11258** as there is a year and date.
11259*/
11260static int parseDateOrTime(
11261  sqlite3_context *context,
11262  const char *zDate,
11263  DateTime *p
11264){
11265  int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
11266  if( parseYyyyMmDd(zDate,p)==0 ){
11267    return 0;
11268  }else if( parseHhMmSs(zDate, p)==0 ){
11269    return 0;
11270  }else if( sqlite3StrICmp(zDate,"now")==0){
11271    setDateTimeToCurrent(context, p);
11272    return 0;
11273  }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
11274    double r;
11275    getValue(zDate, &r);
11276    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11277    p->validJD = 1;
11278    return 0;
11279  }
11280  return 1;
11281}
11282
11283/*
11284** Compute the Year, Month, and Day from the julian day number.
11285*/
11286static void computeYMD(DateTime *p){
11287  int Z, A, B, C, D, E, X1;
11288  if( p->validYMD ) return;
11289  if( !p->validJD ){
11290    p->Y = 2000;
11291    p->M = 1;
11292    p->D = 1;
11293  }else{
11294    Z = (int)((p->iJD + 43200000)/86400000);
11295    A = (int)((Z - 1867216.25)/36524.25);
11296    A = Z + 1 + A - (A/4);
11297    B = A + 1524;
11298    C = (int)((B - 122.1)/365.25);
11299    D = (36525*C)/100;
11300    E = (int)((B-D)/30.6001);
11301    X1 = (int)(30.6001*E);
11302    p->D = B - D - X1;
11303    p->M = E<14 ? E-1 : E-13;
11304    p->Y = p->M>2 ? C - 4716 : C - 4715;
11305  }
11306  p->validYMD = 1;
11307}
11308
11309/*
11310** Compute the Hour, Minute, and Seconds from the julian day number.
11311*/
11312static void computeHMS(DateTime *p){
11313  int s;
11314  if( p->validHMS ) return;
11315  computeJD(p);
11316  s = (int)((p->iJD + 43200000) % 86400000);
11317  p->s = s/1000.0;
11318  s = (int)p->s;
11319  p->s -= s;
11320  p->h = s/3600;
11321  s -= p->h*3600;
11322  p->m = s/60;
11323  p->s += s - p->m*60;
11324  p->validHMS = 1;
11325}
11326
11327/*
11328** Compute both YMD and HMS
11329*/
11330static void computeYMD_HMS(DateTime *p){
11331  computeYMD(p);
11332  computeHMS(p);
11333}
11334
11335/*
11336** Clear the YMD and HMS and the TZ
11337*/
11338static void clearYMD_HMS_TZ(DateTime *p){
11339  p->validYMD = 0;
11340  p->validHMS = 0;
11341  p->validTZ = 0;
11342}
11343
11344#ifndef SQLITE_OMIT_LOCALTIME
11345/*
11346** Compute the difference (in milliseconds)
11347** between localtime and UTC (a.k.a. GMT)
11348** for the time value p where p is in UTC.
11349*/
11350static sqlite3_int64 localtimeOffset(DateTime *p){
11351  DateTime x, y;
11352  time_t t;
11353  x = *p;
11354  computeYMD_HMS(&x);
11355  if( x.Y<1971 || x.Y>=2038 ){
11356    x.Y = 2000;
11357    x.M = 1;
11358    x.D = 1;
11359    x.h = 0;
11360    x.m = 0;
11361    x.s = 0.0;
11362  } else {
11363    int s = (int)(x.s + 0.5);
11364    x.s = s;
11365  }
11366  x.tz = 0;
11367  x.validJD = 0;
11368  computeJD(&x);
11369  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
11370#ifdef HAVE_LOCALTIME_R
11371  {
11372    struct tm sLocal;
11373    localtime_r(&t, &sLocal);
11374    y.Y = sLocal.tm_year + 1900;
11375    y.M = sLocal.tm_mon + 1;
11376    y.D = sLocal.tm_mday;
11377    y.h = sLocal.tm_hour;
11378    y.m = sLocal.tm_min;
11379    y.s = sLocal.tm_sec;
11380  }
11381#elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
11382  {
11383    struct tm sLocal;
11384    localtime_s(&sLocal, &t);
11385    y.Y = sLocal.tm_year + 1900;
11386    y.M = sLocal.tm_mon + 1;
11387    y.D = sLocal.tm_mday;
11388    y.h = sLocal.tm_hour;
11389    y.m = sLocal.tm_min;
11390    y.s = sLocal.tm_sec;
11391  }
11392#else
11393  {
11394    struct tm *pTm;
11395    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11396    pTm = localtime(&t);
11397    y.Y = pTm->tm_year + 1900;
11398    y.M = pTm->tm_mon + 1;
11399    y.D = pTm->tm_mday;
11400    y.h = pTm->tm_hour;
11401    y.m = pTm->tm_min;
11402    y.s = pTm->tm_sec;
11403    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11404  }
11405#endif
11406  y.validYMD = 1;
11407  y.validHMS = 1;
11408  y.validJD = 0;
11409  y.validTZ = 0;
11410  computeJD(&y);
11411  return y.iJD - x.iJD;
11412}
11413#endif /* SQLITE_OMIT_LOCALTIME */
11414
11415/*
11416** Process a modifier to a date-time stamp.  The modifiers are
11417** as follows:
11418**
11419**     NNN days
11420**     NNN hours
11421**     NNN minutes
11422**     NNN.NNNN seconds
11423**     NNN months
11424**     NNN years
11425**     start of month
11426**     start of year
11427**     start of week
11428**     start of day
11429**     weekday N
11430**     unixepoch
11431**     localtime
11432**     utc
11433**
11434** Return 0 on success and 1 if there is any kind of error.
11435*/
11436static int parseModifier(const char *zMod, DateTime *p){
11437  int rc = 1;
11438  int n;
11439  double r;
11440  char *z, zBuf[30];
11441  z = zBuf;
11442  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
11443    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
11444  }
11445  z[n] = 0;
11446  switch( z[0] ){
11447#ifndef SQLITE_OMIT_LOCALTIME
11448    case 'l': {
11449      /*    localtime
11450      **
11451      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
11452      ** show local time.
11453      */
11454      if( strcmp(z, "localtime")==0 ){
11455        computeJD(p);
11456        p->iJD += localtimeOffset(p);
11457        clearYMD_HMS_TZ(p);
11458        rc = 0;
11459      }
11460      break;
11461    }
11462#endif
11463    case 'u': {
11464      /*
11465      **    unixepoch
11466      **
11467      ** Treat the current value of p->iJD as the number of
11468      ** seconds since 1970.  Convert to a real julian day number.
11469      */
11470      if( strcmp(z, "unixepoch")==0 && p->validJD ){
11471        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
11472        clearYMD_HMS_TZ(p);
11473        rc = 0;
11474      }
11475#ifndef SQLITE_OMIT_LOCALTIME
11476      else if( strcmp(z, "utc")==0 ){
11477        sqlite3_int64 c1;
11478        computeJD(p);
11479        c1 = localtimeOffset(p);
11480        p->iJD -= c1;
11481        clearYMD_HMS_TZ(p);
11482        p->iJD += c1 - localtimeOffset(p);
11483        rc = 0;
11484      }
11485#endif
11486      break;
11487    }
11488    case 'w': {
11489      /*
11490      **    weekday N
11491      **
11492      ** Move the date to the same time on the next occurrence of
11493      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
11494      ** date is already on the appropriate weekday, this is a no-op.
11495      */
11496      if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
11497                 && (n=(int)r)==r && n>=0 && r<7 ){
11498        sqlite3_int64 Z;
11499        computeYMD_HMS(p);
11500        p->validTZ = 0;
11501        p->validJD = 0;
11502        computeJD(p);
11503        Z = ((p->iJD + 129600000)/86400000) % 7;
11504        if( Z>n ) Z -= 7;
11505        p->iJD += (n - Z)*86400000;
11506        clearYMD_HMS_TZ(p);
11507        rc = 0;
11508      }
11509      break;
11510    }
11511    case 's': {
11512      /*
11513      **    start of TTTTT
11514      **
11515      ** Move the date backwards to the beginning of the current day,
11516      ** or month or year.
11517      */
11518      if( strncmp(z, "start of ", 9)!=0 ) break;
11519      z += 9;
11520      computeYMD(p);
11521      p->validHMS = 1;
11522      p->h = p->m = 0;
11523      p->s = 0.0;
11524      p->validTZ = 0;
11525      p->validJD = 0;
11526      if( strcmp(z,"month")==0 ){
11527        p->D = 1;
11528        rc = 0;
11529      }else if( strcmp(z,"year")==0 ){
11530        computeYMD(p);
11531        p->M = 1;
11532        p->D = 1;
11533        rc = 0;
11534      }else if( strcmp(z,"day")==0 ){
11535        rc = 0;
11536      }
11537      break;
11538    }
11539    case '+':
11540    case '-':
11541    case '0':
11542    case '1':
11543    case '2':
11544    case '3':
11545    case '4':
11546    case '5':
11547    case '6':
11548    case '7':
11549    case '8':
11550    case '9': {
11551      double rRounder;
11552      n = getValue(z, &r);
11553      assert( n>=1 );
11554      if( z[n]==':' ){
11555        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
11556        ** specified number of hours, minutes, seconds, and fractional seconds
11557        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
11558        ** omitted.
11559        */
11560        const char *z2 = z;
11561        DateTime tx;
11562        sqlite3_int64 day;
11563        if( !sqlite3Isdigit(*z2) ) z2++;
11564        memset(&tx, 0, sizeof(tx));
11565        if( parseHhMmSs(z2, &tx) ) break;
11566        computeJD(&tx);
11567        tx.iJD -= 43200000;
11568        day = tx.iJD/86400000;
11569        tx.iJD -= day*86400000;
11570        if( z[0]=='-' ) tx.iJD = -tx.iJD;
11571        computeJD(p);
11572        clearYMD_HMS_TZ(p);
11573        p->iJD += tx.iJD;
11574        rc = 0;
11575        break;
11576      }
11577      z += n;
11578      while( sqlite3Isspace(*z) ) z++;
11579      n = sqlite3Strlen30(z);
11580      if( n>10 || n<3 ) break;
11581      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
11582      computeJD(p);
11583      rc = 0;
11584      rRounder = r<0 ? -0.5 : +0.5;
11585      if( n==3 && strcmp(z,"day")==0 ){
11586        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
11587      }else if( n==4 && strcmp(z,"hour")==0 ){
11588        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
11589      }else if( n==6 && strcmp(z,"minute")==0 ){
11590        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
11591      }else if( n==6 && strcmp(z,"second")==0 ){
11592        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
11593      }else if( n==5 && strcmp(z,"month")==0 ){
11594        int x, y;
11595        computeYMD_HMS(p);
11596        p->M += (int)r;
11597        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
11598        p->Y += x;
11599        p->M -= x*12;
11600        p->validJD = 0;
11601        computeJD(p);
11602        y = (int)r;
11603        if( y!=r ){
11604          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
11605        }
11606      }else if( n==4 && strcmp(z,"year")==0 ){
11607        int y = (int)r;
11608        computeYMD_HMS(p);
11609        p->Y += y;
11610        p->validJD = 0;
11611        computeJD(p);
11612        if( y!=r ){
11613          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
11614        }
11615      }else{
11616        rc = 1;
11617      }
11618      clearYMD_HMS_TZ(p);
11619      break;
11620    }
11621    default: {
11622      break;
11623    }
11624  }
11625  return rc;
11626}
11627
11628/*
11629** Process time function arguments.  argv[0] is a date-time stamp.
11630** argv[1] and following are modifiers.  Parse them all and write
11631** the resulting time into the DateTime structure p.  Return 0
11632** on success and 1 if there are any errors.
11633**
11634** If there are zero parameters (if even argv[0] is undefined)
11635** then assume a default value of "now" for argv[0].
11636*/
11637static int isDate(
11638  sqlite3_context *context,
11639  int argc,
11640  sqlite3_value **argv,
11641  DateTime *p
11642){
11643  int i;
11644  const unsigned char *z;
11645  int eType;
11646  memset(p, 0, sizeof(*p));
11647  if( argc==0 ){
11648    setDateTimeToCurrent(context, p);
11649  }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
11650                   || eType==SQLITE_INTEGER ){
11651    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
11652    p->validJD = 1;
11653  }else{
11654    z = sqlite3_value_text(argv[0]);
11655    if( !z || parseDateOrTime(context, (char*)z, p) ){
11656      return 1;
11657    }
11658  }
11659  for(i=1; i<argc; i++){
11660    if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
11661      return 1;
11662    }
11663  }
11664  return 0;
11665}
11666
11667
11668/*
11669** The following routines implement the various date and time functions
11670** of SQLite.
11671*/
11672
11673/*
11674**    julianday( TIMESTRING, MOD, MOD, ...)
11675**
11676** Return the julian day number of the date specified in the arguments
11677*/
11678static void juliandayFunc(
11679  sqlite3_context *context,
11680  int argc,
11681  sqlite3_value **argv
11682){
11683  DateTime x;
11684  if( isDate(context, argc, argv, &x)==0 ){
11685    computeJD(&x);
11686    sqlite3_result_double(context, x.iJD/86400000.0);
11687  }
11688}
11689
11690/*
11691**    datetime( TIMESTRING, MOD, MOD, ...)
11692**
11693** Return YYYY-MM-DD HH:MM:SS
11694*/
11695static void datetimeFunc(
11696  sqlite3_context *context,
11697  int argc,
11698  sqlite3_value **argv
11699){
11700  DateTime x;
11701  if( isDate(context, argc, argv, &x)==0 ){
11702    char zBuf[100];
11703    computeYMD_HMS(&x);
11704    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
11705                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
11706    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11707  }
11708}
11709
11710/*
11711**    time( TIMESTRING, MOD, MOD, ...)
11712**
11713** Return HH:MM:SS
11714*/
11715static void timeFunc(
11716  sqlite3_context *context,
11717  int argc,
11718  sqlite3_value **argv
11719){
11720  DateTime x;
11721  if( isDate(context, argc, argv, &x)==0 ){
11722    char zBuf[100];
11723    computeHMS(&x);
11724    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
11725    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11726  }
11727}
11728
11729/*
11730**    date( TIMESTRING, MOD, MOD, ...)
11731**
11732** Return YYYY-MM-DD
11733*/
11734static void dateFunc(
11735  sqlite3_context *context,
11736  int argc,
11737  sqlite3_value **argv
11738){
11739  DateTime x;
11740  if( isDate(context, argc, argv, &x)==0 ){
11741    char zBuf[100];
11742    computeYMD(&x);
11743    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
11744    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11745  }
11746}
11747
11748/*
11749**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
11750**
11751** Return a string described by FORMAT.  Conversions as follows:
11752**
11753**   %d  day of month
11754**   %f  ** fractional seconds  SS.SSS
11755**   %H  hour 00-24
11756**   %j  day of year 000-366
11757**   %J  ** Julian day number
11758**   %m  month 01-12
11759**   %M  minute 00-59
11760**   %s  seconds since 1970-01-01
11761**   %S  seconds 00-59
11762**   %w  day of week 0-6  sunday==0
11763**   %W  week of year 00-53
11764**   %Y  year 0000-9999
11765**   %%  %
11766*/
11767static void strftimeFunc(
11768  sqlite3_context *context,
11769  int argc,
11770  sqlite3_value **argv
11771){
11772  DateTime x;
11773  u64 n;
11774  size_t i,j;
11775  char *z;
11776  sqlite3 *db;
11777  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
11778  char zBuf[100];
11779  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
11780  db = sqlite3_context_db_handle(context);
11781  for(i=0, n=1; zFmt[i]; i++, n++){
11782    if( zFmt[i]=='%' ){
11783      switch( zFmt[i+1] ){
11784        case 'd':
11785        case 'H':
11786        case 'm':
11787        case 'M':
11788        case 'S':
11789        case 'W':
11790          n++;
11791          /* fall thru */
11792        case 'w':
11793        case '%':
11794          break;
11795        case 'f':
11796          n += 8;
11797          break;
11798        case 'j':
11799          n += 3;
11800          break;
11801        case 'Y':
11802          n += 8;
11803          break;
11804        case 's':
11805        case 'J':
11806          n += 50;
11807          break;
11808        default:
11809          return;  /* ERROR.  return a NULL */
11810      }
11811      i++;
11812    }
11813  }
11814  testcase( n==sizeof(zBuf)-1 );
11815  testcase( n==sizeof(zBuf) );
11816  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
11817  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
11818  if( n<sizeof(zBuf) ){
11819    z = zBuf;
11820  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
11821    sqlite3_result_error_toobig(context);
11822    return;
11823  }else{
11824    z = sqlite3DbMallocRaw(db, (int)n);
11825    if( z==0 ){
11826      sqlite3_result_error_nomem(context);
11827      return;
11828    }
11829  }
11830  computeJD(&x);
11831  computeYMD_HMS(&x);
11832  for(i=j=0; zFmt[i]; i++){
11833    if( zFmt[i]!='%' ){
11834      z[j++] = zFmt[i];
11835    }else{
11836      i++;
11837      switch( zFmt[i] ){
11838        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
11839        case 'f': {
11840          double s = x.s;
11841          if( s>59.999 ) s = 59.999;
11842          sqlite3_snprintf(7, &z[j],"%06.3f", s);
11843          j += sqlite3Strlen30(&z[j]);
11844          break;
11845        }
11846        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
11847        case 'W': /* Fall thru */
11848        case 'j': {
11849          int nDay;             /* Number of days since 1st day of year */
11850          DateTime y = x;
11851          y.validJD = 0;
11852          y.M = 1;
11853          y.D = 1;
11854          computeJD(&y);
11855          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
11856          if( zFmt[i]=='W' ){
11857            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
11858            wd = (int)(((x.iJD+43200000)/86400000)%7);
11859            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
11860            j += 2;
11861          }else{
11862            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
11863            j += 3;
11864          }
11865          break;
11866        }
11867        case 'J': {
11868          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
11869          j+=sqlite3Strlen30(&z[j]);
11870          break;
11871        }
11872        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
11873        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
11874        case 's': {
11875          sqlite3_snprintf(30,&z[j],"%lld",
11876                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
11877          j += sqlite3Strlen30(&z[j]);
11878          break;
11879        }
11880        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
11881        case 'w': {
11882          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
11883          break;
11884        }
11885        case 'Y': {
11886          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
11887          break;
11888        }
11889        default:   z[j++] = '%'; break;
11890      }
11891    }
11892  }
11893  z[j] = 0;
11894  sqlite3_result_text(context, z, -1,
11895                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
11896}
11897
11898/*
11899** current_time()
11900**
11901** This function returns the same value as time('now').
11902*/
11903static void ctimeFunc(
11904  sqlite3_context *context,
11905  int NotUsed,
11906  sqlite3_value **NotUsed2
11907){
11908  UNUSED_PARAMETER2(NotUsed, NotUsed2);
11909  timeFunc(context, 0, 0);
11910}
11911
11912/*
11913** current_date()
11914**
11915** This function returns the same value as date('now').
11916*/
11917static void cdateFunc(
11918  sqlite3_context *context,
11919  int NotUsed,
11920  sqlite3_value **NotUsed2
11921){
11922  UNUSED_PARAMETER2(NotUsed, NotUsed2);
11923  dateFunc(context, 0, 0);
11924}
11925
11926/*
11927** current_timestamp()
11928**
11929** This function returns the same value as datetime('now').
11930*/
11931static void ctimestampFunc(
11932  sqlite3_context *context,
11933  int NotUsed,
11934  sqlite3_value **NotUsed2
11935){
11936  UNUSED_PARAMETER2(NotUsed, NotUsed2);
11937  datetimeFunc(context, 0, 0);
11938}
11939#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
11940
11941#ifdef SQLITE_OMIT_DATETIME_FUNCS
11942/*
11943** If the library is compiled to omit the full-scale date and time
11944** handling (to get a smaller binary), the following minimal version
11945** of the functions current_time(), current_date() and current_timestamp()
11946** are included instead. This is to support column declarations that
11947** include "DEFAULT CURRENT_TIME" etc.
11948**
11949** This function uses the C-library functions time(), gmtime()
11950** and strftime(). The format string to pass to strftime() is supplied
11951** as the user-data for the function.
11952*/
11953static void currentTimeFunc(
11954  sqlite3_context *context,
11955  int argc,
11956  sqlite3_value **argv
11957){
11958  time_t t;
11959  char *zFormat = (char *)sqlite3_user_data(context);
11960  sqlite3 *db;
11961  double rT;
11962  char zBuf[20];
11963
11964  UNUSED_PARAMETER(argc);
11965  UNUSED_PARAMETER(argv);
11966
11967  db = sqlite3_context_db_handle(context);
11968  sqlite3OsCurrentTime(db->pVfs, &rT);
11969#ifndef SQLITE_OMIT_FLOATING_POINT
11970  t = 86400.0*(rT - 2440587.5) + 0.5;
11971#else
11972  /* without floating point support, rT will have
11973  ** already lost fractional day precision.
11974  */
11975  t = 86400 * (rT - 2440587) - 43200;
11976#endif
11977#ifdef HAVE_GMTIME_R
11978  {
11979    struct tm sNow;
11980    gmtime_r(&t, &sNow);
11981    strftime(zBuf, 20, zFormat, &sNow);
11982  }
11983#else
11984  {
11985    struct tm *pTm;
11986    sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11987    pTm = gmtime(&t);
11988    strftime(zBuf, 20, zFormat, pTm);
11989    sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11990  }
11991#endif
11992
11993  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
11994}
11995#endif
11996
11997/*
11998** This function registered all of the above C functions as SQL
11999** functions.  This should be the only routine in this file with
12000** external linkage.
12001*/
12002SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
12003  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
12004#ifndef SQLITE_OMIT_DATETIME_FUNCS
12005    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
12006    FUNCTION(date,             -1, 0, 0, dateFunc      ),
12007    FUNCTION(time,             -1, 0, 0, timeFunc      ),
12008    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
12009    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
12010    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
12011    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
12012    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
12013#else
12014    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
12015    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d",          0, currentTimeFunc),
12016    STR_FUNCTION(current_date,      0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
12017#endif
12018  };
12019  int i;
12020  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
12021  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
12022
12023  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
12024    sqlite3FuncDefInsert(pHash, &aFunc[i]);
12025  }
12026}
12027
12028/************** End of date.c ************************************************/
12029/************** Begin file os.c **********************************************/
12030/*
12031** 2005 November 29
12032**
12033** The author disclaims copyright to this source code.  In place of
12034** a legal notice, here is a blessing:
12035**
12036**    May you do good and not evil.
12037**    May you find forgiveness for yourself and forgive others.
12038**    May you share freely, never taking more than you give.
12039**
12040******************************************************************************
12041**
12042** This file contains OS interface code that is common to all
12043** architectures.
12044*/
12045#define _SQLITE_OS_C_ 1
12046#undef _SQLITE_OS_C_
12047
12048/*
12049** The default SQLite sqlite3_vfs implementations do not allocate
12050** memory (actually, os_unix.c allocates a small amount of memory
12051** from within OsOpen()), but some third-party implementations may.
12052** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12053** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12054**
12055** The following functions are instrumented for malloc() failure
12056** testing:
12057**
12058**     sqlite3OsOpen()
12059**     sqlite3OsRead()
12060**     sqlite3OsWrite()
12061**     sqlite3OsSync()
12062**     sqlite3OsLock()
12063**
12064*/
12065#if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
12066  #define DO_OS_MALLOC_TEST(x) if (!x || !sqlite3IsMemJournal(x)) {     \
12067    void *pTstAlloc = sqlite3Malloc(10);                             \
12068    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
12069    sqlite3_free(pTstAlloc);                                         \
12070  }
12071#else
12072  #define DO_OS_MALLOC_TEST(x)
12073#endif
12074
12075/*
12076** The following routines are convenience wrappers around methods
12077** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12078** of this would be completely automatic if SQLite were coded using
12079** C++ instead of plain old C.
12080*/
12081SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12082  int rc = SQLITE_OK;
12083  if( pId->pMethods ){
12084    rc = pId->pMethods->xClose(pId);
12085    pId->pMethods = 0;
12086  }
12087  return rc;
12088}
12089SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12090  DO_OS_MALLOC_TEST(id);
12091  return id->pMethods->xRead(id, pBuf, amt, offset);
12092}
12093SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12094  DO_OS_MALLOC_TEST(id);
12095  return id->pMethods->xWrite(id, pBuf, amt, offset);
12096}
12097SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12098  return id->pMethods->xTruncate(id, size);
12099}
12100SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12101  DO_OS_MALLOC_TEST(id);
12102  return id->pMethods->xSync(id, flags);
12103}
12104SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12105  DO_OS_MALLOC_TEST(id);
12106  return id->pMethods->xFileSize(id, pSize);
12107}
12108SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12109  DO_OS_MALLOC_TEST(id);
12110  return id->pMethods->xLock(id, lockType);
12111}
12112SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12113  return id->pMethods->xUnlock(id, lockType);
12114}
12115SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12116  DO_OS_MALLOC_TEST(id);
12117  return id->pMethods->xCheckReservedLock(id, pResOut);
12118}
12119SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12120  return id->pMethods->xFileControl(id, op, pArg);
12121}
12122SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12123  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12124  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12125}
12126SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12127  return id->pMethods->xDeviceCharacteristics(id);
12128}
12129
12130/*
12131** The next group of routines are convenience wrappers around the
12132** VFS methods.
12133*/
12134SQLITE_PRIVATE int sqlite3OsOpen(
12135  sqlite3_vfs *pVfs,
12136  const char *zPath,
12137  sqlite3_file *pFile,
12138  int flags,
12139  int *pFlagsOut
12140){
12141  int rc;
12142  DO_OS_MALLOC_TEST(0);
12143  /* 0x7f1f is a mask of SQLITE_OPEN_ flags that are valid to be passed
12144  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
12145  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
12146  ** reaching the VFS. */
12147  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x7f1f, pFlagsOut);
12148  assert( rc==SQLITE_OK || pFile->pMethods==0 );
12149  return rc;
12150}
12151SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12152  return pVfs->xDelete(pVfs, zPath, dirSync);
12153}
12154SQLITE_PRIVATE int sqlite3OsAccess(
12155  sqlite3_vfs *pVfs,
12156  const char *zPath,
12157  int flags,
12158  int *pResOut
12159){
12160  DO_OS_MALLOC_TEST(0);
12161  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12162}
12163SQLITE_PRIVATE int sqlite3OsFullPathname(
12164  sqlite3_vfs *pVfs,
12165  const char *zPath,
12166  int nPathOut,
12167  char *zPathOut
12168){
12169  zPathOut[0] = 0;
12170  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12171}
12172#ifndef SQLITE_OMIT_LOAD_EXTENSION
12173SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12174  return pVfs->xDlOpen(pVfs, zPath);
12175}
12176SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12177  pVfs->xDlError(pVfs, nByte, zBufOut);
12178}
12179SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
12180  return pVfs->xDlSym(pVfs, pHdle, zSym);
12181}
12182SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
12183  pVfs->xDlClose(pVfs, pHandle);
12184}
12185#endif /* SQLITE_OMIT_LOAD_EXTENSION */
12186SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12187  return pVfs->xRandomness(pVfs, nByte, zBufOut);
12188}
12189SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
12190  return pVfs->xSleep(pVfs, nMicro);
12191}
12192SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
12193  return pVfs->xCurrentTime(pVfs, pTimeOut);
12194}
12195
12196SQLITE_PRIVATE int sqlite3OsOpenMalloc(
12197  sqlite3_vfs *pVfs,
12198  const char *zFile,
12199  sqlite3_file **ppFile,
12200  int flags,
12201  int *pOutFlags
12202){
12203  int rc = SQLITE_NOMEM;
12204  sqlite3_file *pFile;
12205  pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
12206  if( pFile ){
12207    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
12208    if( rc!=SQLITE_OK ){
12209      sqlite3_free(pFile);
12210    }else{
12211      *ppFile = pFile;
12212    }
12213  }
12214  return rc;
12215}
12216SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
12217  int rc = SQLITE_OK;
12218  assert( pFile );
12219  rc = sqlite3OsClose(pFile);
12220  sqlite3_free(pFile);
12221  return rc;
12222}
12223
12224/*
12225** This function is a wrapper around the OS specific implementation of
12226** sqlite3_os_init(). The purpose of the wrapper is to provide the
12227** ability to simulate a malloc failure, so that the handling of an
12228** error in sqlite3_os_init() by the upper layers can be tested.
12229*/
12230SQLITE_PRIVATE int sqlite3OsInit(void){
12231  void *p = sqlite3_malloc(10);
12232  if( p==0 ) return SQLITE_NOMEM;
12233  sqlite3_free(p);
12234  return sqlite3_os_init();
12235}
12236
12237/*
12238** The list of all registered VFS implementations.
12239*/
12240static sqlite3_vfs * SQLITE_WSD vfsList = 0;
12241#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
12242
12243/*
12244** Locate a VFS by name.  If no name is given, simply return the
12245** first VFS on the list.
12246*/
12247SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
12248  sqlite3_vfs *pVfs = 0;
12249#if SQLITE_THREADSAFE
12250  sqlite3_mutex *mutex;
12251#endif
12252#ifndef SQLITE_OMIT_AUTOINIT
12253  int rc = sqlite3_initialize();
12254  if( rc ) return 0;
12255#endif
12256#if SQLITE_THREADSAFE
12257  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12258#endif
12259  sqlite3_mutex_enter(mutex);
12260  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
12261    if( zVfs==0 ) break;
12262    if( strcmp(zVfs, pVfs->zName)==0 ) break;
12263  }
12264  sqlite3_mutex_leave(mutex);
12265  return pVfs;
12266}
12267
12268/*
12269** Unlink a VFS from the linked list
12270*/
12271static void vfsUnlink(sqlite3_vfs *pVfs){
12272  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
12273  if( pVfs==0 ){
12274    /* No-op */
12275  }else if( vfsList==pVfs ){
12276    vfsList = pVfs->pNext;
12277  }else if( vfsList ){
12278    sqlite3_vfs *p = vfsList;
12279    while( p->pNext && p->pNext!=pVfs ){
12280      p = p->pNext;
12281    }
12282    if( p->pNext==pVfs ){
12283      p->pNext = pVfs->pNext;
12284    }
12285  }
12286}
12287
12288/*
12289** Register a VFS with the system.  It is harmless to register the same
12290** VFS multiple times.  The new VFS becomes the default if makeDflt is
12291** true.
12292*/
12293SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
12294  sqlite3_mutex *mutex = 0;
12295#ifndef SQLITE_OMIT_AUTOINIT
12296  int rc = sqlite3_initialize();
12297  if( rc ) return rc;
12298#endif
12299  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12300  sqlite3_mutex_enter(mutex);
12301  vfsUnlink(pVfs);
12302  if( makeDflt || vfsList==0 ){
12303    pVfs->pNext = vfsList;
12304    vfsList = pVfs;
12305  }else{
12306    pVfs->pNext = vfsList->pNext;
12307    vfsList->pNext = pVfs;
12308  }
12309  assert(vfsList);
12310  sqlite3_mutex_leave(mutex);
12311  return SQLITE_OK;
12312}
12313
12314/*
12315** Unregister a VFS so that it is no longer accessible.
12316*/
12317SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
12318#if SQLITE_THREADSAFE
12319  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12320#endif
12321  sqlite3_mutex_enter(mutex);
12322  vfsUnlink(pVfs);
12323  sqlite3_mutex_leave(mutex);
12324  return SQLITE_OK;
12325}
12326
12327/************** End of os.c **************************************************/
12328/************** Begin file fault.c *******************************************/
12329/*
12330** 2008 Jan 22
12331**
12332** The author disclaims copyright to this source code.  In place of
12333** a legal notice, here is a blessing:
12334**
12335**    May you do good and not evil.
12336**    May you find forgiveness for yourself and forgive others.
12337**    May you share freely, never taking more than you give.
12338**
12339*************************************************************************
12340**
12341** This file contains code to support the concept of "benign"
12342** malloc failures (when the xMalloc() or xRealloc() method of the
12343** sqlite3_mem_methods structure fails to allocate a block of memory
12344** and returns 0).
12345**
12346** Most malloc failures are non-benign. After they occur, SQLite
12347** abandons the current operation and returns an error code (usually
12348** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
12349** fatal. For example, if a malloc fails while resizing a hash table, this
12350** is completely recoverable simply by not carrying out the resize. The
12351** hash table will continue to function normally.  So a malloc failure
12352** during a hash table resize is a benign fault.
12353*/
12354
12355
12356#ifndef SQLITE_OMIT_BUILTIN_TEST
12357
12358/*
12359** Global variables.
12360*/
12361typedef struct BenignMallocHooks BenignMallocHooks;
12362static SQLITE_WSD struct BenignMallocHooks {
12363  void (*xBenignBegin)(void);
12364  void (*xBenignEnd)(void);
12365} sqlite3Hooks = { 0, 0 };
12366
12367/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
12368** structure.  If writable static data is unsupported on the target,
12369** we have to locate the state vector at run-time.  In the more common
12370** case where writable static data is supported, wsdHooks can refer directly
12371** to the "sqlite3Hooks" state vector declared above.
12372*/
12373#ifdef SQLITE_OMIT_WSD
12374# define wsdHooksInit \
12375  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
12376# define wsdHooks x[0]
12377#else
12378# define wsdHooksInit
12379# define wsdHooks sqlite3Hooks
12380#endif
12381
12382
12383/*
12384** Register hooks to call when sqlite3BeginBenignMalloc() and
12385** sqlite3EndBenignMalloc() are called, respectively.
12386*/
12387SQLITE_PRIVATE void sqlite3BenignMallocHooks(
12388  void (*xBenignBegin)(void),
12389  void (*xBenignEnd)(void)
12390){
12391  wsdHooksInit;
12392  wsdHooks.xBenignBegin = xBenignBegin;
12393  wsdHooks.xBenignEnd = xBenignEnd;
12394}
12395
12396/*
12397** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
12398** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
12399** indicates that subsequent malloc failures are non-benign.
12400*/
12401SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
12402  wsdHooksInit;
12403  if( wsdHooks.xBenignBegin ){
12404    wsdHooks.xBenignBegin();
12405  }
12406}
12407SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
12408  wsdHooksInit;
12409  if( wsdHooks.xBenignEnd ){
12410    wsdHooks.xBenignEnd();
12411  }
12412}
12413
12414#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
12415
12416/************** End of fault.c ***********************************************/
12417/************** Begin file mem0.c ********************************************/
12418/*
12419** 2008 October 28
12420**
12421** The author disclaims copyright to this source code.  In place of
12422** a legal notice, here is a blessing:
12423**
12424**    May you do good and not evil.
12425**    May you find forgiveness for yourself and forgive others.
12426**    May you share freely, never taking more than you give.
12427**
12428*************************************************************************
12429**
12430** This file contains a no-op memory allocation drivers for use when
12431** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
12432** here always fail.  SQLite will not operate with these drivers.  These
12433** are merely placeholders.  Real drivers must be substituted using
12434** sqlite3_config() before SQLite will operate.
12435*/
12436
12437/*
12438** This version of the memory allocator is the default.  It is
12439** used when no other memory allocator is specified using compile-time
12440** macros.
12441*/
12442#ifdef SQLITE_ZERO_MALLOC
12443
12444/*
12445** No-op versions of all memory allocation routines
12446*/
12447static void *sqlite3MemMalloc(int nByte){ return 0; }
12448static void sqlite3MemFree(void *pPrior){ return; }
12449static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
12450static int sqlite3MemSize(void *pPrior){ return 0; }
12451static int sqlite3MemRoundup(int n){ return n; }
12452static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
12453static void sqlite3MemShutdown(void *NotUsed){ return; }
12454
12455/*
12456** This routine is the only routine in this file with external linkage.
12457**
12458** Populate the low-level memory allocation function pointers in
12459** sqlite3GlobalConfig.m with pointers to the routines in this file.
12460*/
12461SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12462  static const sqlite3_mem_methods defaultMethods = {
12463     sqlite3MemMalloc,
12464     sqlite3MemFree,
12465     sqlite3MemRealloc,
12466     sqlite3MemSize,
12467     sqlite3MemRoundup,
12468     sqlite3MemInit,
12469     sqlite3MemShutdown,
12470     0
12471  };
12472  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12473}
12474
12475#endif /* SQLITE_ZERO_MALLOC */
12476
12477/************** End of mem0.c ************************************************/
12478/************** Begin file mem1.c ********************************************/
12479/*
12480** 2007 August 14
12481**
12482** The author disclaims copyright to this source code.  In place of
12483** a legal notice, here is a blessing:
12484**
12485**    May you do good and not evil.
12486**    May you find forgiveness for yourself and forgive others.
12487**    May you share freely, never taking more than you give.
12488**
12489*************************************************************************
12490**
12491** This file contains low-level memory allocation drivers for when
12492** SQLite will use the standard C-library malloc/realloc/free interface
12493** to obtain the memory it needs.
12494**
12495** This file contains implementations of the low-level memory allocation
12496** routines specified in the sqlite3_mem_methods object.
12497*/
12498
12499/*
12500** This version of the memory allocator is the default.  It is
12501** used when no other memory allocator is specified using compile-time
12502** macros.
12503*/
12504#ifdef SQLITE_SYSTEM_MALLOC
12505
12506/*
12507** Like malloc(), but remember the size of the allocation
12508** so that we can find it later using sqlite3MemSize().
12509**
12510** For this low-level routine, we are guaranteed that nByte>0 because
12511** cases of nByte<=0 will be intercepted and dealt with by higher level
12512** routines.
12513*/
12514static void *sqlite3MemMalloc(int nByte){
12515  sqlite3_int64 *p;
12516  assert( nByte>0 );
12517  nByte = ROUND8(nByte);
12518  p = malloc( nByte+8 );
12519  if( p ){
12520    p[0] = nByte;
12521    p++;
12522  }
12523  return (void *)p;
12524}
12525
12526/*
12527** Like free() but works for allocations obtained from sqlite3MemMalloc()
12528** or sqlite3MemRealloc().
12529**
12530** For this low-level routine, we already know that pPrior!=0 since
12531** cases where pPrior==0 will have been intecepted and dealt with
12532** by higher-level routines.
12533*/
12534static void sqlite3MemFree(void *pPrior){
12535  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12536  assert( pPrior!=0 );
12537  p--;
12538  free(p);
12539}
12540
12541/*
12542** Like realloc().  Resize an allocation previously obtained from
12543** sqlite3MemMalloc().
12544**
12545** For this low-level interface, we know that pPrior!=0.  Cases where
12546** pPrior==0 while have been intercepted by higher-level routine and
12547** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
12548** cases where nByte<=0 will have been intercepted by higher-level
12549** routines and redirected to xFree.
12550*/
12551static void *sqlite3MemRealloc(void *pPrior, int nByte){
12552  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12553  assert( pPrior!=0 && nByte>0 );
12554  nByte = ROUND8(nByte);
12555  p = (sqlite3_int64*)pPrior;
12556  p--;
12557  p = realloc(p, nByte+8 );
12558  if( p ){
12559    p[0] = nByte;
12560    p++;
12561  }
12562  return (void*)p;
12563}
12564
12565/*
12566** Report the allocated size of a prior return from xMalloc()
12567** or xRealloc().
12568*/
12569static int sqlite3MemSize(void *pPrior){
12570  sqlite3_int64 *p;
12571  if( pPrior==0 ) return 0;
12572  p = (sqlite3_int64*)pPrior;
12573  p--;
12574  return (int)p[0];
12575}
12576
12577/*
12578** Round up a request size to the next valid allocation size.
12579*/
12580static int sqlite3MemRoundup(int n){
12581  return ROUND8(n);
12582}
12583
12584/*
12585** Initialize this module.
12586*/
12587static int sqlite3MemInit(void *NotUsed){
12588  UNUSED_PARAMETER(NotUsed);
12589  return SQLITE_OK;
12590}
12591
12592/*
12593** Deinitialize this module.
12594*/
12595static void sqlite3MemShutdown(void *NotUsed){
12596  UNUSED_PARAMETER(NotUsed);
12597  return;
12598}
12599
12600/*
12601** This routine is the only routine in this file with external linkage.
12602**
12603** Populate the low-level memory allocation function pointers in
12604** sqlite3GlobalConfig.m with pointers to the routines in this file.
12605*/
12606SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12607  static const sqlite3_mem_methods defaultMethods = {
12608     sqlite3MemMalloc,
12609     sqlite3MemFree,
12610     sqlite3MemRealloc,
12611     sqlite3MemSize,
12612     sqlite3MemRoundup,
12613     sqlite3MemInit,
12614     sqlite3MemShutdown,
12615     0
12616  };
12617  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12618}
12619
12620#endif /* SQLITE_SYSTEM_MALLOC */
12621
12622/************** End of mem1.c ************************************************/
12623/************** Begin file mem2.c ********************************************/
12624/*
12625** 2007 August 15
12626**
12627** The author disclaims copyright to this source code.  In place of
12628** a legal notice, here is a blessing:
12629**
12630**    May you do good and not evil.
12631**    May you find forgiveness for yourself and forgive others.
12632**    May you share freely, never taking more than you give.
12633**
12634*************************************************************************
12635**
12636** This file contains low-level memory allocation drivers for when
12637** SQLite will use the standard C-library malloc/realloc/free interface
12638** to obtain the memory it needs while adding lots of additional debugging
12639** information to each allocation in order to help detect and fix memory
12640** leaks and memory usage errors.
12641**
12642** This file contains implementations of the low-level memory allocation
12643** routines specified in the sqlite3_mem_methods object.
12644*/
12645
12646/*
12647** This version of the memory allocator is used only if the
12648** SQLITE_MEMDEBUG macro is defined
12649*/
12650#ifdef SQLITE_MEMDEBUG
12651
12652/*
12653** The backtrace functionality is only available with GLIBC
12654*/
12655#ifdef __GLIBC__
12656  extern int backtrace(void**,int);
12657  extern void backtrace_symbols_fd(void*const*,int,int);
12658#else
12659# define backtrace(A,B) 1
12660# define backtrace_symbols_fd(A,B,C)
12661#endif
12662
12663/*
12664** Each memory allocation looks like this:
12665**
12666**  ------------------------------------------------------------------------
12667**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
12668**  ------------------------------------------------------------------------
12669**
12670** The application code sees only a pointer to the allocation.  We have
12671** to back up from the allocation pointer to find the MemBlockHdr.  The
12672** MemBlockHdr tells us the size of the allocation and the number of
12673** backtrace pointers.  There is also a guard word at the end of the
12674** MemBlockHdr.
12675*/
12676struct MemBlockHdr {
12677  i64 iSize;                          /* Size of this allocation */
12678  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
12679  char nBacktrace;                    /* Number of backtraces on this alloc */
12680  char nBacktraceSlots;               /* Available backtrace slots */
12681  short nTitle;                       /* Bytes of title; includes '\0' */
12682  int iForeGuard;                     /* Guard word for sanity */
12683};
12684
12685/*
12686** Guard words
12687*/
12688#define FOREGUARD 0x80F5E153
12689#define REARGUARD 0xE4676B53
12690
12691/*
12692** Number of malloc size increments to track.
12693*/
12694#define NCSIZE  1000
12695
12696/*
12697** All of the static variables used by this module are collected
12698** into a single structure named "mem".  This is to keep the
12699** static variables organized and to reduce namespace pollution
12700** when this module is combined with other in the amalgamation.
12701*/
12702static struct {
12703
12704  /*
12705  ** Mutex to control access to the memory allocation subsystem.
12706  */
12707  sqlite3_mutex *mutex;
12708
12709  /*
12710  ** Head and tail of a linked list of all outstanding allocations
12711  */
12712  struct MemBlockHdr *pFirst;
12713  struct MemBlockHdr *pLast;
12714
12715  /*
12716  ** The number of levels of backtrace to save in new allocations.
12717  */
12718  int nBacktrace;
12719  void (*xBacktrace)(int, int, void **);
12720
12721  /*
12722  ** Title text to insert in front of each block
12723  */
12724  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
12725  char zTitle[100];  /* The title text */
12726
12727  /*
12728  ** sqlite3MallocDisallow() increments the following counter.
12729  ** sqlite3MallocAllow() decrements it.
12730  */
12731  int disallow; /* Do not allow memory allocation */
12732
12733  /*
12734  ** Gather statistics on the sizes of memory allocations.
12735  ** nAlloc[i] is the number of allocation attempts of i*8
12736  ** bytes.  i==NCSIZE is the number of allocation attempts for
12737  ** sizes more than NCSIZE*8 bytes.
12738  */
12739  int nAlloc[NCSIZE];      /* Total number of allocations */
12740  int nCurrent[NCSIZE];    /* Current number of allocations */
12741  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
12742
12743} mem;
12744
12745
12746/*
12747** Adjust memory usage statistics
12748*/
12749static void adjustStats(int iSize, int increment){
12750  int i = ROUND8(iSize)/8;
12751  if( i>NCSIZE-1 ){
12752    i = NCSIZE - 1;
12753  }
12754  if( increment>0 ){
12755    mem.nAlloc[i]++;
12756    mem.nCurrent[i]++;
12757    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
12758      mem.mxCurrent[i] = mem.nCurrent[i];
12759    }
12760  }else{
12761    mem.nCurrent[i]--;
12762    assert( mem.nCurrent[i]>=0 );
12763  }
12764}
12765
12766/*
12767** Given an allocation, find the MemBlockHdr for that allocation.
12768**
12769** This routine checks the guards at either end of the allocation and
12770** if they are incorrect it asserts.
12771*/
12772static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
12773  struct MemBlockHdr *p;
12774  int *pInt;
12775  u8 *pU8;
12776  int nReserve;
12777
12778  p = (struct MemBlockHdr*)pAllocation;
12779  p--;
12780  assert( p->iForeGuard==(int)FOREGUARD );
12781  nReserve = ROUND8(p->iSize);
12782  pInt = (int*)pAllocation;
12783  pU8 = (u8*)pAllocation;
12784  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
12785  /* This checks any of the "extra" bytes allocated due
12786  ** to rounding up to an 8 byte boundary to ensure
12787  ** they haven't been overwritten.
12788  */
12789  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
12790  return p;
12791}
12792
12793/*
12794** Return the number of bytes currently allocated at address p.
12795*/
12796static int sqlite3MemSize(void *p){
12797  struct MemBlockHdr *pHdr;
12798  if( !p ){
12799    return 0;
12800  }
12801  pHdr = sqlite3MemsysGetHeader(p);
12802  return pHdr->iSize;
12803}
12804
12805/*
12806** Initialize the memory allocation subsystem.
12807*/
12808static int sqlite3MemInit(void *NotUsed){
12809  UNUSED_PARAMETER(NotUsed);
12810  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
12811  if( !sqlite3GlobalConfig.bMemstat ){
12812    /* If memory status is enabled, then the malloc.c wrapper will already
12813    ** hold the STATIC_MEM mutex when the routines here are invoked. */
12814    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
12815  }
12816  return SQLITE_OK;
12817}
12818
12819/*
12820** Deinitialize the memory allocation subsystem.
12821*/
12822static void sqlite3MemShutdown(void *NotUsed){
12823  UNUSED_PARAMETER(NotUsed);
12824  mem.mutex = 0;
12825}
12826
12827/*
12828** Round up a request size to the next valid allocation size.
12829*/
12830static int sqlite3MemRoundup(int n){
12831  return ROUND8(n);
12832}
12833
12834/*
12835** Fill a buffer with pseudo-random bytes.  This is used to preset
12836** the content of a new memory allocation to unpredictable values and
12837** to clear the content of a freed allocation to unpredictable values.
12838*/
12839static void randomFill(char *pBuf, int nByte){
12840  unsigned int x, y, r;
12841  x = SQLITE_PTR_TO_INT(pBuf);
12842  y = nByte | 1;
12843  while( nByte >= 4 ){
12844    x = (x>>1) ^ (-(x&1) & 0xd0000001);
12845    y = y*1103515245 + 12345;
12846    r = x ^ y;
12847    *(int*)pBuf = r;
12848    pBuf += 4;
12849    nByte -= 4;
12850  }
12851  while( nByte-- > 0 ){
12852    x = (x>>1) ^ (-(x&1) & 0xd0000001);
12853    y = y*1103515245 + 12345;
12854    r = x ^ y;
12855    *(pBuf++) = r & 0xff;
12856  }
12857}
12858
12859/*
12860** Allocate nByte bytes of memory.
12861*/
12862static void *sqlite3MemMalloc(int nByte){
12863  struct MemBlockHdr *pHdr;
12864  void **pBt;
12865  char *z;
12866  int *pInt;
12867  void *p = 0;
12868  int totalSize;
12869  int nReserve;
12870  sqlite3_mutex_enter(mem.mutex);
12871  assert( mem.disallow==0 );
12872  nReserve = ROUND8(nByte);
12873  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
12874               mem.nBacktrace*sizeof(void*) + mem.nTitle;
12875  p = malloc(totalSize);
12876  if( p ){
12877    z = p;
12878    pBt = (void**)&z[mem.nTitle];
12879    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
12880    pHdr->pNext = 0;
12881    pHdr->pPrev = mem.pLast;
12882    if( mem.pLast ){
12883      mem.pLast->pNext = pHdr;
12884    }else{
12885      mem.pFirst = pHdr;
12886    }
12887    mem.pLast = pHdr;
12888    pHdr->iForeGuard = FOREGUARD;
12889    pHdr->nBacktraceSlots = mem.nBacktrace;
12890    pHdr->nTitle = mem.nTitle;
12891    if( mem.nBacktrace ){
12892      void *aAddr[40];
12893      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
12894      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
12895      assert(pBt[0]);
12896      if( mem.xBacktrace ){
12897        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
12898      }
12899    }else{
12900      pHdr->nBacktrace = 0;
12901    }
12902    if( mem.nTitle ){
12903      memcpy(z, mem.zTitle, mem.nTitle);
12904    }
12905    pHdr->iSize = nByte;
12906    adjustStats(nByte, +1);
12907    pInt = (int*)&pHdr[1];
12908    pInt[nReserve/sizeof(int)] = REARGUARD;
12909    randomFill((char*)pInt, nByte);
12910    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
12911    p = (void*)pInt;
12912  }
12913  sqlite3_mutex_leave(mem.mutex);
12914  return p;
12915}
12916
12917/*
12918** Free memory.
12919*/
12920static void sqlite3MemFree(void *pPrior){
12921  struct MemBlockHdr *pHdr;
12922  void **pBt;
12923  char *z;
12924  assert( sqlite3GlobalConfig.bMemstat || mem.mutex!=0 );
12925  pHdr = sqlite3MemsysGetHeader(pPrior);
12926  pBt = (void**)pHdr;
12927  pBt -= pHdr->nBacktraceSlots;
12928  sqlite3_mutex_enter(mem.mutex);
12929  if( pHdr->pPrev ){
12930    assert( pHdr->pPrev->pNext==pHdr );
12931    pHdr->pPrev->pNext = pHdr->pNext;
12932  }else{
12933    assert( mem.pFirst==pHdr );
12934    mem.pFirst = pHdr->pNext;
12935  }
12936  if( pHdr->pNext ){
12937    assert( pHdr->pNext->pPrev==pHdr );
12938    pHdr->pNext->pPrev = pHdr->pPrev;
12939  }else{
12940    assert( mem.pLast==pHdr );
12941    mem.pLast = pHdr->pPrev;
12942  }
12943  z = (char*)pBt;
12944  z -= pHdr->nTitle;
12945  adjustStats(pHdr->iSize, -1);
12946  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
12947                pHdr->iSize + sizeof(int) + pHdr->nTitle);
12948  free(z);
12949  sqlite3_mutex_leave(mem.mutex);
12950}
12951
12952/*
12953** Change the size of an existing memory allocation.
12954**
12955** For this debugging implementation, we *always* make a copy of the
12956** allocation into a new place in memory.  In this way, if the
12957** higher level code is using pointer to the old allocation, it is
12958** much more likely to break and we are much more liking to find
12959** the error.
12960*/
12961static void *sqlite3MemRealloc(void *pPrior, int nByte){
12962  struct MemBlockHdr *pOldHdr;
12963  void *pNew;
12964  assert( mem.disallow==0 );
12965  pOldHdr = sqlite3MemsysGetHeader(pPrior);
12966  pNew = sqlite3MemMalloc(nByte);
12967  if( pNew ){
12968    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
12969    if( nByte>pOldHdr->iSize ){
12970      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
12971    }
12972    sqlite3MemFree(pPrior);
12973  }
12974  return pNew;
12975}
12976
12977/*
12978** Populate the low-level memory allocation function pointers in
12979** sqlite3GlobalConfig.m with pointers to the routines in this file.
12980*/
12981SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12982  static const sqlite3_mem_methods defaultMethods = {
12983     sqlite3MemMalloc,
12984     sqlite3MemFree,
12985     sqlite3MemRealloc,
12986     sqlite3MemSize,
12987     sqlite3MemRoundup,
12988     sqlite3MemInit,
12989     sqlite3MemShutdown,
12990     0
12991  };
12992  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12993}
12994
12995/*
12996** Set the number of backtrace levels kept for each allocation.
12997** A value of zero turns off backtracing.  The number is always rounded
12998** up to a multiple of 2.
12999*/
13000SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
13001  if( depth<0 ){ depth = 0; }
13002  if( depth>20 ){ depth = 20; }
13003  depth = (depth+1)&0xfe;
13004  mem.nBacktrace = depth;
13005}
13006
13007SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
13008  mem.xBacktrace = xBacktrace;
13009}
13010
13011/*
13012** Set the title string for subsequent allocations.
13013*/
13014SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
13015  unsigned int n = sqlite3Strlen30(zTitle) + 1;
13016  sqlite3_mutex_enter(mem.mutex);
13017  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
13018  memcpy(mem.zTitle, zTitle, n);
13019  mem.zTitle[n] = 0;
13020  mem.nTitle = ROUND8(n);
13021  sqlite3_mutex_leave(mem.mutex);
13022}
13023
13024SQLITE_PRIVATE void sqlite3MemdebugSync(){
13025  struct MemBlockHdr *pHdr;
13026  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13027    void **pBt = (void**)pHdr;
13028    pBt -= pHdr->nBacktraceSlots;
13029    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
13030  }
13031}
13032
13033/*
13034** Open the file indicated and write a log of all unfreed memory
13035** allocations into that log.
13036*/
13037SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
13038  FILE *out;
13039  struct MemBlockHdr *pHdr;
13040  void **pBt;
13041  int i;
13042  out = fopen(zFilename, "w");
13043  if( out==0 ){
13044    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13045                    zFilename);
13046    return;
13047  }
13048  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13049    char *z = (char*)pHdr;
13050    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
13051    fprintf(out, "**** %lld bytes at %p from %s ****\n",
13052            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
13053    if( pHdr->nBacktrace ){
13054      fflush(out);
13055      pBt = (void**)pHdr;
13056      pBt -= pHdr->nBacktraceSlots;
13057      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
13058      fprintf(out, "\n");
13059    }
13060  }
13061  fprintf(out, "COUNTS:\n");
13062  for(i=0; i<NCSIZE-1; i++){
13063    if( mem.nAlloc[i] ){
13064      fprintf(out, "   %5d: %10d %10d %10d\n",
13065            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
13066    }
13067  }
13068  if( mem.nAlloc[NCSIZE-1] ){
13069    fprintf(out, "   %5d: %10d %10d %10d\n",
13070             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
13071             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
13072  }
13073  fclose(out);
13074}
13075
13076/*
13077** Return the number of times sqlite3MemMalloc() has been called.
13078*/
13079SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
13080  int i;
13081  int nTotal = 0;
13082  for(i=0; i<NCSIZE; i++){
13083    nTotal += mem.nAlloc[i];
13084  }
13085  return nTotal;
13086}
13087
13088
13089#endif /* SQLITE_MEMDEBUG */
13090
13091/************** End of mem2.c ************************************************/
13092/************** Begin file mem3.c ********************************************/
13093/*
13094** 2007 October 14
13095**
13096** The author disclaims copyright to this source code.  In place of
13097** a legal notice, here is a blessing:
13098**
13099**    May you do good and not evil.
13100**    May you find forgiveness for yourself and forgive others.
13101**    May you share freely, never taking more than you give.
13102**
13103*************************************************************************
13104** This file contains the C functions that implement a memory
13105** allocation subsystem for use by SQLite.
13106**
13107** This version of the memory allocation subsystem omits all
13108** use of malloc(). The SQLite user supplies a block of memory
13109** before calling sqlite3_initialize() from which allocations
13110** are made and returned by the xMalloc() and xRealloc()
13111** implementations. Once sqlite3_initialize() has been called,
13112** the amount of memory available to SQLite is fixed and cannot
13113** be changed.
13114**
13115** This version of the memory allocation subsystem is included
13116** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
13117*/
13118
13119/*
13120** This version of the memory allocator is only built into the library
13121** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
13122** mean that the library will use a memory-pool by default, just that
13123** it is available. The mempool allocator is activated by calling
13124** sqlite3_config().
13125*/
13126#ifdef SQLITE_ENABLE_MEMSYS3
13127
13128/*
13129** Maximum size (in Mem3Blocks) of a "small" chunk.
13130*/
13131#define MX_SMALL 10
13132
13133
13134/*
13135** Number of freelist hash slots
13136*/
13137#define N_HASH  61
13138
13139/*
13140** A memory allocation (also called a "chunk") consists of two or
13141** more blocks where each block is 8 bytes.  The first 8 bytes are
13142** a header that is not returned to the user.
13143**
13144** A chunk is two or more blocks that is either checked out or
13145** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
13146** size of the allocation in blocks if the allocation is free.
13147** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13148** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13149** is true if the previous chunk is checked out and false if the
13150** previous chunk is free.  The u.hdr.prevSize field is the size of
13151** the previous chunk in blocks if the previous chunk is on the
13152** freelist. If the previous chunk is checked out, then
13153** u.hdr.prevSize can be part of the data for that chunk and should
13154** not be read or written.
13155**
13156** We often identify a chunk by its index in mem3.aPool[].  When
13157** this is done, the chunk index refers to the second block of
13158** the chunk.  In this way, the first chunk has an index of 1.
13159** A chunk index of 0 means "no such chunk" and is the equivalent
13160** of a NULL pointer.
13161**
13162** The second block of free chunks is of the form u.list.  The
13163** two fields form a double-linked list of chunks of related sizes.
13164** Pointers to the head of the list are stored in mem3.aiSmall[]
13165** for smaller chunks and mem3.aiHash[] for larger chunks.
13166**
13167** The second block of a chunk is user data if the chunk is checked
13168** out.  If a chunk is checked out, the user data may extend into
13169** the u.hdr.prevSize value of the following chunk.
13170*/
13171typedef struct Mem3Block Mem3Block;
13172struct Mem3Block {
13173  union {
13174    struct {
13175      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
13176      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
13177    } hdr;
13178    struct {
13179      u32 next;       /* Index in mem3.aPool[] of next free chunk */
13180      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
13181    } list;
13182  } u;
13183};
13184
13185/*
13186** All of the static variables used by this module are collected
13187** into a single structure named "mem3".  This is to keep the
13188** static variables organized and to reduce namespace pollution
13189** when this module is combined with other in the amalgamation.
13190*/
13191static SQLITE_WSD struct Mem3Global {
13192  /*
13193  ** Memory available for allocation. nPool is the size of the array
13194  ** (in Mem3Blocks) pointed to by aPool less 2.
13195  */
13196  u32 nPool;
13197  Mem3Block *aPool;
13198
13199  /*
13200  ** True if we are evaluating an out-of-memory callback.
13201  */
13202  int alarmBusy;
13203
13204  /*
13205  ** Mutex to control access to the memory allocation subsystem.
13206  */
13207  sqlite3_mutex *mutex;
13208
13209  /*
13210  ** The minimum amount of free space that we have seen.
13211  */
13212  u32 mnMaster;
13213
13214  /*
13215  ** iMaster is the index of the master chunk.  Most new allocations
13216  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
13217  ** of the current master.  iMaster is 0 if there is not master chunk.
13218  ** The master chunk is not in either the aiHash[] or aiSmall[].
13219  */
13220  u32 iMaster;
13221  u32 szMaster;
13222
13223  /*
13224  ** Array of lists of free blocks according to the block size
13225  ** for smaller chunks, or a hash on the block size for larger
13226  ** chunks.
13227  */
13228  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
13229  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
13230} mem3 = { 97535575 };
13231
13232#define mem3 GLOBAL(struct Mem3Global, mem3)
13233
13234/*
13235** Unlink the chunk at mem3.aPool[i] from list it is currently
13236** on.  *pRoot is the list that i is a member of.
13237*/
13238static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
13239  u32 next = mem3.aPool[i].u.list.next;
13240  u32 prev = mem3.aPool[i].u.list.prev;
13241  assert( sqlite3_mutex_held(mem3.mutex) );
13242  if( prev==0 ){
13243    *pRoot = next;
13244  }else{
13245    mem3.aPool[prev].u.list.next = next;
13246  }
13247  if( next ){
13248    mem3.aPool[next].u.list.prev = prev;
13249  }
13250  mem3.aPool[i].u.list.next = 0;
13251  mem3.aPool[i].u.list.prev = 0;
13252}
13253
13254/*
13255** Unlink the chunk at index i from
13256** whatever list is currently a member of.
13257*/
13258static void memsys3Unlink(u32 i){
13259  u32 size, hash;
13260  assert( sqlite3_mutex_held(mem3.mutex) );
13261  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13262  assert( i>=1 );
13263  size = mem3.aPool[i-1].u.hdr.size4x/4;
13264  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13265  assert( size>=2 );
13266  if( size <= MX_SMALL ){
13267    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
13268  }else{
13269    hash = size % N_HASH;
13270    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13271  }
13272}
13273
13274/*
13275** Link the chunk at mem3.aPool[i] so that is on the list rooted
13276** at *pRoot.
13277*/
13278static void memsys3LinkIntoList(u32 i, u32 *pRoot){
13279  assert( sqlite3_mutex_held(mem3.mutex) );
13280  mem3.aPool[i].u.list.next = *pRoot;
13281  mem3.aPool[i].u.list.prev = 0;
13282  if( *pRoot ){
13283    mem3.aPool[*pRoot].u.list.prev = i;
13284  }
13285  *pRoot = i;
13286}
13287
13288/*
13289** Link the chunk at index i into either the appropriate
13290** small chunk list, or into the large chunk hash table.
13291*/
13292static void memsys3Link(u32 i){
13293  u32 size, hash;
13294  assert( sqlite3_mutex_held(mem3.mutex) );
13295  assert( i>=1 );
13296  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13297  size = mem3.aPool[i-1].u.hdr.size4x/4;
13298  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13299  assert( size>=2 );
13300  if( size <= MX_SMALL ){
13301    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
13302  }else{
13303    hash = size % N_HASH;
13304    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
13305  }
13306}
13307
13308/*
13309** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13310** will already be held (obtained by code in malloc.c) if
13311** sqlite3GlobalConfig.bMemStat is true.
13312*/
13313static void memsys3Enter(void){
13314  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
13315    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13316  }
13317  sqlite3_mutex_enter(mem3.mutex);
13318}
13319static void memsys3Leave(void){
13320  sqlite3_mutex_leave(mem3.mutex);
13321}
13322
13323/*
13324** Called when we are unable to satisfy an allocation of nBytes.
13325*/
13326static void memsys3OutOfMemory(int nByte){
13327  if( !mem3.alarmBusy ){
13328    mem3.alarmBusy = 1;
13329    assert( sqlite3_mutex_held(mem3.mutex) );
13330    sqlite3_mutex_leave(mem3.mutex);
13331    sqlite3_release_memory(nByte);
13332    sqlite3_mutex_enter(mem3.mutex);
13333    mem3.alarmBusy = 0;
13334  }
13335}
13336
13337
13338/*
13339** Chunk i is a free chunk that has been unlinked.  Adjust its
13340** size parameters for check-out and return a pointer to the
13341** user portion of the chunk.
13342*/
13343static void *memsys3Checkout(u32 i, u32 nBlock){
13344  u32 x;
13345  assert( sqlite3_mutex_held(mem3.mutex) );
13346  assert( i>=1 );
13347  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
13348  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
13349  x = mem3.aPool[i-1].u.hdr.size4x;
13350  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
13351  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
13352  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
13353  return &mem3.aPool[i];
13354}
13355
13356/*
13357** Carve a piece off of the end of the mem3.iMaster free chunk.
13358** Return a pointer to the new allocation.  Or, if the master chunk
13359** is not large enough, return 0.
13360*/
13361static void *memsys3FromMaster(u32 nBlock){
13362  assert( sqlite3_mutex_held(mem3.mutex) );
13363  assert( mem3.szMaster>=nBlock );
13364  if( nBlock>=mem3.szMaster-1 ){
13365    /* Use the entire master */
13366    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
13367    mem3.iMaster = 0;
13368    mem3.szMaster = 0;
13369    mem3.mnMaster = 0;
13370    return p;
13371  }else{
13372    /* Split the master block.  Return the tail. */
13373    u32 newi, x;
13374    newi = mem3.iMaster + mem3.szMaster - nBlock;
13375    assert( newi > mem3.iMaster+1 );
13376    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
13377    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
13378    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
13379    mem3.szMaster -= nBlock;
13380    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
13381    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13382    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13383    if( mem3.szMaster < mem3.mnMaster ){
13384      mem3.mnMaster = mem3.szMaster;
13385    }
13386    return (void*)&mem3.aPool[newi];
13387  }
13388}
13389
13390/*
13391** *pRoot is the head of a list of free chunks of the same size
13392** or same size hash.  In other words, *pRoot is an entry in either
13393** mem3.aiSmall[] or mem3.aiHash[].
13394**
13395** This routine examines all entries on the given list and tries
13396** to coalesce each entries with adjacent free chunks.
13397**
13398** If it sees a chunk that is larger than mem3.iMaster, it replaces
13399** the current mem3.iMaster with the new larger chunk.  In order for
13400** this mem3.iMaster replacement to work, the master chunk must be
13401** linked into the hash tables.  That is not the normal state of
13402** affairs, of course.  The calling routine must link the master
13403** chunk before invoking this routine, then must unlink the (possibly
13404** changed) master chunk once this routine has finished.
13405*/
13406static void memsys3Merge(u32 *pRoot){
13407  u32 iNext, prev, size, i, x;
13408
13409  assert( sqlite3_mutex_held(mem3.mutex) );
13410  for(i=*pRoot; i>0; i=iNext){
13411    iNext = mem3.aPool[i].u.list.next;
13412    size = mem3.aPool[i-1].u.hdr.size4x;
13413    assert( (size&1)==0 );
13414    if( (size&2)==0 ){
13415      memsys3UnlinkFromList(i, pRoot);
13416      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
13417      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
13418      if( prev==iNext ){
13419        iNext = mem3.aPool[prev].u.list.next;
13420      }
13421      memsys3Unlink(prev);
13422      size = i + size/4 - prev;
13423      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
13424      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
13425      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
13426      memsys3Link(prev);
13427      i = prev;
13428    }else{
13429      size /= 4;
13430    }
13431    if( size>mem3.szMaster ){
13432      mem3.iMaster = i;
13433      mem3.szMaster = size;
13434    }
13435  }
13436}
13437
13438/*
13439** Return a block of memory of at least nBytes in size.
13440** Return NULL if unable.
13441**
13442** This function assumes that the necessary mutexes, if any, are
13443** already held by the caller. Hence "Unsafe".
13444*/
13445static void *memsys3MallocUnsafe(int nByte){
13446  u32 i;
13447  u32 nBlock;
13448  u32 toFree;
13449
13450  assert( sqlite3_mutex_held(mem3.mutex) );
13451  assert( sizeof(Mem3Block)==8 );
13452  if( nByte<=12 ){
13453    nBlock = 2;
13454  }else{
13455    nBlock = (nByte + 11)/8;
13456  }
13457  assert( nBlock>=2 );
13458
13459  /* STEP 1:
13460  ** Look for an entry of the correct size in either the small
13461  ** chunk table or in the large chunk hash table.  This is
13462  ** successful most of the time (about 9 times out of 10).
13463  */
13464  if( nBlock <= MX_SMALL ){
13465    i = mem3.aiSmall[nBlock-2];
13466    if( i>0 ){
13467      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
13468      return memsys3Checkout(i, nBlock);
13469    }
13470  }else{
13471    int hash = nBlock % N_HASH;
13472    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
13473      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
13474        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13475        return memsys3Checkout(i, nBlock);
13476      }
13477    }
13478  }
13479
13480  /* STEP 2:
13481  ** Try to satisfy the allocation by carving a piece off of the end
13482  ** of the master chunk.  This step usually works if step 1 fails.
13483  */
13484  if( mem3.szMaster>=nBlock ){
13485    return memsys3FromMaster(nBlock);
13486  }
13487
13488
13489  /* STEP 3:
13490  ** Loop through the entire memory pool.  Coalesce adjacent free
13491  ** chunks.  Recompute the master chunk as the largest free chunk.
13492  ** Then try again to satisfy the allocation by carving a piece off
13493  ** of the end of the master chunk.  This step happens very
13494  ** rarely (we hope!)
13495  */
13496  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
13497    memsys3OutOfMemory(toFree);
13498    if( mem3.iMaster ){
13499      memsys3Link(mem3.iMaster);
13500      mem3.iMaster = 0;
13501      mem3.szMaster = 0;
13502    }
13503    for(i=0; i<N_HASH; i++){
13504      memsys3Merge(&mem3.aiHash[i]);
13505    }
13506    for(i=0; i<MX_SMALL-1; i++){
13507      memsys3Merge(&mem3.aiSmall[i]);
13508    }
13509    if( mem3.szMaster ){
13510      memsys3Unlink(mem3.iMaster);
13511      if( mem3.szMaster>=nBlock ){
13512        return memsys3FromMaster(nBlock);
13513      }
13514    }
13515  }
13516
13517  /* If none of the above worked, then we fail. */
13518  return 0;
13519}
13520
13521/*
13522** Free an outstanding memory allocation.
13523**
13524** This function assumes that the necessary mutexes, if any, are
13525** already held by the caller. Hence "Unsafe".
13526*/
13527void memsys3FreeUnsafe(void *pOld){
13528  Mem3Block *p = (Mem3Block*)pOld;
13529  int i;
13530  u32 size, x;
13531  assert( sqlite3_mutex_held(mem3.mutex) );
13532  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
13533  i = p - mem3.aPool;
13534  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
13535  size = mem3.aPool[i-1].u.hdr.size4x/4;
13536  assert( i+size<=mem3.nPool+1 );
13537  mem3.aPool[i-1].u.hdr.size4x &= ~1;
13538  mem3.aPool[i+size-1].u.hdr.prevSize = size;
13539  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
13540  memsys3Link(i);
13541
13542  /* Try to expand the master using the newly freed chunk */
13543  if( mem3.iMaster ){
13544    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
13545      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
13546      mem3.iMaster -= size;
13547      mem3.szMaster += size;
13548      memsys3Unlink(mem3.iMaster);
13549      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13550      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13551      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13552    }
13553    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13554    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
13555      memsys3Unlink(mem3.iMaster+mem3.szMaster);
13556      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
13557      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13558      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
13559    }
13560  }
13561}
13562
13563/*
13564** Return the size of an outstanding allocation, in bytes.  The
13565** size returned omits the 8-byte header overhead.  This only
13566** works for chunks that are currently checked out.
13567*/
13568static int memsys3Size(void *p){
13569  Mem3Block *pBlock;
13570  if( p==0 ) return 0;
13571  pBlock = (Mem3Block*)p;
13572  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
13573  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
13574}
13575
13576/*
13577** Round up a request size to the next valid allocation size.
13578*/
13579static int memsys3Roundup(int n){
13580  if( n<=12 ){
13581    return 12;
13582  }else{
13583    return ((n+11)&~7) - 4;
13584  }
13585}
13586
13587/*
13588** Allocate nBytes of memory.
13589*/
13590static void *memsys3Malloc(int nBytes){
13591  sqlite3_int64 *p;
13592  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
13593  memsys3Enter();
13594  p = memsys3MallocUnsafe(nBytes);
13595  memsys3Leave();
13596  return (void*)p;
13597}
13598
13599/*
13600** Free memory.
13601*/
13602void memsys3Free(void *pPrior){
13603  assert( pPrior );
13604  memsys3Enter();
13605  memsys3FreeUnsafe(pPrior);
13606  memsys3Leave();
13607}
13608
13609/*
13610** Change the size of an existing memory allocation
13611*/
13612void *memsys3Realloc(void *pPrior, int nBytes){
13613  int nOld;
13614  void *p;
13615  if( pPrior==0 ){
13616    return sqlite3_malloc(nBytes);
13617  }
13618  if( nBytes<=0 ){
13619    sqlite3_free(pPrior);
13620    return 0;
13621  }
13622  nOld = memsys3Size(pPrior);
13623  if( nBytes<=nOld && nBytes>=nOld-128 ){
13624    return pPrior;
13625  }
13626  memsys3Enter();
13627  p = memsys3MallocUnsafe(nBytes);
13628  if( p ){
13629    if( nOld<nBytes ){
13630      memcpy(p, pPrior, nOld);
13631    }else{
13632      memcpy(p, pPrior, nBytes);
13633    }
13634    memsys3FreeUnsafe(pPrior);
13635  }
13636  memsys3Leave();
13637  return p;
13638}
13639
13640/*
13641** Initialize this module.
13642*/
13643static int memsys3Init(void *NotUsed){
13644  UNUSED_PARAMETER(NotUsed);
13645  if( !sqlite3GlobalConfig.pHeap ){
13646    return SQLITE_ERROR;
13647  }
13648
13649  /* Store a pointer to the memory block in global structure mem3. */
13650  assert( sizeof(Mem3Block)==8 );
13651  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
13652  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
13653
13654  /* Initialize the master block. */
13655  mem3.szMaster = mem3.nPool;
13656  mem3.mnMaster = mem3.szMaster;
13657  mem3.iMaster = 1;
13658  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
13659  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
13660  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
13661
13662  return SQLITE_OK;
13663}
13664
13665/*
13666** Deinitialize this module.
13667*/
13668static void memsys3Shutdown(void *NotUsed){
13669  UNUSED_PARAMETER(NotUsed);
13670  mem3.mutex = 0;
13671  return;
13672}
13673
13674
13675
13676/*
13677** Open the file indicated and write a log of all unfreed memory
13678** allocations into that log.
13679*/
13680SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
13681#ifdef SQLITE_DEBUG
13682  FILE *out;
13683  u32 i, j;
13684  u32 size;
13685  if( zFilename==0 || zFilename[0]==0 ){
13686    out = stdout;
13687  }else{
13688    out = fopen(zFilename, "w");
13689    if( out==0 ){
13690      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13691                      zFilename);
13692      return;
13693    }
13694  }
13695  memsys3Enter();
13696  fprintf(out, "CHUNKS:\n");
13697  for(i=1; i<=mem3.nPool; i+=size/4){
13698    size = mem3.aPool[i-1].u.hdr.size4x;
13699    if( size/4<=1 ){
13700      fprintf(out, "%p size error\n", &mem3.aPool[i]);
13701      assert( 0 );
13702      break;
13703    }
13704    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
13705      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
13706      assert( 0 );
13707      break;
13708    }
13709    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
13710      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
13711      assert( 0 );
13712      break;
13713    }
13714    if( size&1 ){
13715      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
13716    }else{
13717      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
13718                  i==mem3.iMaster ? " **master**" : "");
13719    }
13720  }
13721  for(i=0; i<MX_SMALL-1; i++){
13722    if( mem3.aiSmall[i]==0 ) continue;
13723    fprintf(out, "small(%2d):", i);
13724    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
13725      fprintf(out, " %p(%d)", &mem3.aPool[j],
13726              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13727    }
13728    fprintf(out, "\n");
13729  }
13730  for(i=0; i<N_HASH; i++){
13731    if( mem3.aiHash[i]==0 ) continue;
13732    fprintf(out, "hash(%2d):", i);
13733    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
13734      fprintf(out, " %p(%d)", &mem3.aPool[j],
13735              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
13736    }
13737    fprintf(out, "\n");
13738  }
13739  fprintf(out, "master=%d\n", mem3.iMaster);
13740  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
13741  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
13742  sqlite3_mutex_leave(mem3.mutex);
13743  if( out==stdout ){
13744    fflush(stdout);
13745  }else{
13746    fclose(out);
13747  }
13748#else
13749  UNUSED_PARAMETER(zFilename);
13750#endif
13751}
13752
13753/*
13754** This routine is the only routine in this file with external
13755** linkage.
13756**
13757** Populate the low-level memory allocation function pointers in
13758** sqlite3GlobalConfig.m with pointers to the routines in this file. The
13759** arguments specify the block of memory to manage.
13760**
13761** This routine is only called by sqlite3_config(), and therefore
13762** is not required to be threadsafe (it is not).
13763*/
13764SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
13765  static const sqlite3_mem_methods mempoolMethods = {
13766     memsys3Malloc,
13767     memsys3Free,
13768     memsys3Realloc,
13769     memsys3Size,
13770     memsys3Roundup,
13771     memsys3Init,
13772     memsys3Shutdown,
13773     0
13774  };
13775  return &mempoolMethods;
13776}
13777
13778#endif /* SQLITE_ENABLE_MEMSYS3 */
13779
13780/************** End of mem3.c ************************************************/
13781/************** Begin file mem5.c ********************************************/
13782/*
13783** 2007 October 14
13784**
13785** The author disclaims copyright to this source code.  In place of
13786** a legal notice, here is a blessing:
13787**
13788**    May you do good and not evil.
13789**    May you find forgiveness for yourself and forgive others.
13790**    May you share freely, never taking more than you give.
13791**
13792*************************************************************************
13793** This file contains the C functions that implement a memory
13794** allocation subsystem for use by SQLite.
13795**
13796** This version of the memory allocation subsystem omits all
13797** use of malloc(). The application gives SQLite a block of memory
13798** before calling sqlite3_initialize() from which allocations
13799** are made and returned by the xMalloc() and xRealloc()
13800** implementations. Once sqlite3_initialize() has been called,
13801** the amount of memory available to SQLite is fixed and cannot
13802** be changed.
13803**
13804** This version of the memory allocation subsystem is included
13805** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
13806**
13807** This memory allocator uses the following algorithm:
13808**
13809**   1.  All memory allocations sizes are rounded up to a power of 2.
13810**
13811**   2.  If two adjacent free blocks are the halves of a larger block,
13812**       then the two blocks are coalesed into the single larger block.
13813**
13814**   3.  New memory is allocated from the first available free block.
13815**
13816** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
13817** Concerning Dynamic Storage Allocation". Journal of the Association for
13818** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
13819**
13820** Let n be the size of the largest allocation divided by the minimum
13821** allocation size (after rounding all sizes up to a power of 2.)  Let M
13822** be the maximum amount of memory ever outstanding at one time.  Let
13823** N be the total amount of memory available for allocation.  Robson
13824** proved that this memory allocator will never breakdown due to
13825** fragmentation as long as the following constraint holds:
13826**
13827**      N >=  M*(1 + log2(n)/2) - n + 1
13828**
13829** The sqlite3_status() logic tracks the maximum values of n and M so
13830** that an application can, at any time, verify this constraint.
13831*/
13832
13833/*
13834** This version of the memory allocator is used only when
13835** SQLITE_ENABLE_MEMSYS5 is defined.
13836*/
13837#ifdef SQLITE_ENABLE_MEMSYS5
13838
13839/*
13840** A minimum allocation is an instance of the following structure.
13841** Larger allocations are an array of these structures where the
13842** size of the array is a power of 2.
13843**
13844** The size of this object must be a power of two.  That fact is
13845** verified in memsys5Init().
13846*/
13847typedef struct Mem5Link Mem5Link;
13848struct Mem5Link {
13849  int next;       /* Index of next free chunk */
13850  int prev;       /* Index of previous free chunk */
13851};
13852
13853/*
13854** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
13855** mem5.szAtom is always at least 8 and 32-bit integers are used,
13856** it is not actually possible to reach this limit.
13857*/
13858#define LOGMAX 30
13859
13860/*
13861** Masks used for mem5.aCtrl[] elements.
13862*/
13863#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
13864#define CTRL_FREE     0x20    /* True if not checked out */
13865
13866/*
13867** All of the static variables used by this module are collected
13868** into a single structure named "mem5".  This is to keep the
13869** static variables organized and to reduce namespace pollution
13870** when this module is combined with other in the amalgamation.
13871*/
13872static SQLITE_WSD struct Mem5Global {
13873  /*
13874  ** Memory available for allocation
13875  */
13876  int szAtom;      /* Smallest possible allocation in bytes */
13877  int nBlock;      /* Number of szAtom sized blocks in zPool */
13878  u8 *zPool;       /* Memory available to be allocated */
13879
13880  /*
13881  ** Mutex to control access to the memory allocation subsystem.
13882  */
13883  sqlite3_mutex *mutex;
13884
13885  /*
13886  ** Performance statistics
13887  */
13888  u64 nAlloc;         /* Total number of calls to malloc */
13889  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
13890  u64 totalExcess;    /* Total internal fragmentation */
13891  u32 currentOut;     /* Current checkout, including internal fragmentation */
13892  u32 currentCount;   /* Current number of distinct checkouts */
13893  u32 maxOut;         /* Maximum instantaneous currentOut */
13894  u32 maxCount;       /* Maximum instantaneous currentCount */
13895  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
13896
13897  /*
13898  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
13899  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
13900  ** and so forth.
13901  */
13902  int aiFreelist[LOGMAX+1];
13903
13904  /*
13905  ** Space for tracking which blocks are checked out and the size
13906  ** of each block.  One byte per block.
13907  */
13908  u8 *aCtrl;
13909
13910} mem5 = { 0 };
13911
13912/*
13913** Access the static variable through a macro for SQLITE_OMIT_WSD
13914*/
13915#define mem5 GLOBAL(struct Mem5Global, mem5)
13916
13917/*
13918** Assuming mem5.zPool is divided up into an array of Mem5Link
13919** structures, return a pointer to the idx-th such lik.
13920*/
13921#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
13922
13923/*
13924** Unlink the chunk at mem5.aPool[i] from list it is currently
13925** on.  It should be found on mem5.aiFreelist[iLogsize].
13926*/
13927static void memsys5Unlink(int i, int iLogsize){
13928  int next, prev;
13929  assert( i>=0 && i<mem5.nBlock );
13930  assert( iLogsize>=0 && iLogsize<=LOGMAX );
13931  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13932
13933  next = MEM5LINK(i)->next;
13934  prev = MEM5LINK(i)->prev;
13935  if( prev<0 ){
13936    mem5.aiFreelist[iLogsize] = next;
13937  }else{
13938    MEM5LINK(prev)->next = next;
13939  }
13940  if( next>=0 ){
13941    MEM5LINK(next)->prev = prev;
13942  }
13943}
13944
13945/*
13946** Link the chunk at mem5.aPool[i] so that is on the iLogsize
13947** free list.
13948*/
13949static void memsys5Link(int i, int iLogsize){
13950  int x;
13951  assert( sqlite3_mutex_held(mem5.mutex) );
13952  assert( i>=0 && i<mem5.nBlock );
13953  assert( iLogsize>=0 && iLogsize<=LOGMAX );
13954  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
13955
13956  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
13957  MEM5LINK(i)->prev = -1;
13958  if( x>=0 ){
13959    assert( x<mem5.nBlock );
13960    MEM5LINK(x)->prev = i;
13961  }
13962  mem5.aiFreelist[iLogsize] = i;
13963}
13964
13965/*
13966** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13967** will already be held (obtained by code in malloc.c) if
13968** sqlite3GlobalConfig.bMemStat is true.
13969*/
13970static void memsys5Enter(void){
13971  sqlite3_mutex_enter(mem5.mutex);
13972}
13973static void memsys5Leave(void){
13974  sqlite3_mutex_leave(mem5.mutex);
13975}
13976
13977/*
13978** Return the size of an outstanding allocation, in bytes.  The
13979** size returned omits the 8-byte header overhead.  This only
13980** works for chunks that are currently checked out.
13981*/
13982static int memsys5Size(void *p){
13983  int iSize = 0;
13984  if( p ){
13985    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
13986    assert( i>=0 && i<mem5.nBlock );
13987    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
13988  }
13989  return iSize;
13990}
13991
13992/*
13993** Find the first entry on the freelist iLogsize.  Unlink that
13994** entry and return its index.
13995*/
13996static int memsys5UnlinkFirst(int iLogsize){
13997  int i;
13998  int iFirst;
13999
14000  assert( iLogsize>=0 && iLogsize<=LOGMAX );
14001  i = iFirst = mem5.aiFreelist[iLogsize];
14002  assert( iFirst>=0 );
14003  while( i>0 ){
14004    if( i<iFirst ) iFirst = i;
14005    i = MEM5LINK(i)->next;
14006  }
14007  memsys5Unlink(iFirst, iLogsize);
14008  return iFirst;
14009}
14010
14011/*
14012** Return a block of memory of at least nBytes in size.
14013** Return NULL if unable.  Return NULL if nBytes==0.
14014**
14015** The caller guarantees that nByte positive.
14016**
14017** The caller has obtained a mutex prior to invoking this
14018** routine so there is never any chance that two or more
14019** threads can be in this routine at the same time.
14020*/
14021static void *memsys5MallocUnsafe(int nByte){
14022  int i;           /* Index of a mem5.aPool[] slot */
14023  int iBin;        /* Index into mem5.aiFreelist[] */
14024  int iFullSz;     /* Size of allocation rounded up to power of 2 */
14025  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
14026
14027  /* nByte must be a positive */
14028  assert( nByte>0 );
14029
14030  /* Keep track of the maximum allocation request.  Even unfulfilled
14031  ** requests are counted */
14032  if( (u32)nByte>mem5.maxRequest ){
14033    mem5.maxRequest = nByte;
14034  }
14035
14036  /* Abort if the requested allocation size is larger than the largest
14037  ** power of two that we can represent using 32-bit signed integers.
14038  */
14039  if( nByte > 0x40000000 ){
14040    return 0;
14041  }
14042
14043  /* Round nByte up to the next valid power of two */
14044  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
14045
14046  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14047  ** block.  If not, then split a block of the next larger power of
14048  ** two in order to create a new free block of size iLogsize.
14049  */
14050  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
14051  if( iBin>LOGMAX ) return 0;
14052  i = memsys5UnlinkFirst(iBin);
14053  while( iBin>iLogsize ){
14054    int newSize;
14055
14056    iBin--;
14057    newSize = 1 << iBin;
14058    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
14059    memsys5Link(i+newSize, iBin);
14060  }
14061  mem5.aCtrl[i] = iLogsize;
14062
14063  /* Update allocator performance statistics. */
14064  mem5.nAlloc++;
14065  mem5.totalAlloc += iFullSz;
14066  mem5.totalExcess += iFullSz - nByte;
14067  mem5.currentCount++;
14068  mem5.currentOut += iFullSz;
14069  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
14070  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
14071
14072  /* Return a pointer to the allocated memory. */
14073  return (void*)&mem5.zPool[i*mem5.szAtom];
14074}
14075
14076/*
14077** Free an outstanding memory allocation.
14078*/
14079static void memsys5FreeUnsafe(void *pOld){
14080  u32 size, iLogsize;
14081  int iBlock;
14082
14083  /* Set iBlock to the index of the block pointed to by pOld in
14084  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
14085  */
14086  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
14087
14088  /* Check that the pointer pOld points to a valid, non-free block. */
14089  assert( iBlock>=0 && iBlock<mem5.nBlock );
14090  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
14091  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
14092
14093  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
14094  size = 1<<iLogsize;
14095  assert( iBlock+size-1<(u32)mem5.nBlock );
14096
14097  mem5.aCtrl[iBlock] |= CTRL_FREE;
14098  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
14099  assert( mem5.currentCount>0 );
14100  assert( mem5.currentOut>=(size*mem5.szAtom) );
14101  mem5.currentCount--;
14102  mem5.currentOut -= size*mem5.szAtom;
14103  assert( mem5.currentOut>0 || mem5.currentCount==0 );
14104  assert( mem5.currentCount>0 || mem5.currentOut==0 );
14105
14106  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14107  while( ALWAYS(iLogsize<LOGMAX) ){
14108    int iBuddy;
14109    if( (iBlock>>iLogsize) & 1 ){
14110      iBuddy = iBlock - size;
14111    }else{
14112      iBuddy = iBlock + size;
14113    }
14114    assert( iBuddy>=0 );
14115    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
14116    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14117    memsys5Unlink(iBuddy, iLogsize);
14118    iLogsize++;
14119    if( iBuddy<iBlock ){
14120      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14121      mem5.aCtrl[iBlock] = 0;
14122      iBlock = iBuddy;
14123    }else{
14124      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14125      mem5.aCtrl[iBuddy] = 0;
14126    }
14127    size *= 2;
14128  }
14129  memsys5Link(iBlock, iLogsize);
14130}
14131
14132/*
14133** Allocate nBytes of memory
14134*/
14135static void *memsys5Malloc(int nBytes){
14136  sqlite3_int64 *p = 0;
14137  if( nBytes>0 ){
14138    memsys5Enter();
14139    p = memsys5MallocUnsafe(nBytes);
14140    memsys5Leave();
14141  }
14142  return (void*)p;
14143}
14144
14145/*
14146** Free memory.
14147**
14148** The outer layer memory allocator prevents this routine from
14149** being called with pPrior==0.
14150*/
14151static void memsys5Free(void *pPrior){
14152  assert( pPrior!=0 );
14153  memsys5Enter();
14154  memsys5FreeUnsafe(pPrior);
14155  memsys5Leave();
14156}
14157
14158/*
14159** Change the size of an existing memory allocation.
14160**
14161** The outer layer memory allocator prevents this routine from
14162** being called with pPrior==0.
14163**
14164** nBytes is always a value obtained from a prior call to
14165** memsys5Round().  Hence nBytes is always a non-negative power
14166** of two.  If nBytes==0 that means that an oversize allocation
14167** (an allocation larger than 0x40000000) was requested and this
14168** routine should return 0 without freeing pPrior.
14169*/
14170static void *memsys5Realloc(void *pPrior, int nBytes){
14171  int nOld;
14172  void *p;
14173  assert( pPrior!=0 );
14174  assert( (nBytes&(nBytes-1))==0 );
14175  assert( nBytes>=0 );
14176  if( nBytes==0 ){
14177    return 0;
14178  }
14179  nOld = memsys5Size(pPrior);
14180  if( nBytes<=nOld ){
14181    return pPrior;
14182  }
14183  memsys5Enter();
14184  p = memsys5MallocUnsafe(nBytes);
14185  if( p ){
14186    memcpy(p, pPrior, nOld);
14187    memsys5FreeUnsafe(pPrior);
14188  }
14189  memsys5Leave();
14190  return p;
14191}
14192
14193/*
14194** Round up a request size to the next valid allocation size.  If
14195** the allocation is too large to be handled by this allocation system,
14196** return 0.
14197**
14198** All allocations must be a power of two and must be expressed by a
14199** 32-bit signed integer.  Hence the largest allocation is 0x40000000
14200** or 1073741824 bytes.
14201*/
14202static int memsys5Roundup(int n){
14203  int iFullSz;
14204  if( n > 0x40000000 ) return 0;
14205  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
14206  return iFullSz;
14207}
14208
14209/*
14210** Return the ceiling of the logarithm base 2 of iValue.
14211**
14212** Examples:   memsys5Log(1) -> 0
14213**             memsys5Log(2) -> 1
14214**             memsys5Log(4) -> 2
14215**             memsys5Log(5) -> 3
14216**             memsys5Log(8) -> 3
14217**             memsys5Log(9) -> 4
14218*/
14219static int memsys5Log(int iValue){
14220  int iLog;
14221  for(iLog=0; (1<<iLog)<iValue; iLog++);
14222  return iLog;
14223}
14224
14225/*
14226** Initialize the memory allocator.
14227**
14228** This routine is not threadsafe.  The caller must be holding a mutex
14229** to prevent multiple threads from entering at the same time.
14230*/
14231static int memsys5Init(void *NotUsed){
14232  int ii;            /* Loop counter */
14233  int nByte;         /* Number of bytes of memory available to this allocator */
14234  u8 *zByte;         /* Memory usable by this allocator */
14235  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
14236  int iOffset;       /* An offset into mem5.aCtrl[] */
14237
14238  UNUSED_PARAMETER(NotUsed);
14239
14240  /* For the purposes of this routine, disable the mutex */
14241  mem5.mutex = 0;
14242
14243  /* The size of a Mem5Link object must be a power of two.  Verify that
14244  ** this is case.
14245  */
14246  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
14247
14248  nByte = sqlite3GlobalConfig.nHeap;
14249  zByte = (u8*)sqlite3GlobalConfig.pHeap;
14250  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
14251
14252  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
14253  mem5.szAtom = (1<<nMinLog);
14254  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
14255    mem5.szAtom = mem5.szAtom << 1;
14256  }
14257
14258  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
14259  mem5.zPool = zByte;
14260  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
14261
14262  for(ii=0; ii<=LOGMAX; ii++){
14263    mem5.aiFreelist[ii] = -1;
14264  }
14265
14266  iOffset = 0;
14267  for(ii=LOGMAX; ii>=0; ii--){
14268    int nAlloc = (1<<ii);
14269    if( (iOffset+nAlloc)<=mem5.nBlock ){
14270      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
14271      memsys5Link(iOffset, ii);
14272      iOffset += nAlloc;
14273    }
14274    assert((iOffset+nAlloc)>mem5.nBlock);
14275  }
14276
14277  /* If a mutex is required for normal operation, allocate one */
14278  if( sqlite3GlobalConfig.bMemstat==0 ){
14279    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14280  }
14281
14282  return SQLITE_OK;
14283}
14284
14285/*
14286** Deinitialize this module.
14287*/
14288static void memsys5Shutdown(void *NotUsed){
14289  UNUSED_PARAMETER(NotUsed);
14290  mem5.mutex = 0;
14291  return;
14292}
14293
14294#ifdef SQLITE_TEST
14295/*
14296** Open the file indicated and write a log of all unfreed memory
14297** allocations into that log.
14298*/
14299SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
14300  FILE *out;
14301  int i, j, n;
14302  int nMinLog;
14303
14304  if( zFilename==0 || zFilename[0]==0 ){
14305    out = stdout;
14306  }else{
14307    out = fopen(zFilename, "w");
14308    if( out==0 ){
14309      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14310                      zFilename);
14311      return;
14312    }
14313  }
14314  memsys5Enter();
14315  nMinLog = memsys5Log(mem5.szAtom);
14316  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
14317    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
14318    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
14319  }
14320  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
14321  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
14322  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
14323  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
14324  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
14325  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
14326  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
14327  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
14328  memsys5Leave();
14329  if( out==stdout ){
14330    fflush(stdout);
14331  }else{
14332    fclose(out);
14333  }
14334}
14335#endif
14336
14337/*
14338** This routine is the only routine in this file with external
14339** linkage. It returns a pointer to a static sqlite3_mem_methods
14340** struct populated with the memsys5 methods.
14341*/
14342SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
14343  static const sqlite3_mem_methods memsys5Methods = {
14344     memsys5Malloc,
14345     memsys5Free,
14346     memsys5Realloc,
14347     memsys5Size,
14348     memsys5Roundup,
14349     memsys5Init,
14350     memsys5Shutdown,
14351     0
14352  };
14353  return &memsys5Methods;
14354}
14355
14356#endif /* SQLITE_ENABLE_MEMSYS5 */
14357
14358/************** End of mem5.c ************************************************/
14359/************** Begin file mutex.c *******************************************/
14360/*
14361** 2007 August 14
14362**
14363** The author disclaims copyright to this source code.  In place of
14364** a legal notice, here is a blessing:
14365**
14366**    May you do good and not evil.
14367**    May you find forgiveness for yourself and forgive others.
14368**    May you share freely, never taking more than you give.
14369**
14370*************************************************************************
14371** This file contains the C functions that implement mutexes.
14372**
14373** This file contains code that is common across all mutex implementations.
14374*/
14375
14376#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
14377/*
14378** For debugging purposes, record when the mutex subsystem is initialized
14379** and uninitialized so that we can assert() if there is an attempt to
14380** allocate a mutex while the system is uninitialized.
14381*/
14382static SQLITE_WSD int mutexIsInit = 0;
14383#endif /* SQLITE_DEBUG */
14384
14385
14386#ifndef SQLITE_MUTEX_OMIT
14387/*
14388** Initialize the mutex system.
14389*/
14390SQLITE_PRIVATE int sqlite3MutexInit(void){
14391  int rc = SQLITE_OK;
14392  if( sqlite3GlobalConfig.bCoreMutex ){
14393    if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
14394      /* If the xMutexAlloc method has not been set, then the user did not
14395      ** install a mutex implementation via sqlite3_config() prior to
14396      ** sqlite3_initialize() being called. This block copies pointers to
14397      ** the default implementation into the sqlite3GlobalConfig structure.
14398      */
14399      sqlite3_mutex_methods *pFrom = sqlite3DefaultMutex();
14400      sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
14401
14402      memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
14403      memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
14404             sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
14405      pTo->xMutexAlloc = pFrom->xMutexAlloc;
14406    }
14407    rc = sqlite3GlobalConfig.mutex.xMutexInit();
14408  }
14409
14410#ifdef SQLITE_DEBUG
14411  GLOBAL(int, mutexIsInit) = 1;
14412#endif
14413
14414  return rc;
14415}
14416
14417/*
14418** Shutdown the mutex system. This call frees resources allocated by
14419** sqlite3MutexInit().
14420*/
14421SQLITE_PRIVATE int sqlite3MutexEnd(void){
14422  int rc = SQLITE_OK;
14423  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
14424    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
14425  }
14426
14427#ifdef SQLITE_DEBUG
14428  GLOBAL(int, mutexIsInit) = 0;
14429#endif
14430
14431  return rc;
14432}
14433
14434/*
14435** Retrieve a pointer to a static mutex or allocate a new dynamic one.
14436*/
14437SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
14438#ifndef SQLITE_OMIT_AUTOINIT
14439  if( sqlite3_initialize() ) return 0;
14440#endif
14441  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14442}
14443
14444SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
14445  if( !sqlite3GlobalConfig.bCoreMutex ){
14446    return 0;
14447  }
14448  assert( GLOBAL(int, mutexIsInit) );
14449  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14450}
14451
14452/*
14453** Free a dynamic mutex.
14454*/
14455SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
14456  if( p ){
14457    sqlite3GlobalConfig.mutex.xMutexFree(p);
14458  }
14459}
14460
14461/*
14462** Obtain the mutex p. If some other thread already has the mutex, block
14463** until it can be obtained.
14464*/
14465SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
14466  if( p ){
14467    sqlite3GlobalConfig.mutex.xMutexEnter(p);
14468  }
14469}
14470
14471/*
14472** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
14473** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
14474*/
14475SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
14476  int rc = SQLITE_OK;
14477  if( p ){
14478    return sqlite3GlobalConfig.mutex.xMutexTry(p);
14479  }
14480  return rc;
14481}
14482
14483/*
14484** The sqlite3_mutex_leave() routine exits a mutex that was previously
14485** entered by the same thread.  The behavior is undefined if the mutex
14486** is not currently entered. If a NULL pointer is passed as an argument
14487** this function is a no-op.
14488*/
14489SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
14490  if( p ){
14491    sqlite3GlobalConfig.mutex.xMutexLeave(p);
14492  }
14493}
14494
14495#ifndef NDEBUG
14496/*
14497** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14498** intended for use inside assert() statements.
14499*/
14500SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
14501  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
14502}
14503SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
14504  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
14505}
14506#endif
14507
14508#endif /* SQLITE_MUTEX_OMIT */
14509
14510/************** End of mutex.c ***********************************************/
14511/************** Begin file mutex_noop.c **************************************/
14512/*
14513** 2008 October 07
14514**
14515** The author disclaims copyright to this source code.  In place of
14516** a legal notice, here is a blessing:
14517**
14518**    May you do good and not evil.
14519**    May you find forgiveness for yourself and forgive others.
14520**    May you share freely, never taking more than you give.
14521**
14522*************************************************************************
14523** This file contains the C functions that implement mutexes.
14524**
14525** This implementation in this file does not provide any mutual
14526** exclusion and is thus suitable for use only in applications
14527** that use SQLite in a single thread.  The routines defined
14528** here are place-holders.  Applications can substitute working
14529** mutex routines at start-time using the
14530**
14531**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
14532**
14533** interface.
14534**
14535** If compiled with SQLITE_DEBUG, then additional logic is inserted
14536** that does error checking on mutexes to make sure they are being
14537** called correctly.
14538*/
14539
14540
14541#if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
14542/*
14543** Stub routines for all mutex methods.
14544**
14545** This routines provide no mutual exclusion or error checking.
14546*/
14547static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
14548static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
14549static int noopMutexInit(void){ return SQLITE_OK; }
14550static int noopMutexEnd(void){ return SQLITE_OK; }
14551static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
14552static void noopMutexFree(sqlite3_mutex *p){ return; }
14553static void noopMutexEnter(sqlite3_mutex *p){ return; }
14554static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
14555static void noopMutexLeave(sqlite3_mutex *p){ return; }
14556
14557SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14558  static sqlite3_mutex_methods sMutex = {
14559    noopMutexInit,
14560    noopMutexEnd,
14561    noopMutexAlloc,
14562    noopMutexFree,
14563    noopMutexEnter,
14564    noopMutexTry,
14565    noopMutexLeave,
14566
14567    noopMutexHeld,
14568    noopMutexNotheld
14569  };
14570
14571  return &sMutex;
14572}
14573#endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */
14574
14575#if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
14576/*
14577** In this implementation, error checking is provided for testing
14578** and debugging purposes.  The mutexes still do not provide any
14579** mutual exclusion.
14580*/
14581
14582/*
14583** The mutex object
14584*/
14585struct sqlite3_mutex {
14586  int id;     /* The mutex type */
14587  int cnt;    /* Number of entries without a matching leave */
14588};
14589
14590/*
14591** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14592** intended for use inside assert() statements.
14593*/
14594static int debugMutexHeld(sqlite3_mutex *p){
14595  return p==0 || p->cnt>0;
14596}
14597static int debugMutexNotheld(sqlite3_mutex *p){
14598  return p==0 || p->cnt==0;
14599}
14600
14601/*
14602** Initialize and deinitialize the mutex subsystem.
14603*/
14604static int debugMutexInit(void){ return SQLITE_OK; }
14605static int debugMutexEnd(void){ return SQLITE_OK; }
14606
14607/*
14608** The sqlite3_mutex_alloc() routine allocates a new
14609** mutex and returns a pointer to it.  If it returns NULL
14610** that means that a mutex could not be allocated.
14611*/
14612static sqlite3_mutex *debugMutexAlloc(int id){
14613  static sqlite3_mutex aStatic[6];
14614  sqlite3_mutex *pNew = 0;
14615  switch( id ){
14616    case SQLITE_MUTEX_FAST:
14617    case SQLITE_MUTEX_RECURSIVE: {
14618      pNew = sqlite3Malloc(sizeof(*pNew));
14619      if( pNew ){
14620        pNew->id = id;
14621        pNew->cnt = 0;
14622      }
14623      break;
14624    }
14625    default: {
14626      assert( id-2 >= 0 );
14627      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
14628      pNew = &aStatic[id-2];
14629      pNew->id = id;
14630      break;
14631    }
14632  }
14633  return pNew;
14634}
14635
14636/*
14637** This routine deallocates a previously allocated mutex.
14638*/
14639static void debugMutexFree(sqlite3_mutex *p){
14640  assert( p->cnt==0 );
14641  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14642  sqlite3_free(p);
14643}
14644
14645/*
14646** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14647** to enter a mutex.  If another thread is already within the mutex,
14648** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14649** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14650** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14651** be entered multiple times by the same thread.  In such cases the,
14652** mutex must be exited an equal number of times before another thread
14653** can enter.  If the same thread tries to enter any other kind of mutex
14654** more than once, the behavior is undefined.
14655*/
14656static void debugMutexEnter(sqlite3_mutex *p){
14657  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14658  p->cnt++;
14659}
14660static int debugMutexTry(sqlite3_mutex *p){
14661  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14662  p->cnt++;
14663  return SQLITE_OK;
14664}
14665
14666/*
14667** The sqlite3_mutex_leave() routine exits a mutex that was
14668** previously entered by the same thread.  The behavior
14669** is undefined if the mutex is not currently entered or
14670** is not currently allocated.  SQLite will never do either.
14671*/
14672static void debugMutexLeave(sqlite3_mutex *p){
14673  assert( debugMutexHeld(p) );
14674  p->cnt--;
14675  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
14676}
14677
14678SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14679  static sqlite3_mutex_methods sMutex = {
14680    debugMutexInit,
14681    debugMutexEnd,
14682    debugMutexAlloc,
14683    debugMutexFree,
14684    debugMutexEnter,
14685    debugMutexTry,
14686    debugMutexLeave,
14687
14688    debugMutexHeld,
14689    debugMutexNotheld
14690  };
14691
14692  return &sMutex;
14693}
14694#endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */
14695
14696/************** End of mutex_noop.c ******************************************/
14697/************** Begin file mutex_os2.c ***************************************/
14698/*
14699** 2007 August 28
14700**
14701** The author disclaims copyright to this source code.  In place of
14702** a legal notice, here is a blessing:
14703**
14704**    May you do good and not evil.
14705**    May you find forgiveness for yourself and forgive others.
14706**    May you share freely, never taking more than you give.
14707**
14708*************************************************************************
14709** This file contains the C functions that implement mutexes for OS/2
14710*/
14711
14712/*
14713** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
14714** See the mutex.h file for details.
14715*/
14716#ifdef SQLITE_MUTEX_OS2
14717
14718/********************** OS/2 Mutex Implementation **********************
14719**
14720** This implementation of mutexes is built using the OS/2 API.
14721*/
14722
14723/*
14724** The mutex object
14725** Each recursive mutex is an instance of the following structure.
14726*/
14727struct sqlite3_mutex {
14728  HMTX mutex;       /* Mutex controlling the lock */
14729  int  id;          /* Mutex type */
14730  int  nRef;        /* Number of references */
14731  TID  owner;       /* Thread holding this mutex */
14732};
14733
14734#define OS2_MUTEX_INITIALIZER   0,0,0,0
14735
14736/*
14737** Initialize and deinitialize the mutex subsystem.
14738*/
14739static int os2MutexInit(void){ return SQLITE_OK; }
14740static int os2MutexEnd(void){ return SQLITE_OK; }
14741
14742/*
14743** The sqlite3_mutex_alloc() routine allocates a new
14744** mutex and returns a pointer to it.  If it returns NULL
14745** that means that a mutex could not be allocated.
14746** SQLite will unwind its stack and return an error.  The argument
14747** to sqlite3_mutex_alloc() is one of these integer constants:
14748**
14749** <ul>
14750** <li>  SQLITE_MUTEX_FAST               0
14751** <li>  SQLITE_MUTEX_RECURSIVE          1
14752** <li>  SQLITE_MUTEX_STATIC_MASTER      2
14753** <li>  SQLITE_MUTEX_STATIC_MEM         3
14754** <li>  SQLITE_MUTEX_STATIC_PRNG        4
14755** </ul>
14756**
14757** The first two constants cause sqlite3_mutex_alloc() to create
14758** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
14759** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
14760** The mutex implementation does not need to make a distinction
14761** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
14762** not want to.  But SQLite will only request a recursive mutex in
14763** cases where it really needs one.  If a faster non-recursive mutex
14764** implementation is available on the host platform, the mutex subsystem
14765** might return such a mutex in response to SQLITE_MUTEX_FAST.
14766**
14767** The other allowed parameters to sqlite3_mutex_alloc() each return
14768** a pointer to a static preexisting mutex.  Three static mutexes are
14769** used by the current version of SQLite.  Future versions of SQLite
14770** may add additional static mutexes.  Static mutexes are for internal
14771** use by SQLite only.  Applications that use SQLite mutexes should
14772** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
14773** SQLITE_MUTEX_RECURSIVE.
14774**
14775** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
14776** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
14777** returns a different mutex on every call.  But for the static
14778** mutex types, the same mutex is returned on every call that has
14779** the same type number.
14780*/
14781static sqlite3_mutex *os2MutexAlloc(int iType){
14782  sqlite3_mutex *p = NULL;
14783  switch( iType ){
14784    case SQLITE_MUTEX_FAST:
14785    case SQLITE_MUTEX_RECURSIVE: {
14786      p = sqlite3MallocZero( sizeof(*p) );
14787      if( p ){
14788        p->id = iType;
14789        if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
14790          sqlite3_free( p );
14791          p = NULL;
14792        }
14793      }
14794      break;
14795    }
14796    default: {
14797      static volatile int isInit = 0;
14798      static sqlite3_mutex staticMutexes[] = {
14799        { OS2_MUTEX_INITIALIZER, },
14800        { OS2_MUTEX_INITIALIZER, },
14801        { OS2_MUTEX_INITIALIZER, },
14802        { OS2_MUTEX_INITIALIZER, },
14803        { OS2_MUTEX_INITIALIZER, },
14804        { OS2_MUTEX_INITIALIZER, },
14805      };
14806      if ( !isInit ){
14807        APIRET rc;
14808        PTIB ptib;
14809        PPIB ppib;
14810        HMTX mutex;
14811        char name[32];
14812        DosGetInfoBlocks( &ptib, &ppib );
14813        sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
14814                          ppib->pib_ulpid );
14815        while( !isInit ){
14816          mutex = 0;
14817          rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
14818          if( rc == NO_ERROR ){
14819            unsigned int i;
14820            if( !isInit ){
14821              for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
14822                DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
14823              }
14824              isInit = 1;
14825            }
14826            DosCloseMutexSem( mutex );
14827          }else if( rc == ERROR_DUPLICATE_NAME ){
14828            DosSleep( 1 );
14829          }else{
14830            return p;
14831          }
14832        }
14833      }
14834      assert( iType-2 >= 0 );
14835      assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
14836      p = &staticMutexes[iType-2];
14837      p->id = iType;
14838      break;
14839    }
14840  }
14841  return p;
14842}
14843
14844
14845/*
14846** This routine deallocates a previously allocated mutex.
14847** SQLite is careful to deallocate every mutex that it allocates.
14848*/
14849static void os2MutexFree(sqlite3_mutex *p){
14850  if( p==0 ) return;
14851  assert( p->nRef==0 );
14852  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
14853  DosCloseMutexSem( p->mutex );
14854  sqlite3_free( p );
14855}
14856
14857#ifdef SQLITE_DEBUG
14858/*
14859** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14860** intended for use inside assert() statements.
14861*/
14862static int os2MutexHeld(sqlite3_mutex *p){
14863  TID tid;
14864  PID pid;
14865  ULONG ulCount;
14866  PTIB ptib;
14867  if( p!=0 ) {
14868    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
14869  } else {
14870    DosGetInfoBlocks(&ptib, NULL);
14871    tid = ptib->tib_ptib2->tib2_ultid;
14872  }
14873  return p==0 || (p->nRef!=0 && p->owner==tid);
14874}
14875static int os2MutexNotheld(sqlite3_mutex *p){
14876  TID tid;
14877  PID pid;
14878  ULONG ulCount;
14879  PTIB ptib;
14880  if( p!= 0 ) {
14881    DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
14882  } else {
14883    DosGetInfoBlocks(&ptib, NULL);
14884    tid = ptib->tib_ptib2->tib2_ultid;
14885  }
14886  return p==0 || p->nRef==0 || p->owner!=tid;
14887}
14888#endif
14889
14890/*
14891** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
14892** to enter a mutex.  If another thread is already within the mutex,
14893** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
14894** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
14895** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
14896** be entered multiple times by the same thread.  In such cases the,
14897** mutex must be exited an equal number of times before another thread
14898** can enter.  If the same thread tries to enter any other kind of mutex
14899** more than once, the behavior is undefined.
14900*/
14901static void os2MutexEnter(sqlite3_mutex *p){
14902  TID tid;
14903  PID holder1;
14904  ULONG holder2;
14905  if( p==0 ) return;
14906  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
14907  DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
14908  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14909  p->owner = tid;
14910  p->nRef++;
14911}
14912static int os2MutexTry(sqlite3_mutex *p){
14913  int rc;
14914  TID tid;
14915  PID holder1;
14916  ULONG holder2;
14917  if( p==0 ) return SQLITE_OK;
14918  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
14919  if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
14920    DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14921    p->owner = tid;
14922    p->nRef++;
14923    rc = SQLITE_OK;
14924  } else {
14925    rc = SQLITE_BUSY;
14926  }
14927
14928  return rc;
14929}
14930
14931/*
14932** The sqlite3_mutex_leave() routine exits a mutex that was
14933** previously entered by the same thread.  The behavior
14934** is undefined if the mutex is not currently entered or
14935** is not currently allocated.  SQLite will never do either.
14936*/
14937static void os2MutexLeave(sqlite3_mutex *p){
14938  TID tid;
14939  PID holder1;
14940  ULONG holder2;
14941  if( p==0 ) return;
14942  assert( p->nRef>0 );
14943  DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
14944  assert( p->owner==tid );
14945  p->nRef--;
14946  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
14947  DosReleaseMutexSem(p->mutex);
14948}
14949
14950SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
14951  static sqlite3_mutex_methods sMutex = {
14952    os2MutexInit,
14953    os2MutexEnd,
14954    os2MutexAlloc,
14955    os2MutexFree,
14956    os2MutexEnter,
14957    os2MutexTry,
14958    os2MutexLeave,
14959#ifdef SQLITE_DEBUG
14960    os2MutexHeld,
14961    os2MutexNotheld
14962#endif
14963  };
14964
14965  return &sMutex;
14966}
14967#endif /* SQLITE_MUTEX_OS2 */
14968
14969/************** End of mutex_os2.c *******************************************/
14970/************** Begin file mutex_unix.c **************************************/
14971/*
14972** 2007 August 28
14973**
14974** The author disclaims copyright to this source code.  In place of
14975** a legal notice, here is a blessing:
14976**
14977**    May you do good and not evil.
14978**    May you find forgiveness for yourself and forgive others.
14979**    May you share freely, never taking more than you give.
14980**
14981*************************************************************************
14982** This file contains the C functions that implement mutexes for pthreads
14983*/
14984
14985/*
14986** The code in this file is only used if we are compiling threadsafe
14987** under unix with pthreads.
14988**
14989** Note that this implementation requires a version of pthreads that
14990** supports recursive mutexes.
14991*/
14992#ifdef SQLITE_MUTEX_PTHREADS
14993
14994#include <pthread.h>
14995
14996
14997/*
14998** Each recursive mutex is an instance of the following structure.
14999*/
15000struct sqlite3_mutex {
15001  pthread_mutex_t mutex;     /* Mutex controlling the lock */
15002  int id;                    /* Mutex type */
15003  int nRef;                  /* Number of entrances */
15004  pthread_t owner;           /* Thread that is within this mutex */
15005#ifdef SQLITE_DEBUG
15006  int trace;                 /* True to trace changes */
15007#endif
15008};
15009#ifdef SQLITE_DEBUG
15010#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15011#else
15012#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
15013#endif
15014
15015/*
15016** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15017** intended for use only inside assert() statements.  On some platforms,
15018** there might be race conditions that can cause these routines to
15019** deliver incorrect results.  In particular, if pthread_equal() is
15020** not an atomic operation, then these routines might delivery
15021** incorrect results.  On most platforms, pthread_equal() is a
15022** comparison of two integers and is therefore atomic.  But we are
15023** told that HPUX is not such a platform.  If so, then these routines
15024** will not always work correctly on HPUX.
15025**
15026** On those platforms where pthread_equal() is not atomic, SQLite
15027** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15028** make sure no assert() statements are evaluated and hence these
15029** routines are never called.
15030*/
15031#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
15032static int pthreadMutexHeld(sqlite3_mutex *p){
15033  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15034}
15035static int pthreadMutexNotheld(sqlite3_mutex *p){
15036  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15037}
15038#endif
15039
15040/*
15041** Initialize and deinitialize the mutex subsystem.
15042*/
15043static int pthreadMutexInit(void){ return SQLITE_OK; }
15044static int pthreadMutexEnd(void){ return SQLITE_OK; }
15045
15046/*
15047** The sqlite3_mutex_alloc() routine allocates a new
15048** mutex and returns a pointer to it.  If it returns NULL
15049** that means that a mutex could not be allocated.  SQLite
15050** will unwind its stack and return an error.  The argument
15051** to sqlite3_mutex_alloc() is one of these integer constants:
15052**
15053** <ul>
15054** <li>  SQLITE_MUTEX_FAST
15055** <li>  SQLITE_MUTEX_RECURSIVE
15056** <li>  SQLITE_MUTEX_STATIC_MASTER
15057** <li>  SQLITE_MUTEX_STATIC_MEM
15058** <li>  SQLITE_MUTEX_STATIC_MEM2
15059** <li>  SQLITE_MUTEX_STATIC_PRNG
15060** <li>  SQLITE_MUTEX_STATIC_LRU
15061** <li>  SQLITE_MUTEX_STATIC_LRU2
15062** </ul>
15063**
15064** The first two constants cause sqlite3_mutex_alloc() to create
15065** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15066** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15067** The mutex implementation does not need to make a distinction
15068** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15069** not want to.  But SQLite will only request a recursive mutex in
15070** cases where it really needs one.  If a faster non-recursive mutex
15071** implementation is available on the host platform, the mutex subsystem
15072** might return such a mutex in response to SQLITE_MUTEX_FAST.
15073**
15074** The other allowed parameters to sqlite3_mutex_alloc() each return
15075** a pointer to a static preexisting mutex.  Six static mutexes are
15076** used by the current version of SQLite.  Future versions of SQLite
15077** may add additional static mutexes.  Static mutexes are for internal
15078** use by SQLite only.  Applications that use SQLite mutexes should
15079** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15080** SQLITE_MUTEX_RECURSIVE.
15081**
15082** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15083** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15084** returns a different mutex on every call.  But for the static
15085** mutex types, the same mutex is returned on every call that has
15086** the same type number.
15087*/
15088static sqlite3_mutex *pthreadMutexAlloc(int iType){
15089  static sqlite3_mutex staticMutexes[] = {
15090    SQLITE3_MUTEX_INITIALIZER,
15091    SQLITE3_MUTEX_INITIALIZER,
15092    SQLITE3_MUTEX_INITIALIZER,
15093    SQLITE3_MUTEX_INITIALIZER,
15094    SQLITE3_MUTEX_INITIALIZER,
15095    SQLITE3_MUTEX_INITIALIZER
15096  };
15097  sqlite3_mutex *p;
15098  switch( iType ){
15099    case SQLITE_MUTEX_RECURSIVE: {
15100      p = sqlite3MallocZero( sizeof(*p) );
15101      if( p ){
15102#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15103        /* If recursive mutexes are not available, we will have to
15104        ** build our own.  See below. */
15105        pthread_mutex_init(&p->mutex, 0);
15106#else
15107        /* Use a recursive mutex if it is available */
15108        pthread_mutexattr_t recursiveAttr;
15109        pthread_mutexattr_init(&recursiveAttr);
15110        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15111        pthread_mutex_init(&p->mutex, &recursiveAttr);
15112        pthread_mutexattr_destroy(&recursiveAttr);
15113#endif
15114        p->id = iType;
15115      }
15116      break;
15117    }
15118    case SQLITE_MUTEX_FAST: {
15119      p = sqlite3MallocZero( sizeof(*p) );
15120      if( p ){
15121        p->id = iType;
15122        pthread_mutex_init(&p->mutex, 0);
15123      }
15124      break;
15125    }
15126    default: {
15127      assert( iType-2 >= 0 );
15128      assert( iType-2 < ArraySize(staticMutexes) );
15129      p = &staticMutexes[iType-2];
15130      p->id = iType;
15131      break;
15132    }
15133  }
15134  return p;
15135}
15136
15137
15138/*
15139** This routine deallocates a previously
15140** allocated mutex.  SQLite is careful to deallocate every
15141** mutex that it allocates.
15142*/
15143static void pthreadMutexFree(sqlite3_mutex *p){
15144  assert( p->nRef==0 );
15145  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15146  pthread_mutex_destroy(&p->mutex);
15147  sqlite3_free(p);
15148}
15149
15150/*
15151** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15152** to enter a mutex.  If another thread is already within the mutex,
15153** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15154** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15155** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15156** be entered multiple times by the same thread.  In such cases the,
15157** mutex must be exited an equal number of times before another thread
15158** can enter.  If the same thread tries to enter any other kind of mutex
15159** more than once, the behavior is undefined.
15160*/
15161static void pthreadMutexEnter(sqlite3_mutex *p){
15162  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15163
15164#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15165  /* If recursive mutexes are not available, then we have to grow
15166  ** our own.  This implementation assumes that pthread_equal()
15167  ** is atomic - that it cannot be deceived into thinking self
15168  ** and p->owner are equal if p->owner changes between two values
15169  ** that are not equal to self while the comparison is taking place.
15170  ** This implementation also assumes a coherent cache - that
15171  ** separate processes cannot read different values from the same
15172  ** address at the same time.  If either of these two conditions
15173  ** are not met, then the mutexes will fail and problems will result.
15174  */
15175  {
15176    pthread_t self = pthread_self();
15177    if( p->nRef>0 && pthread_equal(p->owner, self) ){
15178      p->nRef++;
15179    }else{
15180      pthread_mutex_lock(&p->mutex);
15181      assert( p->nRef==0 );
15182      p->owner = self;
15183      p->nRef = 1;
15184    }
15185  }
15186#else
15187  /* Use the built-in recursive mutexes if they are available.
15188  */
15189  pthread_mutex_lock(&p->mutex);
15190  p->owner = pthread_self();
15191  p->nRef++;
15192#endif
15193
15194#ifdef SQLITE_DEBUG
15195  if( p->trace ){
15196    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15197  }
15198#endif
15199}
15200static int pthreadMutexTry(sqlite3_mutex *p){
15201  int rc;
15202  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15203
15204#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15205  /* If recursive mutexes are not available, then we have to grow
15206  ** our own.  This implementation assumes that pthread_equal()
15207  ** is atomic - that it cannot be deceived into thinking self
15208  ** and p->owner are equal if p->owner changes between two values
15209  ** that are not equal to self while the comparison is taking place.
15210  ** This implementation also assumes a coherent cache - that
15211  ** separate processes cannot read different values from the same
15212  ** address at the same time.  If either of these two conditions
15213  ** are not met, then the mutexes will fail and problems will result.
15214  */
15215  {
15216    pthread_t self = pthread_self();
15217    if( p->nRef>0 && pthread_equal(p->owner, self) ){
15218      p->nRef++;
15219      rc = SQLITE_OK;
15220    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
15221      assert( p->nRef==0 );
15222      p->owner = self;
15223      p->nRef = 1;
15224      rc = SQLITE_OK;
15225    }else{
15226      rc = SQLITE_BUSY;
15227    }
15228  }
15229#else
15230  /* Use the built-in recursive mutexes if they are available.
15231  */
15232  if( pthread_mutex_trylock(&p->mutex)==0 ){
15233    p->owner = pthread_self();
15234    p->nRef++;
15235    rc = SQLITE_OK;
15236  }else{
15237    rc = SQLITE_BUSY;
15238  }
15239#endif
15240
15241#ifdef SQLITE_DEBUG
15242  if( rc==SQLITE_OK && p->trace ){
15243    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15244  }
15245#endif
15246  return rc;
15247}
15248
15249/*
15250** The sqlite3_mutex_leave() routine exits a mutex that was
15251** previously entered by the same thread.  The behavior
15252** is undefined if the mutex is not currently entered or
15253** is not currently allocated.  SQLite will never do either.
15254*/
15255static void pthreadMutexLeave(sqlite3_mutex *p){
15256  assert( pthreadMutexHeld(p) );
15257  p->nRef--;
15258  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15259
15260#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15261  if( p->nRef==0 ){
15262    pthread_mutex_unlock(&p->mutex);
15263  }
15264#else
15265  pthread_mutex_unlock(&p->mutex);
15266#endif
15267
15268#ifdef SQLITE_DEBUG
15269  if( p->trace ){
15270    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15271  }
15272#endif
15273}
15274
15275SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15276  static sqlite3_mutex_methods sMutex = {
15277    pthreadMutexInit,
15278    pthreadMutexEnd,
15279    pthreadMutexAlloc,
15280    pthreadMutexFree,
15281    pthreadMutexEnter,
15282    pthreadMutexTry,
15283    pthreadMutexLeave,
15284#ifdef SQLITE_DEBUG
15285    pthreadMutexHeld,
15286    pthreadMutexNotheld
15287#else
15288    0,
15289    0
15290#endif
15291  };
15292
15293  return &sMutex;
15294}
15295
15296#endif /* SQLITE_MUTEX_PTHREAD */
15297
15298/************** End of mutex_unix.c ******************************************/
15299/************** Begin file mutex_w32.c ***************************************/
15300/*
15301** 2007 August 14
15302**
15303** The author disclaims copyright to this source code.  In place of
15304** a legal notice, here is a blessing:
15305**
15306**    May you do good and not evil.
15307**    May you find forgiveness for yourself and forgive others.
15308**    May you share freely, never taking more than you give.
15309**
15310*************************************************************************
15311** This file contains the C functions that implement mutexes for win32
15312*/
15313
15314/*
15315** The code in this file is only used if we are compiling multithreaded
15316** on a win32 system.
15317*/
15318#ifdef SQLITE_MUTEX_W32
15319
15320/*
15321** Each recursive mutex is an instance of the following structure.
15322*/
15323struct sqlite3_mutex {
15324  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
15325  int id;                    /* Mutex type */
15326  int nRef;                  /* Number of enterances */
15327  DWORD owner;               /* Thread holding this mutex */
15328};
15329
15330/*
15331** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
15332** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
15333**
15334** Here is an interesting observation:  Win95, Win98, and WinME lack
15335** the LockFileEx() API.  But we can still statically link against that
15336** API as long as we don't call it win running Win95/98/ME.  A call to
15337** this routine is used to determine if the host is Win95/98/ME or
15338** WinNT/2K/XP so that we will know whether or not we can safely call
15339** the LockFileEx() API.
15340**
15341** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
15342** which is only available if your application was compiled with
15343** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
15344** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
15345** this out as well.
15346*/
15347#if 0
15348#if SQLITE_OS_WINCE
15349# define mutexIsNT()  (1)
15350#else
15351  static int mutexIsNT(void){
15352    static int osType = 0;
15353    if( osType==0 ){
15354      OSVERSIONINFO sInfo;
15355      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
15356      GetVersionEx(&sInfo);
15357      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
15358    }
15359    return osType==2;
15360  }
15361#endif /* SQLITE_OS_WINCE */
15362#endif
15363
15364#ifdef SQLITE_DEBUG
15365/*
15366** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15367** intended for use only inside assert() statements.
15368*/
15369static int winMutexHeld(sqlite3_mutex *p){
15370  return p->nRef!=0 && p->owner==GetCurrentThreadId();
15371}
15372static int winMutexNotheld(sqlite3_mutex *p){
15373  return p->nRef==0 || p->owner!=GetCurrentThreadId();
15374}
15375#endif
15376
15377
15378/*
15379** Initialize and deinitialize the mutex subsystem.
15380*/
15381static sqlite3_mutex winMutex_staticMutexes[6];
15382static int winMutex_isInit = 0;
15383/* As winMutexInit() and winMutexEnd() are called as part
15384** of the sqlite3_initialize and sqlite3_shutdown()
15385** processing, the "interlocked" magic is probably not
15386** strictly necessary.
15387*/
15388static long winMutex_lock = 0;
15389
15390static int winMutexInit(void){
15391  /* The first to increment to 1 does actual initialization */
15392  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
15393    int i;
15394    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15395      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
15396    }
15397    winMutex_isInit = 1;
15398  }else{
15399    /* Someone else is in the process of initing the static mutexes */
15400    while( !winMutex_isInit ){
15401      Sleep(1);
15402    }
15403  }
15404  return SQLITE_OK;
15405}
15406
15407static int winMutexEnd(void){
15408  /* The first to decrement to 0 does actual shutdown
15409  ** (which should be the last to shutdown.) */
15410  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
15411    if( winMutex_isInit==1 ){
15412      int i;
15413      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15414        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
15415      }
15416      winMutex_isInit = 0;
15417    }
15418  }
15419  return SQLITE_OK;
15420}
15421
15422/*
15423** The sqlite3_mutex_alloc() routine allocates a new
15424** mutex and returns a pointer to it.  If it returns NULL
15425** that means that a mutex could not be allocated.  SQLite
15426** will unwind its stack and return an error.  The argument
15427** to sqlite3_mutex_alloc() is one of these integer constants:
15428**
15429** <ul>
15430** <li>  SQLITE_MUTEX_FAST
15431** <li>  SQLITE_MUTEX_RECURSIVE
15432** <li>  SQLITE_MUTEX_STATIC_MASTER
15433** <li>  SQLITE_MUTEX_STATIC_MEM
15434** <li>  SQLITE_MUTEX_STATIC_MEM2
15435** <li>  SQLITE_MUTEX_STATIC_PRNG
15436** <li>  SQLITE_MUTEX_STATIC_LRU
15437** <li>  SQLITE_MUTEX_STATIC_LRU2
15438** </ul>
15439**
15440** The first two constants cause sqlite3_mutex_alloc() to create
15441** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15442** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15443** The mutex implementation does not need to make a distinction
15444** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15445** not want to.  But SQLite will only request a recursive mutex in
15446** cases where it really needs one.  If a faster non-recursive mutex
15447** implementation is available on the host platform, the mutex subsystem
15448** might return such a mutex in response to SQLITE_MUTEX_FAST.
15449**
15450** The other allowed parameters to sqlite3_mutex_alloc() each return
15451** a pointer to a static preexisting mutex.  Six static mutexes are
15452** used by the current version of SQLite.  Future versions of SQLite
15453** may add additional static mutexes.  Static mutexes are for internal
15454** use by SQLite only.  Applications that use SQLite mutexes should
15455** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15456** SQLITE_MUTEX_RECURSIVE.
15457**
15458** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15459** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15460** returns a different mutex on every call.  But for the static
15461** mutex types, the same mutex is returned on every call that has
15462** the same type number.
15463*/
15464static sqlite3_mutex *winMutexAlloc(int iType){
15465  sqlite3_mutex *p;
15466
15467  switch( iType ){
15468    case SQLITE_MUTEX_FAST:
15469    case SQLITE_MUTEX_RECURSIVE: {
15470      p = sqlite3MallocZero( sizeof(*p) );
15471      if( p ){
15472        p->id = iType;
15473        InitializeCriticalSection(&p->mutex);
15474      }
15475      break;
15476    }
15477    default: {
15478      assert( winMutex_isInit==1 );
15479      assert( iType-2 >= 0 );
15480      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
15481      p = &winMutex_staticMutexes[iType-2];
15482      p->id = iType;
15483      break;
15484    }
15485  }
15486  return p;
15487}
15488
15489
15490/*
15491** This routine deallocates a previously
15492** allocated mutex.  SQLite is careful to deallocate every
15493** mutex that it allocates.
15494*/
15495static void winMutexFree(sqlite3_mutex *p){
15496  assert( p );
15497  assert( p->nRef==0 );
15498  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15499  DeleteCriticalSection(&p->mutex);
15500  sqlite3_free(p);
15501}
15502
15503/*
15504** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15505** to enter a mutex.  If another thread is already within the mutex,
15506** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15507** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15508** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15509** be entered multiple times by the same thread.  In such cases the,
15510** mutex must be exited an equal number of times before another thread
15511** can enter.  If the same thread tries to enter any other kind of mutex
15512** more than once, the behavior is undefined.
15513*/
15514static void winMutexEnter(sqlite3_mutex *p){
15515  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15516  EnterCriticalSection(&p->mutex);
15517  p->owner = GetCurrentThreadId();
15518  p->nRef++;
15519}
15520static int winMutexTry(sqlite3_mutex *p){
15521  int rc = SQLITE_BUSY;
15522  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld(p) );
15523  /*
15524  ** The sqlite3_mutex_try() routine is very rarely used, and when it
15525  ** is used it is merely an optimization.  So it is OK for it to always
15526  ** fail.
15527  **
15528  ** The TryEnterCriticalSection() interface is only available on WinNT.
15529  ** And some windows compilers complain if you try to use it without
15530  ** first doing some #defines that prevent SQLite from building on Win98.
15531  ** For that reason, we will omit this optimization for now.  See
15532  ** ticket #2685.
15533  */
15534#if 0
15535  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
15536    p->owner = GetCurrentThreadId();
15537    p->nRef++;
15538    rc = SQLITE_OK;
15539  }
15540#else
15541  UNUSED_PARAMETER(p);
15542#endif
15543  return rc;
15544}
15545
15546/*
15547** The sqlite3_mutex_leave() routine exits a mutex that was
15548** previously entered by the same thread.  The behavior
15549** is undefined if the mutex is not currently entered or
15550** is not currently allocated.  SQLite will never do either.
15551*/
15552static void winMutexLeave(sqlite3_mutex *p){
15553  assert( p->nRef>0 );
15554  assert( p->owner==GetCurrentThreadId() );
15555  p->nRef--;
15556  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15557  LeaveCriticalSection(&p->mutex);
15558}
15559
15560SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15561  static sqlite3_mutex_methods sMutex = {
15562    winMutexInit,
15563    winMutexEnd,
15564    winMutexAlloc,
15565    winMutexFree,
15566    winMutexEnter,
15567    winMutexTry,
15568    winMutexLeave,
15569#ifdef SQLITE_DEBUG
15570    winMutexHeld,
15571    winMutexNotheld
15572#else
15573    0,
15574    0
15575#endif
15576  };
15577
15578  return &sMutex;
15579}
15580#endif /* SQLITE_MUTEX_W32 */
15581
15582/************** End of mutex_w32.c *******************************************/
15583/************** Begin file malloc.c ******************************************/
15584/*
15585** 2001 September 15
15586**
15587** The author disclaims copyright to this source code.  In place of
15588** a legal notice, here is a blessing:
15589**
15590**    May you do good and not evil.
15591**    May you find forgiveness for yourself and forgive others.
15592**    May you share freely, never taking more than you give.
15593**
15594*************************************************************************
15595**
15596** Memory allocation functions used throughout sqlite.
15597*/
15598
15599/*
15600** This routine runs when the memory allocator sees that the
15601** total memory allocation is about to exceed the soft heap
15602** limit.
15603*/
15604static void softHeapLimitEnforcer(
15605  void *NotUsed,
15606  sqlite3_int64 NotUsed2,
15607  int allocSize
15608){
15609  UNUSED_PARAMETER2(NotUsed, NotUsed2);
15610  sqlite3_release_memory(allocSize);
15611}
15612
15613/*
15614** Set the soft heap-size limit for the library. Passing a zero or
15615** negative value indicates no limit.
15616*/
15617SQLITE_API void sqlite3_soft_heap_limit(int n){
15618  sqlite3_uint64 iLimit;
15619  int overage;
15620  if( n<0 ){
15621    iLimit = 0;
15622  }else{
15623    iLimit = n;
15624  }
15625#ifndef SQLITE_OMIT_AUTOINIT
15626  sqlite3_initialize();
15627#endif
15628  if( iLimit>0 ){
15629    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
15630  }else{
15631    sqlite3MemoryAlarm(0, 0, 0);
15632  }
15633  overage = (int)(sqlite3_memory_used() - (i64)n);
15634  if( overage>0 ){
15635    sqlite3_release_memory(overage);
15636  }
15637}
15638
15639/*
15640** Attempt to release up to n bytes of non-essential memory currently
15641** held by SQLite. An example of non-essential memory is memory used to
15642** cache database pages that are not currently in use.
15643*/
15644SQLITE_API int sqlite3_release_memory(int n){
15645#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
15646  int nRet = 0;
15647  nRet += sqlite3PcacheReleaseMemory(n-nRet);
15648  return nRet;
15649#else
15650  UNUSED_PARAMETER(n);
15651  return SQLITE_OK;
15652#endif
15653}
15654
15655/*
15656** State information local to the memory allocation subsystem.
15657*/
15658static SQLITE_WSD struct Mem0Global {
15659  /* Number of free pages for scratch and page-cache memory */
15660  u32 nScratchFree;
15661  u32 nPageFree;
15662
15663  sqlite3_mutex *mutex;         /* Mutex to serialize access */
15664
15665  /*
15666  ** The alarm callback and its arguments.  The mem0.mutex lock will
15667  ** be held while the callback is running.  Recursive calls into
15668  ** the memory subsystem are allowed, but no new callbacks will be
15669  ** issued.
15670  */
15671  sqlite3_int64 alarmThreshold;
15672  void (*alarmCallback)(void*, sqlite3_int64,int);
15673  void *alarmArg;
15674
15675  /*
15676  ** Pointers to the end of sqlite3GlobalConfig.pScratch and
15677  ** sqlite3GlobalConfig.pPage to a block of memory that records
15678  ** which pages are available.
15679  */
15680  u32 *aScratchFree;
15681  u32 *aPageFree;
15682} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
15683
15684#define mem0 GLOBAL(struct Mem0Global, mem0)
15685
15686/*
15687** Initialize the memory allocation subsystem.
15688*/
15689SQLITE_PRIVATE int sqlite3MallocInit(void){
15690  if( sqlite3GlobalConfig.m.xMalloc==0 ){
15691    sqlite3MemSetDefault();
15692  }
15693  memset(&mem0, 0, sizeof(mem0));
15694  if( sqlite3GlobalConfig.bCoreMutex ){
15695    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15696  }
15697  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
15698      && sqlite3GlobalConfig.nScratch>=0 ){
15699    int i;
15700    sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
15701    mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
15702                  [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
15703    for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
15704    mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
15705  }else{
15706    sqlite3GlobalConfig.pScratch = 0;
15707    sqlite3GlobalConfig.szScratch = 0;
15708  }
15709  if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
15710      && sqlite3GlobalConfig.nPage>=1 ){
15711    int i;
15712    int overhead;
15713    int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
15714    int n = sqlite3GlobalConfig.nPage;
15715    overhead = (4*n + sz - 1)/sz;
15716    sqlite3GlobalConfig.nPage -= overhead;
15717    mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
15718                  [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
15719    for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
15720    mem0.nPageFree = sqlite3GlobalConfig.nPage;
15721  }else{
15722    sqlite3GlobalConfig.pPage = 0;
15723    sqlite3GlobalConfig.szPage = 0;
15724  }
15725  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
15726}
15727
15728/*
15729** Deinitialize the memory allocation subsystem.
15730*/
15731SQLITE_PRIVATE void sqlite3MallocEnd(void){
15732  if( sqlite3GlobalConfig.m.xShutdown ){
15733    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
15734  }
15735  memset(&mem0, 0, sizeof(mem0));
15736}
15737
15738/*
15739** Return the amount of memory currently checked out.
15740*/
15741SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
15742  int n, mx;
15743  sqlite3_int64 res;
15744  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
15745  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
15746  return res;
15747}
15748
15749/*
15750** Return the maximum amount of memory that has ever been
15751** checked out since either the beginning of this process
15752** or since the most recent reset.
15753*/
15754SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
15755  int n, mx;
15756  sqlite3_int64 res;
15757  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
15758  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
15759  return res;
15760}
15761
15762/*
15763** Change the alarm callback
15764*/
15765SQLITE_PRIVATE int sqlite3MemoryAlarm(
15766  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15767  void *pArg,
15768  sqlite3_int64 iThreshold
15769){
15770  sqlite3_mutex_enter(mem0.mutex);
15771  mem0.alarmCallback = xCallback;
15772  mem0.alarmArg = pArg;
15773  mem0.alarmThreshold = iThreshold;
15774  sqlite3_mutex_leave(mem0.mutex);
15775  return SQLITE_OK;
15776}
15777
15778#ifndef SQLITE_OMIT_DEPRECATED
15779/*
15780** Deprecated external interface.  Internal/core SQLite code
15781** should call sqlite3MemoryAlarm.
15782*/
15783SQLITE_API int sqlite3_memory_alarm(
15784  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
15785  void *pArg,
15786  sqlite3_int64 iThreshold
15787){
15788  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
15789}
15790#endif
15791
15792/*
15793** Trigger the alarm
15794*/
15795static void sqlite3MallocAlarm(int nByte){
15796  void (*xCallback)(void*,sqlite3_int64,int);
15797  sqlite3_int64 nowUsed;
15798  void *pArg;
15799  if( mem0.alarmCallback==0 ) return;
15800  xCallback = mem0.alarmCallback;
15801  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15802  pArg = mem0.alarmArg;
15803  mem0.alarmCallback = 0;
15804  sqlite3_mutex_leave(mem0.mutex);
15805  xCallback(pArg, nowUsed, nByte);
15806  sqlite3_mutex_enter(mem0.mutex);
15807  mem0.alarmCallback = xCallback;
15808  mem0.alarmArg = pArg;
15809}
15810
15811/*
15812** Do a memory allocation with statistics and alarms.  Assume the
15813** lock is already held.
15814*/
15815static int mallocWithAlarm(int n, void **pp){
15816  int nFull;
15817  void *p;
15818  assert( sqlite3_mutex_held(mem0.mutex) );
15819  nFull = sqlite3GlobalConfig.m.xRoundup(n);
15820  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
15821  if( mem0.alarmCallback!=0 ){
15822    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
15823    if( nUsed+nFull >= mem0.alarmThreshold ){
15824      sqlite3MallocAlarm(nFull);
15825    }
15826  }
15827  p = sqlite3GlobalConfig.m.xMalloc(nFull);
15828  if( p==0 && mem0.alarmCallback ){
15829    sqlite3MallocAlarm(nFull);
15830    p = sqlite3GlobalConfig.m.xMalloc(nFull);
15831  }
15832  if( p ){
15833    nFull = sqlite3MallocSize(p);
15834    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
15835  }
15836  *pp = p;
15837  return nFull;
15838}
15839
15840/*
15841** Allocate memory.  This routine is like sqlite3_malloc() except that it
15842** assumes the memory subsystem has already been initialized.
15843*/
15844SQLITE_PRIVATE void *sqlite3Malloc(int n){
15845  void *p;
15846  if( n<=0 || n>=0x7fffff00 ){
15847    /* A memory allocation of a number of bytes which is near the maximum
15848    ** signed integer value might cause an integer overflow inside of the
15849    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
15850    ** 255 bytes of overhead.  SQLite itself will never use anything near
15851    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
15852    p = 0;
15853  }else if( sqlite3GlobalConfig.bMemstat ){
15854    sqlite3_mutex_enter(mem0.mutex);
15855    mallocWithAlarm(n, &p);
15856    sqlite3_mutex_leave(mem0.mutex);
15857  }else{
15858    p = sqlite3GlobalConfig.m.xMalloc(n);
15859  }
15860  return p;
15861}
15862
15863/*
15864** This version of the memory allocation is for use by the application.
15865** First make sure the memory subsystem is initialized, then do the
15866** allocation.
15867*/
15868SQLITE_API void *sqlite3_malloc(int n){
15869#ifndef SQLITE_OMIT_AUTOINIT
15870  if( sqlite3_initialize() ) return 0;
15871#endif
15872  return sqlite3Malloc(n);
15873}
15874
15875/*
15876** Each thread may only have a single outstanding allocation from
15877** xScratchMalloc().  We verify this constraint in the single-threaded
15878** case by setting scratchAllocOut to 1 when an allocation
15879** is outstanding clearing it when the allocation is freed.
15880*/
15881#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15882static int scratchAllocOut = 0;
15883#endif
15884
15885
15886/*
15887** Allocate memory that is to be used and released right away.
15888** This routine is similar to alloca() in that it is not intended
15889** for situations where the memory might be held long-term.  This
15890** routine is intended to get memory to old large transient data
15891** structures that would not normally fit on the stack of an
15892** embedded processor.
15893*/
15894SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
15895  void *p;
15896  assert( n>0 );
15897
15898#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15899  /* Verify that no more than one scratch allocation per thread
15900  ** is outstanding at one time.  (This is only checked in the
15901  ** single-threaded case since checking in the multi-threaded case
15902  ** would be much more complicated.) */
15903  assert( scratchAllocOut==0 );
15904#endif
15905
15906  if( sqlite3GlobalConfig.szScratch<n ){
15907    goto scratch_overflow;
15908  }else{
15909    sqlite3_mutex_enter(mem0.mutex);
15910    if( mem0.nScratchFree==0 ){
15911      sqlite3_mutex_leave(mem0.mutex);
15912      goto scratch_overflow;
15913    }else{
15914      int i;
15915      i = mem0.aScratchFree[--mem0.nScratchFree];
15916      i *= sqlite3GlobalConfig.szScratch;
15917      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
15918      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
15919      sqlite3_mutex_leave(mem0.mutex);
15920      p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
15921      assert(  (((u8*)p - (u8*)0) & 7)==0 );
15922    }
15923  }
15924#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15925  scratchAllocOut = p!=0;
15926#endif
15927
15928  return p;
15929
15930scratch_overflow:
15931  if( sqlite3GlobalConfig.bMemstat ){
15932    sqlite3_mutex_enter(mem0.mutex);
15933    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
15934    n = mallocWithAlarm(n, &p);
15935    if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
15936    sqlite3_mutex_leave(mem0.mutex);
15937  }else{
15938    p = sqlite3GlobalConfig.m.xMalloc(n);
15939  }
15940#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15941  scratchAllocOut = p!=0;
15942#endif
15943  return p;
15944}
15945SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
15946  if( p ){
15947
15948#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
15949    /* Verify that no more than one scratch allocation per thread
15950    ** is outstanding at one time.  (This is only checked in the
15951    ** single-threaded case since checking in the multi-threaded case
15952    ** would be much more complicated.) */
15953    assert( scratchAllocOut==1 );
15954    scratchAllocOut = 0;
15955#endif
15956
15957    if( sqlite3GlobalConfig.pScratch==0
15958           || p<sqlite3GlobalConfig.pScratch
15959           || p>=(void*)mem0.aScratchFree ){
15960      if( sqlite3GlobalConfig.bMemstat ){
15961        int iSize = sqlite3MallocSize(p);
15962        sqlite3_mutex_enter(mem0.mutex);
15963        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
15964        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
15965        sqlite3GlobalConfig.m.xFree(p);
15966        sqlite3_mutex_leave(mem0.mutex);
15967      }else{
15968        sqlite3GlobalConfig.m.xFree(p);
15969      }
15970    }else{
15971      int i;
15972      i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
15973      i /= sqlite3GlobalConfig.szScratch;
15974      assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
15975      sqlite3_mutex_enter(mem0.mutex);
15976      assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
15977      mem0.aScratchFree[mem0.nScratchFree++] = i;
15978      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
15979      sqlite3_mutex_leave(mem0.mutex);
15980    }
15981  }
15982}
15983
15984/*
15985** TRUE if p is a lookaside memory allocation from db
15986*/
15987#ifndef SQLITE_OMIT_LOOKASIDE
15988static int isLookaside(sqlite3 *db, void *p){
15989  return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
15990}
15991#else
15992#define isLookaside(A,B) 0
15993#endif
15994
15995/*
15996** Return the size of a memory allocation previously obtained from
15997** sqlite3Malloc() or sqlite3_malloc().
15998*/
15999SQLITE_PRIVATE int sqlite3MallocSize(void *p){
16000  return sqlite3GlobalConfig.m.xSize(p);
16001}
16002SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16003  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16004  if( isLookaside(db, p) ){
16005    return db->lookaside.sz;
16006  }else{
16007    return sqlite3GlobalConfig.m.xSize(p);
16008  }
16009}
16010
16011/*
16012** Free memory previously obtained from sqlite3Malloc().
16013*/
16014SQLITE_API void sqlite3_free(void *p){
16015  if( p==0 ) return;
16016  if( sqlite3GlobalConfig.bMemstat ){
16017    sqlite3_mutex_enter(mem0.mutex);
16018    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16019    sqlite3GlobalConfig.m.xFree(p);
16020    sqlite3_mutex_leave(mem0.mutex);
16021  }else{
16022    sqlite3GlobalConfig.m.xFree(p);
16023  }
16024}
16025
16026/*
16027** Free memory that might be associated with a particular database
16028** connection.
16029*/
16030SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16031  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16032  if( isLookaside(db, p) ){
16033    LookasideSlot *pBuf = (LookasideSlot*)p;
16034    pBuf->pNext = db->lookaside.pFree;
16035    db->lookaside.pFree = pBuf;
16036    db->lookaside.nOut--;
16037  }else{
16038    sqlite3_free(p);
16039  }
16040}
16041
16042/*
16043** Change the size of an existing memory allocation
16044*/
16045SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16046  int nOld, nNew;
16047  void *pNew;
16048  if( pOld==0 ){
16049    return sqlite3Malloc(nBytes);
16050  }
16051  if( nBytes<=0 ){
16052    sqlite3_free(pOld);
16053    return 0;
16054  }
16055  if( nBytes>=0x7fffff00 ){
16056    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
16057    return 0;
16058  }
16059  nOld = sqlite3MallocSize(pOld);
16060  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
16061  if( nOld==nNew ){
16062    pNew = pOld;
16063  }else if( sqlite3GlobalConfig.bMemstat ){
16064    sqlite3_mutex_enter(mem0.mutex);
16065    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
16066    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >=
16067          mem0.alarmThreshold ){
16068      sqlite3MallocAlarm(nNew-nOld);
16069    }
16070    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16071    if( pNew==0 && mem0.alarmCallback ){
16072      sqlite3MallocAlarm(nBytes);
16073      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16074    }
16075    if( pNew ){
16076      nNew = sqlite3MallocSize(pNew);
16077      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
16078    }
16079    sqlite3_mutex_leave(mem0.mutex);
16080  }else{
16081    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16082  }
16083  return pNew;
16084}
16085
16086/*
16087** The public interface to sqlite3Realloc.  Make sure that the memory
16088** subsystem is initialized prior to invoking sqliteRealloc.
16089*/
16090SQLITE_API void *sqlite3_realloc(void *pOld, int n){
16091#ifndef SQLITE_OMIT_AUTOINIT
16092  if( sqlite3_initialize() ) return 0;
16093#endif
16094  return sqlite3Realloc(pOld, n);
16095}
16096
16097
16098/*
16099** Allocate and zero memory.
16100*/
16101SQLITE_PRIVATE void *sqlite3MallocZero(int n){
16102  void *p = sqlite3Malloc(n);
16103  if( p ){
16104    memset(p, 0, n);
16105  }
16106  return p;
16107}
16108
16109/*
16110** Allocate and zero memory.  If the allocation fails, make
16111** the mallocFailed flag in the connection pointer.
16112*/
16113SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
16114  void *p = sqlite3DbMallocRaw(db, n);
16115  if( p ){
16116    memset(p, 0, n);
16117  }
16118  return p;
16119}
16120
16121/*
16122** Allocate and zero memory.  If the allocation fails, make
16123** the mallocFailed flag in the connection pointer.
16124**
16125** If db!=0 and db->mallocFailed is true (indicating a prior malloc
16126** failure on the same database connection) then always return 0.
16127** Hence for a particular database connection, once malloc starts
16128** failing, it fails consistently until mallocFailed is reset.
16129** This is an important assumption.  There are many places in the
16130** code that do things like this:
16131**
16132**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
16133**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
16134**         if( b ) a[10] = 9;
16135**
16136** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
16137** that all prior mallocs (ex: "a") worked too.
16138*/
16139SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
16140  void *p;
16141  assert( db==0 || sqlite3_mutex_held(db->mutex) );
16142#ifndef SQLITE_OMIT_LOOKASIDE
16143  if( db ){
16144    LookasideSlot *pBuf;
16145    if( db->mallocFailed ){
16146      return 0;
16147    }
16148    if( db->lookaside.bEnabled && n<=db->lookaside.sz
16149         && (pBuf = db->lookaside.pFree)!=0 ){
16150      db->lookaside.pFree = pBuf->pNext;
16151      db->lookaside.nOut++;
16152      if( db->lookaside.nOut>db->lookaside.mxOut ){
16153        db->lookaside.mxOut = db->lookaside.nOut;
16154      }
16155      return (void*)pBuf;
16156    }
16157  }
16158#else
16159  if( db && db->mallocFailed ){
16160    return 0;
16161  }
16162#endif
16163  p = sqlite3Malloc(n);
16164  if( !p && db ){
16165    db->mallocFailed = 1;
16166  }
16167  return p;
16168}
16169
16170/*
16171** Resize the block of memory pointed to by p to n bytes. If the
16172** resize fails, set the mallocFailed flag in the connection object.
16173*/
16174SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
16175  void *pNew = 0;
16176  assert( db!=0 );
16177  assert( sqlite3_mutex_held(db->mutex) );
16178  if( db->mallocFailed==0 ){
16179    if( p==0 ){
16180      return sqlite3DbMallocRaw(db, n);
16181    }
16182    if( isLookaside(db, p) ){
16183      if( n<=db->lookaside.sz ){
16184        return p;
16185      }
16186      pNew = sqlite3DbMallocRaw(db, n);
16187      if( pNew ){
16188        memcpy(pNew, p, db->lookaside.sz);
16189        sqlite3DbFree(db, p);
16190      }
16191    }else{
16192      pNew = sqlite3_realloc(p, n);
16193      if( !pNew ){
16194        db->mallocFailed = 1;
16195      }
16196    }
16197  }
16198  return pNew;
16199}
16200
16201/*
16202** Attempt to reallocate p.  If the reallocation fails, then free p
16203** and set the mallocFailed flag in the database connection.
16204*/
16205SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
16206  void *pNew;
16207  pNew = sqlite3DbRealloc(db, p, n);
16208  if( !pNew ){
16209    sqlite3DbFree(db, p);
16210  }
16211  return pNew;
16212}
16213
16214/*
16215** Make a copy of a string in memory obtained from sqliteMalloc(). These
16216** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
16217** is because when memory debugging is turned on, these two functions are
16218** called via macros that record the current file and line number in the
16219** ThreadData structure.
16220*/
16221SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
16222  char *zNew;
16223  size_t n;
16224  if( z==0 ){
16225    return 0;
16226  }
16227  n = sqlite3Strlen30(z) + 1;
16228  assert( (n&0x7fffffff)==n );
16229  zNew = sqlite3DbMallocRaw(db, (int)n);
16230  if( zNew ){
16231    memcpy(zNew, z, n);
16232  }
16233  return zNew;
16234}
16235SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
16236  char *zNew;
16237  if( z==0 ){
16238    return 0;
16239  }
16240  assert( (n&0x7fffffff)==n );
16241  zNew = sqlite3DbMallocRaw(db, n+1);
16242  if( zNew ){
16243    memcpy(zNew, z, n);
16244    zNew[n] = 0;
16245  }
16246  return zNew;
16247}
16248
16249/*
16250** Create a string from the zFromat argument and the va_list that follows.
16251** Store the string in memory obtained from sqliteMalloc() and make *pz
16252** point to that string.
16253*/
16254SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
16255  va_list ap;
16256  char *z;
16257
16258  va_start(ap, zFormat);
16259  z = sqlite3VMPrintf(db, zFormat, ap);
16260  va_end(ap);
16261  sqlite3DbFree(db, *pz);
16262  *pz = z;
16263}
16264
16265
16266/*
16267** This function must be called before exiting any API function (i.e.
16268** returning control to the user) that has called sqlite3_malloc or
16269** sqlite3_realloc.
16270**
16271** The returned value is normally a copy of the second argument to this
16272** function. However, if a malloc() failure has occurred since the previous
16273** invocation SQLITE_NOMEM is returned instead.
16274**
16275** If the first argument, db, is not NULL and a malloc() error has occurred,
16276** then the connection error-code (the value returned by sqlite3_errcode())
16277** is set to SQLITE_NOMEM.
16278*/
16279SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
16280  /* If the db handle is not NULL, then we must hold the connection handle
16281  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
16282  ** is unsafe, as is the call to sqlite3Error().
16283  */
16284  assert( !db || sqlite3_mutex_held(db->mutex) );
16285  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
16286    sqlite3Error(db, SQLITE_NOMEM, 0);
16287    db->mallocFailed = 0;
16288    rc = SQLITE_NOMEM;
16289  }
16290  return rc & (db ? db->errMask : 0xff);
16291}
16292
16293/************** End of malloc.c **********************************************/
16294/************** Begin file printf.c ******************************************/
16295/*
16296** The "printf" code that follows dates from the 1980's.  It is in
16297** the public domain.  The original comments are included here for
16298** completeness.  They are very out-of-date but might be useful as
16299** an historical reference.  Most of the "enhancements" have been backed
16300** out so that the functionality is now the same as standard printf().
16301**
16302**************************************************************************
16303**
16304** The following modules is an enhanced replacement for the "printf" subroutines
16305** found in the standard C library.  The following enhancements are
16306** supported:
16307**
16308**      +  Additional functions.  The standard set of "printf" functions
16309**         includes printf, fprintf, sprintf, vprintf, vfprintf, and
16310**         vsprintf.  This module adds the following:
16311**
16312**           *  snprintf -- Works like sprintf, but has an extra argument
16313**                          which is the size of the buffer written to.
16314**
16315**           *  mprintf --  Similar to sprintf.  Writes output to memory
16316**                          obtained from malloc.
16317**
16318**           *  xprintf --  Calls a function to dispose of output.
16319**
16320**           *  nprintf --  No output, but returns the number of characters
16321**                          that would have been output by printf.
16322**
16323**           *  A v- version (ex: vsnprintf) of every function is also
16324**              supplied.
16325**
16326**      +  A few extensions to the formatting notation are supported:
16327**
16328**           *  The "=" flag (similar to "-") causes the output to be
16329**              be centered in the appropriately sized field.
16330**
16331**           *  The %b field outputs an integer in binary notation.
16332**
16333**           *  The %c field now accepts a precision.  The character output
16334**              is repeated by the number of times the precision specifies.
16335**
16336**           *  The %' field works like %c, but takes as its character the
16337**              next character of the format string, instead of the next
16338**              argument.  For example,  printf("%.78'-")  prints 78 minus
16339**              signs, the same as  printf("%.78c",'-').
16340**
16341**      +  When compiled using GCC on a SPARC, this version of printf is
16342**         faster than the library printf for SUN OS 4.1.
16343**
16344**      +  All functions are fully reentrant.
16345**
16346*/
16347
16348/*
16349** Conversion types fall into various categories as defined by the
16350** following enumeration.
16351*/
16352#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
16353#define etFLOAT       2 /* Floating point.  %f */
16354#define etEXP         3 /* Exponentional notation. %e and %E */
16355#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
16356#define etSIZE        5 /* Return number of characters processed so far. %n */
16357#define etSTRING      6 /* Strings. %s */
16358#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
16359#define etPERCENT     8 /* Percent symbol. %% */
16360#define etCHARX       9 /* Characters. %c */
16361/* The rest are extensions, not normally found in printf() */
16362#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
16363#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
16364                          NULL pointers replaced by SQL NULL.  %Q */
16365#define etTOKEN      12 /* a pointer to a Token structure */
16366#define etSRCLIST    13 /* a pointer to a SrcList */
16367#define etPOINTER    14 /* The %p conversion */
16368#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
16369#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
16370
16371#define etINVALID     0 /* Any unrecognized conversion type */
16372
16373
16374/*
16375** An "etByte" is an 8-bit unsigned value.
16376*/
16377typedef unsigned char etByte;
16378
16379/*
16380** Each builtin conversion character (ex: the 'd' in "%d") is described
16381** by an instance of the following structure
16382*/
16383typedef struct et_info {   /* Information about each format field */
16384  char fmttype;            /* The format field code letter */
16385  etByte base;             /* The base for radix conversion */
16386  etByte flags;            /* One or more of FLAG_ constants below */
16387  etByte type;             /* Conversion paradigm */
16388  etByte charset;          /* Offset into aDigits[] of the digits string */
16389  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
16390} et_info;
16391
16392/*
16393** Allowed values for et_info.flags
16394*/
16395#define FLAG_SIGNED  1     /* True if the value to convert is signed */
16396#define FLAG_INTERN  2     /* True if for internal use only */
16397#define FLAG_STRING  4     /* Allow infinity precision */
16398
16399
16400/*
16401** The following table is searched linearly, so it is good to put the
16402** most frequently used conversion types first.
16403*/
16404static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
16405static const char aPrefix[] = "-x0\000X0";
16406static const et_info fmtinfo[] = {
16407  {  'd', 10, 1, etRADIX,      0,  0 },
16408  {  's',  0, 4, etSTRING,     0,  0 },
16409  {  'g',  0, 1, etGENERIC,    30, 0 },
16410  {  'z',  0, 4, etDYNSTRING,  0,  0 },
16411  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
16412  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
16413  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
16414  {  'c',  0, 0, etCHARX,      0,  0 },
16415  {  'o',  8, 0, etRADIX,      0,  2 },
16416  {  'u', 10, 0, etRADIX,      0,  0 },
16417  {  'x', 16, 0, etRADIX,      16, 1 },
16418  {  'X', 16, 0, etRADIX,      0,  4 },
16419#ifndef SQLITE_OMIT_FLOATING_POINT
16420  {  'f',  0, 1, etFLOAT,      0,  0 },
16421  {  'e',  0, 1, etEXP,        30, 0 },
16422  {  'E',  0, 1, etEXP,        14, 0 },
16423  {  'G',  0, 1, etGENERIC,    14, 0 },
16424#endif
16425  {  'i', 10, 1, etRADIX,      0,  0 },
16426  {  'n',  0, 0, etSIZE,       0,  0 },
16427  {  '%',  0, 0, etPERCENT,    0,  0 },
16428  {  'p', 16, 0, etPOINTER,    0,  1 },
16429
16430/* All the rest have the FLAG_INTERN bit set and are thus for internal
16431** use only */
16432  {  'T',  0, 2, etTOKEN,      0,  0 },
16433  {  'S',  0, 2, etSRCLIST,    0,  0 },
16434  {  'r', 10, 3, etORDINAL,    0,  0 },
16435};
16436
16437/*
16438** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
16439** conversions will work.
16440*/
16441#ifndef SQLITE_OMIT_FLOATING_POINT
16442/*
16443** "*val" is a double such that 0.1 <= *val < 10.0
16444** Return the ascii code for the leading digit of *val, then
16445** multiply "*val" by 10.0 to renormalize.
16446**
16447** Example:
16448**     input:     *val = 3.14159
16449**     output:    *val = 1.4159    function return = '3'
16450**
16451** The counter *cnt is incremented each time.  After counter exceeds
16452** 16 (the number of significant digits in a 64-bit float) '0' is
16453** always returned.
16454*/
16455static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
16456  int digit;
16457  LONGDOUBLE_TYPE d;
16458  if( (*cnt)++ >= 16 ) return '0';
16459  digit = (int)*val;
16460  d = digit;
16461  digit += '0';
16462  *val = (*val - d)*10.0;
16463  return (char)digit;
16464}
16465#endif /* SQLITE_OMIT_FLOATING_POINT */
16466
16467/*
16468** Append N space characters to the given string buffer.
16469*/
16470static void appendSpace(StrAccum *pAccum, int N){
16471  static const char zSpaces[] = "                             ";
16472  while( N>=(int)sizeof(zSpaces)-1 ){
16473    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
16474    N -= sizeof(zSpaces)-1;
16475  }
16476  if( N>0 ){
16477    sqlite3StrAccumAppend(pAccum, zSpaces, N);
16478  }
16479}
16480
16481/*
16482** On machines with a small stack size, you can redefine the
16483** SQLITE_PRINT_BUF_SIZE to be less than 350.
16484*/
16485#ifndef SQLITE_PRINT_BUF_SIZE
16486# if defined(SQLITE_SMALL_STACK)
16487#   define SQLITE_PRINT_BUF_SIZE 50
16488# else
16489#   define SQLITE_PRINT_BUF_SIZE 350
16490# endif
16491#endif
16492#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
16493
16494/*
16495** The root program.  All variations call this core.
16496**
16497** INPUTS:
16498**   func   This is a pointer to a function taking three arguments
16499**            1. A pointer to anything.  Same as the "arg" parameter.
16500**            2. A pointer to the list of characters to be output
16501**               (Note, this list is NOT null terminated.)
16502**            3. An integer number of characters to be output.
16503**               (Note: This number might be zero.)
16504**
16505**   arg    This is the pointer to anything which will be passed as the
16506**          first argument to "func".  Use it for whatever you like.
16507**
16508**   fmt    This is the format string, as in the usual print.
16509**
16510**   ap     This is a pointer to a list of arguments.  Same as in
16511**          vfprint.
16512**
16513** OUTPUTS:
16514**          The return value is the total number of characters sent to
16515**          the function "func".  Returns -1 on a error.
16516**
16517** Note that the order in which automatic variables are declared below
16518** seems to make a big difference in determining how fast this beast
16519** will run.
16520*/
16521SQLITE_PRIVATE void sqlite3VXPrintf(
16522  StrAccum *pAccum,                  /* Accumulate results here */
16523  int useExtended,                   /* Allow extended %-conversions */
16524  const char *fmt,                   /* Format string */
16525  va_list ap                         /* arguments */
16526){
16527  int c;                     /* Next character in the format string */
16528  char *bufpt;               /* Pointer to the conversion buffer */
16529  int precision;             /* Precision of the current field */
16530  int length;                /* Length of the field */
16531  int idx;                   /* A general purpose loop counter */
16532  int width;                 /* Width of the current field */
16533  etByte flag_leftjustify;   /* True if "-" flag is present */
16534  etByte flag_plussign;      /* True if "+" flag is present */
16535  etByte flag_blanksign;     /* True if " " flag is present */
16536  etByte flag_alternateform; /* True if "#" flag is present */
16537  etByte flag_altform2;      /* True if "!" flag is present */
16538  etByte flag_zeropad;       /* True if field width constant starts with zero */
16539  etByte flag_long;          /* True if "l" flag is present */
16540  etByte flag_longlong;      /* True if the "ll" flag is present */
16541  etByte done;               /* Loop termination flag */
16542  sqlite_uint64 longvalue;   /* Value for integer types */
16543  LONGDOUBLE_TYPE realvalue; /* Value for real types */
16544  const et_info *infop;      /* Pointer to the appropriate info structure */
16545  char buf[etBUFSIZE];       /* Conversion buffer */
16546  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
16547  etByte xtype = 0;          /* Conversion paradigm */
16548  char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
16549#ifndef SQLITE_OMIT_FLOATING_POINT
16550  int  exp, e2;              /* exponent of real numbers */
16551  double rounder;            /* Used for rounding floating point values */
16552  etByte flag_dp;            /* True if decimal point should be shown */
16553  etByte flag_rtz;           /* True if trailing zeros should be removed */
16554  etByte flag_exp;           /* True to force display of the exponent */
16555  int nsd;                   /* Number of significant digits returned */
16556#endif
16557
16558  length = 0;
16559  bufpt = 0;
16560  for(; (c=(*fmt))!=0; ++fmt){
16561    if( c!='%' ){
16562      int amt;
16563      bufpt = (char *)fmt;
16564      amt = 1;
16565      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
16566      sqlite3StrAccumAppend(pAccum, bufpt, amt);
16567      if( c==0 ) break;
16568    }
16569    if( (c=(*++fmt))==0 ){
16570      sqlite3StrAccumAppend(pAccum, "%", 1);
16571      break;
16572    }
16573    /* Find out what flags are present */
16574    flag_leftjustify = flag_plussign = flag_blanksign =
16575     flag_alternateform = flag_altform2 = flag_zeropad = 0;
16576    done = 0;
16577    do{
16578      switch( c ){
16579        case '-':   flag_leftjustify = 1;     break;
16580        case '+':   flag_plussign = 1;        break;
16581        case ' ':   flag_blanksign = 1;       break;
16582        case '#':   flag_alternateform = 1;   break;
16583        case '!':   flag_altform2 = 1;        break;
16584        case '0':   flag_zeropad = 1;         break;
16585        default:    done = 1;                 break;
16586      }
16587    }while( !done && (c=(*++fmt))!=0 );
16588    /* Get the field width */
16589    width = 0;
16590    if( c=='*' ){
16591      width = va_arg(ap,int);
16592      if( width<0 ){
16593        flag_leftjustify = 1;
16594        width = -width;
16595      }
16596      c = *++fmt;
16597    }else{
16598      while( c>='0' && c<='9' ){
16599        width = width*10 + c - '0';
16600        c = *++fmt;
16601      }
16602    }
16603    if( width > etBUFSIZE-10 ){
16604      width = etBUFSIZE-10;
16605    }
16606    /* Get the precision */
16607    if( c=='.' ){
16608      precision = 0;
16609      c = *++fmt;
16610      if( c=='*' ){
16611        precision = va_arg(ap,int);
16612        if( precision<0 ) precision = -precision;
16613        c = *++fmt;
16614      }else{
16615        while( c>='0' && c<='9' ){
16616          precision = precision*10 + c - '0';
16617          c = *++fmt;
16618        }
16619      }
16620    }else{
16621      precision = -1;
16622    }
16623    /* Get the conversion type modifier */
16624    if( c=='l' ){
16625      flag_long = 1;
16626      c = *++fmt;
16627      if( c=='l' ){
16628        flag_longlong = 1;
16629        c = *++fmt;
16630      }else{
16631        flag_longlong = 0;
16632      }
16633    }else{
16634      flag_long = flag_longlong = 0;
16635    }
16636    /* Fetch the info entry for the field */
16637    infop = &fmtinfo[0];
16638    xtype = etINVALID;
16639    for(idx=0; idx<ArraySize(fmtinfo); idx++){
16640      if( c==fmtinfo[idx].fmttype ){
16641        infop = &fmtinfo[idx];
16642        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
16643          xtype = infop->type;
16644        }else{
16645          return;
16646        }
16647        break;
16648      }
16649    }
16650    zExtra = 0;
16651
16652
16653    /* Limit the precision to prevent overflowing buf[] during conversion */
16654    if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
16655      precision = etBUFSIZE-40;
16656    }
16657
16658    /*
16659    ** At this point, variables are initialized as follows:
16660    **
16661    **   flag_alternateform          TRUE if a '#' is present.
16662    **   flag_altform2               TRUE if a '!' is present.
16663    **   flag_plussign               TRUE if a '+' is present.
16664    **   flag_leftjustify            TRUE if a '-' is present or if the
16665    **                               field width was negative.
16666    **   flag_zeropad                TRUE if the width began with 0.
16667    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
16668    **                               the conversion character.
16669    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
16670    **                               the conversion character.
16671    **   flag_blanksign              TRUE if a ' ' is present.
16672    **   width                       The specified field width.  This is
16673    **                               always non-negative.  Zero is the default.
16674    **   precision                   The specified precision.  The default
16675    **                               is -1.
16676    **   xtype                       The class of the conversion.
16677    **   infop                       Pointer to the appropriate info struct.
16678    */
16679    switch( xtype ){
16680      case etPOINTER:
16681        flag_longlong = sizeof(char*)==sizeof(i64);
16682        flag_long = sizeof(char*)==sizeof(long int);
16683        /* Fall through into the next case */
16684      case etORDINAL:
16685      case etRADIX:
16686        if( infop->flags & FLAG_SIGNED ){
16687          i64 v;
16688          if( flag_longlong ){
16689            v = va_arg(ap,i64);
16690          }else if( flag_long ){
16691            v = va_arg(ap,long int);
16692          }else{
16693            v = va_arg(ap,int);
16694          }
16695          if( v<0 ){
16696            longvalue = -v;
16697            prefix = '-';
16698          }else{
16699            longvalue = v;
16700            if( flag_plussign )        prefix = '+';
16701            else if( flag_blanksign )  prefix = ' ';
16702            else                       prefix = 0;
16703          }
16704        }else{
16705          if( flag_longlong ){
16706            longvalue = va_arg(ap,u64);
16707          }else if( flag_long ){
16708            longvalue = va_arg(ap,unsigned long int);
16709          }else{
16710            longvalue = va_arg(ap,unsigned int);
16711          }
16712          prefix = 0;
16713        }
16714        if( longvalue==0 ) flag_alternateform = 0;
16715        if( flag_zeropad && precision<width-(prefix!=0) ){
16716          precision = width-(prefix!=0);
16717        }
16718        bufpt = &buf[etBUFSIZE-1];
16719        if( xtype==etORDINAL ){
16720          static const char zOrd[] = "thstndrd";
16721          int x = (int)(longvalue % 10);
16722          if( x>=4 || (longvalue/10)%10==1 ){
16723            x = 0;
16724          }
16725          buf[etBUFSIZE-3] = zOrd[x*2];
16726          buf[etBUFSIZE-2] = zOrd[x*2+1];
16727          bufpt -= 2;
16728        }
16729        {
16730          register const char *cset;      /* Use registers for speed */
16731          register int base;
16732          cset = &aDigits[infop->charset];
16733          base = infop->base;
16734          do{                                           /* Convert to ascii */
16735            *(--bufpt) = cset[longvalue%base];
16736            longvalue = longvalue/base;
16737          }while( longvalue>0 );
16738        }
16739        length = (int)(&buf[etBUFSIZE-1]-bufpt);
16740        for(idx=precision-length; idx>0; idx--){
16741          *(--bufpt) = '0';                             /* Zero pad */
16742        }
16743        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
16744        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
16745          const char *pre;
16746          char x;
16747          pre = &aPrefix[infop->prefix];
16748          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
16749        }
16750        length = (int)(&buf[etBUFSIZE-1]-bufpt);
16751        break;
16752      case etFLOAT:
16753      case etEXP:
16754      case etGENERIC:
16755        realvalue = va_arg(ap,double);
16756#ifndef SQLITE_OMIT_FLOATING_POINT
16757        if( precision<0 ) precision = 6;         /* Set default precision */
16758        if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
16759        if( realvalue<0.0 ){
16760          realvalue = -realvalue;
16761          prefix = '-';
16762        }else{
16763          if( flag_plussign )          prefix = '+';
16764          else if( flag_blanksign )    prefix = ' ';
16765          else                         prefix = 0;
16766        }
16767        if( xtype==etGENERIC && precision>0 ) precision--;
16768#if 0
16769        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
16770        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
16771#else
16772        /* It makes more sense to use 0.5 */
16773        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
16774#endif
16775        if( xtype==etFLOAT ) realvalue += rounder;
16776        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
16777        exp = 0;
16778        if( sqlite3IsNaN((double)realvalue) ){
16779          bufpt = "NaN";
16780          length = 3;
16781          break;
16782        }
16783        if( realvalue>0.0 ){
16784          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
16785          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
16786          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
16787          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
16788          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
16789          if( exp>350 ){
16790            if( prefix=='-' ){
16791              bufpt = "-Inf";
16792            }else if( prefix=='+' ){
16793              bufpt = "+Inf";
16794            }else{
16795              bufpt = "Inf";
16796            }
16797            length = sqlite3Strlen30(bufpt);
16798            break;
16799          }
16800        }
16801        bufpt = buf;
16802        /*
16803        ** If the field type is etGENERIC, then convert to either etEXP
16804        ** or etFLOAT, as appropriate.
16805        */
16806        flag_exp = xtype==etEXP;
16807        if( xtype!=etFLOAT ){
16808          realvalue += rounder;
16809          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
16810        }
16811        if( xtype==etGENERIC ){
16812          flag_rtz = !flag_alternateform;
16813          if( exp<-4 || exp>precision ){
16814            xtype = etEXP;
16815          }else{
16816            precision = precision - exp;
16817            xtype = etFLOAT;
16818          }
16819        }else{
16820          flag_rtz = 0;
16821        }
16822        if( xtype==etEXP ){
16823          e2 = 0;
16824        }else{
16825          e2 = exp;
16826        }
16827        nsd = 0;
16828        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
16829        /* The sign in front of the number */
16830        if( prefix ){
16831          *(bufpt++) = prefix;
16832        }
16833        /* Digits prior to the decimal point */
16834        if( e2<0 ){
16835          *(bufpt++) = '0';
16836        }else{
16837          for(; e2>=0; e2--){
16838            *(bufpt++) = et_getdigit(&realvalue,&nsd);
16839          }
16840        }
16841        /* The decimal point */
16842        if( flag_dp ){
16843          *(bufpt++) = '.';
16844        }
16845        /* "0" digits after the decimal point but before the first
16846        ** significant digit of the number */
16847        for(e2++; e2<0; precision--, e2++){
16848          assert( precision>0 );
16849          *(bufpt++) = '0';
16850        }
16851        /* Significant digits after the decimal point */
16852        while( (precision--)>0 ){
16853          *(bufpt++) = et_getdigit(&realvalue,&nsd);
16854        }
16855        /* Remove trailing zeros and the "." if no digits follow the "." */
16856        if( flag_rtz && flag_dp ){
16857          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
16858          assert( bufpt>buf );
16859          if( bufpt[-1]=='.' ){
16860            if( flag_altform2 ){
16861              *(bufpt++) = '0';
16862            }else{
16863              *(--bufpt) = 0;
16864            }
16865          }
16866        }
16867        /* Add the "eNNN" suffix */
16868        if( flag_exp || xtype==etEXP ){
16869          *(bufpt++) = aDigits[infop->charset];
16870          if( exp<0 ){
16871            *(bufpt++) = '-'; exp = -exp;
16872          }else{
16873            *(bufpt++) = '+';
16874          }
16875          if( exp>=100 ){
16876            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
16877            exp %= 100;
16878          }
16879          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
16880          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
16881        }
16882        *bufpt = 0;
16883
16884        /* The converted number is in buf[] and zero terminated. Output it.
16885        ** Note that the number is in the usual order, not reversed as with
16886        ** integer conversions. */
16887        length = (int)(bufpt-buf);
16888        bufpt = buf;
16889
16890        /* Special case:  Add leading zeros if the flag_zeropad flag is
16891        ** set and we are not left justified */
16892        if( flag_zeropad && !flag_leftjustify && length < width){
16893          int i;
16894          int nPad = width - length;
16895          for(i=width; i>=nPad; i--){
16896            bufpt[i] = bufpt[i-nPad];
16897          }
16898          i = prefix!=0;
16899          while( nPad-- ) bufpt[i++] = '0';
16900          length = width;
16901        }
16902#endif
16903        break;
16904      case etSIZE:
16905        *(va_arg(ap,int*)) = pAccum->nChar;
16906        length = width = 0;
16907        break;
16908      case etPERCENT:
16909        buf[0] = '%';
16910        bufpt = buf;
16911        length = 1;
16912        break;
16913      case etCHARX:
16914        c = va_arg(ap,int);
16915        buf[0] = (char)c;
16916        if( precision>=0 ){
16917          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
16918          length = precision;
16919        }else{
16920          length =1;
16921        }
16922        bufpt = buf;
16923        break;
16924      case etSTRING:
16925      case etDYNSTRING:
16926        bufpt = va_arg(ap,char*);
16927        if( bufpt==0 ){
16928          bufpt = "";
16929        }else if( xtype==etDYNSTRING ){
16930          zExtra = bufpt;
16931        }
16932        if( precision>=0 ){
16933          for(length=0; length<precision && bufpt[length]; length++){}
16934        }else{
16935          length = sqlite3Strlen30(bufpt);
16936        }
16937        break;
16938      case etSQLESCAPE:
16939      case etSQLESCAPE2:
16940      case etSQLESCAPE3: {
16941        int i, j, k, n, isnull;
16942        int needQuote;
16943        char ch;
16944        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
16945        char *escarg = va_arg(ap,char*);
16946        isnull = escarg==0;
16947        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
16948        k = precision;
16949        for(i=n=0; (ch=escarg[i])!=0 && k!=0; i++, k--){
16950          if( ch==q )  n++;
16951        }
16952        needQuote = !isnull && xtype==etSQLESCAPE2;
16953        n += i + 1 + needQuote*2;
16954        if( n>etBUFSIZE ){
16955          bufpt = zExtra = sqlite3Malloc( n );
16956          if( bufpt==0 ){
16957            pAccum->mallocFailed = 1;
16958            return;
16959          }
16960        }else{
16961          bufpt = buf;
16962        }
16963        j = 0;
16964        if( needQuote ) bufpt[j++] = q;
16965        k = i;
16966        for(i=0; i<k; i++){
16967          bufpt[j++] = ch = escarg[i];
16968          if( ch==q ) bufpt[j++] = ch;
16969        }
16970        if( needQuote ) bufpt[j++] = q;
16971        bufpt[j] = 0;
16972        length = j;
16973        /* The precision in %q and %Q means how many input characters to
16974        ** consume, not the length of the output...
16975        ** if( precision>=0 && precision<length ) length = precision; */
16976        break;
16977      }
16978      case etTOKEN: {
16979        Token *pToken = va_arg(ap, Token*);
16980        if( pToken ){
16981          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
16982        }
16983        length = width = 0;
16984        break;
16985      }
16986      case etSRCLIST: {
16987        SrcList *pSrc = va_arg(ap, SrcList*);
16988        int k = va_arg(ap, int);
16989        struct SrcList_item *pItem = &pSrc->a[k];
16990        assert( k>=0 && k<pSrc->nSrc );
16991        if( pItem->zDatabase ){
16992          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
16993          sqlite3StrAccumAppend(pAccum, ".", 1);
16994        }
16995        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
16996        length = width = 0;
16997        break;
16998      }
16999      default: {
17000        assert( xtype==etINVALID );
17001        return;
17002      }
17003    }/* End switch over the format type */
17004    /*
17005    ** The text of the conversion is pointed to by "bufpt" and is
17006    ** "length" characters long.  The field width is "width".  Do
17007    ** the output.
17008    */
17009    if( !flag_leftjustify ){
17010      register int nspace;
17011      nspace = width-length;
17012      if( nspace>0 ){
17013        appendSpace(pAccum, nspace);
17014      }
17015    }
17016    if( length>0 ){
17017      sqlite3StrAccumAppend(pAccum, bufpt, length);
17018    }
17019    if( flag_leftjustify ){
17020      register int nspace;
17021      nspace = width-length;
17022      if( nspace>0 ){
17023        appendSpace(pAccum, nspace);
17024      }
17025    }
17026    if( zExtra ){
17027      sqlite3_free(zExtra);
17028    }
17029  }/* End for loop over the format string */
17030} /* End of function */
17031
17032/*
17033** Append N bytes of text from z to the StrAccum object.
17034*/
17035SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17036  assert( z!=0 || N==0 );
17037  if( p->tooBig | p->mallocFailed ){
17038    testcase(p->tooBig);
17039    testcase(p->mallocFailed);
17040    return;
17041  }
17042  if( N<0 ){
17043    N = sqlite3Strlen30(z);
17044  }
17045  if( N==0 || NEVER(z==0) ){
17046    return;
17047  }
17048  if( p->nChar+N >= p->nAlloc ){
17049    char *zNew;
17050    if( !p->useMalloc ){
17051      p->tooBig = 1;
17052      N = p->nAlloc - p->nChar - 1;
17053      if( N<=0 ){
17054        return;
17055      }
17056    }else{
17057      i64 szNew = p->nChar;
17058      szNew += N + 1;
17059      if( szNew > p->mxAlloc ){
17060        sqlite3StrAccumReset(p);
17061        p->tooBig = 1;
17062        return;
17063      }else{
17064        p->nAlloc = (int)szNew;
17065      }
17066      zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
17067      if( zNew ){
17068        memcpy(zNew, p->zText, p->nChar);
17069        sqlite3StrAccumReset(p);
17070        p->zText = zNew;
17071      }else{
17072        p->mallocFailed = 1;
17073        sqlite3StrAccumReset(p);
17074        return;
17075      }
17076    }
17077  }
17078  memcpy(&p->zText[p->nChar], z, N);
17079  p->nChar += N;
17080}
17081
17082/*
17083** Finish off a string by making sure it is zero-terminated.
17084** Return a pointer to the resulting string.  Return a NULL
17085** pointer if any kind of error was encountered.
17086*/
17087SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
17088  if( p->zText ){
17089    p->zText[p->nChar] = 0;
17090    if( p->useMalloc && p->zText==p->zBase ){
17091      p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
17092      if( p->zText ){
17093        memcpy(p->zText, p->zBase, p->nChar+1);
17094      }else{
17095        p->mallocFailed = 1;
17096      }
17097    }
17098  }
17099  return p->zText;
17100}
17101
17102/*
17103** Reset an StrAccum string.  Reclaim all malloced memory.
17104*/
17105SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
17106  if( p->zText!=p->zBase ){
17107    sqlite3DbFree(p->db, p->zText);
17108  }
17109  p->zText = 0;
17110}
17111
17112/*
17113** Initialize a string accumulator
17114*/
17115SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
17116  p->zText = p->zBase = zBase;
17117  p->db = 0;
17118  p->nChar = 0;
17119  p->nAlloc = n;
17120  p->mxAlloc = mx;
17121  p->useMalloc = 1;
17122  p->tooBig = 0;
17123  p->mallocFailed = 0;
17124}
17125
17126/*
17127** Print into memory obtained from sqliteMalloc().  Use the internal
17128** %-conversion extensions.
17129*/
17130SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
17131  char *z;
17132  char zBase[SQLITE_PRINT_BUF_SIZE];
17133  StrAccum acc;
17134  assert( db!=0 );
17135  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
17136                      db->aLimit[SQLITE_LIMIT_LENGTH]);
17137  acc.db = db;
17138  sqlite3VXPrintf(&acc, 1, zFormat, ap);
17139  z = sqlite3StrAccumFinish(&acc);
17140  if( acc.mallocFailed ){
17141    db->mallocFailed = 1;
17142  }
17143  return z;
17144}
17145
17146/*
17147** Print into memory obtained from sqliteMalloc().  Use the internal
17148** %-conversion extensions.
17149*/
17150SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
17151  va_list ap;
17152  char *z;
17153  va_start(ap, zFormat);
17154  z = sqlite3VMPrintf(db, zFormat, ap);
17155  va_end(ap);
17156  return z;
17157}
17158
17159/*
17160** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
17161** the string and before returnning.  This routine is intended to be used
17162** to modify an existing string.  For example:
17163**
17164**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
17165**
17166*/
17167SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
17168  va_list ap;
17169  char *z;
17170  va_start(ap, zFormat);
17171  z = sqlite3VMPrintf(db, zFormat, ap);
17172  va_end(ap);
17173  sqlite3DbFree(db, zStr);
17174  return z;
17175}
17176
17177/*
17178** Print into memory obtained from sqlite3_malloc().  Omit the internal
17179** %-conversion extensions.
17180*/
17181SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
17182  char *z;
17183  char zBase[SQLITE_PRINT_BUF_SIZE];
17184  StrAccum acc;
17185#ifndef SQLITE_OMIT_AUTOINIT
17186  if( sqlite3_initialize() ) return 0;
17187#endif
17188  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
17189  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17190  z = sqlite3StrAccumFinish(&acc);
17191  return z;
17192}
17193
17194/*
17195** Print into memory obtained from sqlite3_malloc()().  Omit the internal
17196** %-conversion extensions.
17197*/
17198SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
17199  va_list ap;
17200  char *z;
17201#ifndef SQLITE_OMIT_AUTOINIT
17202  if( sqlite3_initialize() ) return 0;
17203#endif
17204  va_start(ap, zFormat);
17205  z = sqlite3_vmprintf(zFormat, ap);
17206  va_end(ap);
17207  return z;
17208}
17209
17210/*
17211** sqlite3_snprintf() works like snprintf() except that it ignores the
17212** current locale settings.  This is important for SQLite because we
17213** are not able to use a "," as the decimal point in place of "." as
17214** specified by some locales.
17215*/
17216SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
17217  char *z;
17218  va_list ap;
17219  StrAccum acc;
17220
17221  if( n<=0 ){
17222    return zBuf;
17223  }
17224  sqlite3StrAccumInit(&acc, zBuf, n, 0);
17225  acc.useMalloc = 0;
17226  va_start(ap,zFormat);
17227  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17228  va_end(ap);
17229  z = sqlite3StrAccumFinish(&acc);
17230  return z;
17231}
17232
17233#if defined(SQLITE_DEBUG)
17234/*
17235** A version of printf() that understands %lld.  Used for debugging.
17236** The printf() built into some versions of windows does not understand %lld
17237** and segfaults if you give it a long long int.
17238*/
17239SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
17240  va_list ap;
17241  StrAccum acc;
17242  char zBuf[500];
17243  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
17244  acc.useMalloc = 0;
17245  va_start(ap,zFormat);
17246  sqlite3VXPrintf(&acc, 0, zFormat, ap);
17247  va_end(ap);
17248  sqlite3StrAccumFinish(&acc);
17249  fprintf(stdout,"%s", zBuf);
17250  fflush(stdout);
17251}
17252#endif
17253
17254#ifndef SQLITE_OMIT_TRACE
17255/*
17256** variable-argument wrapper around sqlite3VXPrintf().
17257*/
17258SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
17259  va_list ap;
17260  va_start(ap,zFormat);
17261  sqlite3VXPrintf(p, 1, zFormat, ap);
17262  va_end(ap);
17263}
17264#endif
17265
17266/************** End of printf.c **********************************************/
17267/************** Begin file random.c ******************************************/
17268/*
17269** 2001 September 15
17270**
17271** The author disclaims copyright to this source code.  In place of
17272** a legal notice, here is a blessing:
17273**
17274**    May you do good and not evil.
17275**    May you find forgiveness for yourself and forgive others.
17276**    May you share freely, never taking more than you give.
17277**
17278*************************************************************************
17279** This file contains code to implement a pseudo-random number
17280** generator (PRNG) for SQLite.
17281**
17282** Random numbers are used by some of the database backends in order
17283** to generate random integer keys for tables or random filenames.
17284*/
17285
17286
17287/* All threads share a single random number generator.
17288** This structure is the current state of the generator.
17289*/
17290static SQLITE_WSD struct sqlite3PrngType {
17291  unsigned char isInit;          /* True if initialized */
17292  unsigned char i, j;            /* State variables */
17293  unsigned char s[256];          /* State variables */
17294} sqlite3Prng;
17295
17296/*
17297** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
17298** must be held while executing this routine.
17299**
17300** Why not just use a library random generator like lrand48() for this?
17301** Because the OP_NewRowid opcode in the VDBE depends on having a very
17302** good source of random numbers.  The lrand48() library function may
17303** well be good enough.  But maybe not.  Or maybe lrand48() has some
17304** subtle problems on some systems that could cause problems.  It is hard
17305** to know.  To minimize the risk of problems due to bad lrand48()
17306** implementations, SQLite uses this random number generator based
17307** on RC4, which we know works very well.
17308**
17309** (Later):  Actually, OP_NewRowid does not depend on a good source of
17310** randomness any more.  But we will leave this code in all the same.
17311*/
17312static u8 randomByte(void){
17313  unsigned char t;
17314
17315
17316  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
17317  ** state vector.  If writable static data is unsupported on the target,
17318  ** we have to locate the state vector at run-time.  In the more common
17319  ** case where writable static data is supported, wsdPrng can refer directly
17320  ** to the "sqlite3Prng" state vector declared above.
17321  */
17322#ifdef SQLITE_OMIT_WSD
17323  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
17324# define wsdPrng p[0]
17325#else
17326# define wsdPrng sqlite3Prng
17327#endif
17328
17329
17330  /* Initialize the state of the random number generator once,
17331  ** the first time this routine is called.  The seed value does
17332  ** not need to contain a lot of randomness since we are not
17333  ** trying to do secure encryption or anything like that...
17334  **
17335  ** Nothing in this file or anywhere else in SQLite does any kind of
17336  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
17337  ** number generator) not as an encryption device.
17338  */
17339  if( !wsdPrng.isInit ){
17340    int i;
17341    char k[256];
17342    wsdPrng.j = 0;
17343    wsdPrng.i = 0;
17344    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
17345    for(i=0; i<256; i++){
17346      wsdPrng.s[i] = (u8)i;
17347    }
17348    for(i=0; i<256; i++){
17349      wsdPrng.j += wsdPrng.s[i] + k[i];
17350      t = wsdPrng.s[wsdPrng.j];
17351      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
17352      wsdPrng.s[i] = t;
17353    }
17354    wsdPrng.isInit = 1;
17355  }
17356
17357  /* Generate and return single random byte
17358  */
17359  wsdPrng.i++;
17360  t = wsdPrng.s[wsdPrng.i];
17361  wsdPrng.j += t;
17362  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
17363  wsdPrng.s[wsdPrng.j] = t;
17364  t += wsdPrng.s[wsdPrng.i];
17365  return wsdPrng.s[t];
17366}
17367
17368/*
17369** Return N random bytes.
17370*/
17371SQLITE_API void sqlite3_randomness(int N, void *pBuf){
17372  unsigned char *zBuf = pBuf;
17373#if SQLITE_THREADSAFE
17374  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
17375#endif
17376  sqlite3_mutex_enter(mutex);
17377  while( N-- ){
17378    *(zBuf++) = randomByte();
17379  }
17380  sqlite3_mutex_leave(mutex);
17381}
17382
17383#ifndef SQLITE_OMIT_BUILTIN_TEST
17384/*
17385** For testing purposes, we sometimes want to preserve the state of
17386** PRNG and restore the PRNG to its saved state at a later time, or
17387** to reset the PRNG to its initial state.  These routines accomplish
17388** those tasks.
17389**
17390** The sqlite3_test_control() interface calls these routines to
17391** control the PRNG.
17392*/
17393static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
17394SQLITE_PRIVATE void sqlite3PrngSaveState(void){
17395  memcpy(
17396    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17397    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17398    sizeof(sqlite3Prng)
17399  );
17400}
17401SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
17402  memcpy(
17403    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17404    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17405    sizeof(sqlite3Prng)
17406  );
17407}
17408SQLITE_PRIVATE void sqlite3PrngResetState(void){
17409  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
17410}
17411#endif /* SQLITE_OMIT_BUILTIN_TEST */
17412
17413/************** End of random.c **********************************************/
17414/************** Begin file utf.c *********************************************/
17415/*
17416** 2004 April 13
17417**
17418** The author disclaims copyright to this source code.  In place of
17419** a legal notice, here is a blessing:
17420**
17421**    May you do good and not evil.
17422**    May you find forgiveness for yourself and forgive others.
17423**    May you share freely, never taking more than you give.
17424**
17425*************************************************************************
17426** This file contains routines used to translate between UTF-8,
17427** UTF-16, UTF-16BE, and UTF-16LE.
17428**
17429** Notes on UTF-8:
17430**
17431**   Byte-0    Byte-1    Byte-2    Byte-3    Value
17432**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
17433**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
17434**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
17435**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
17436**
17437**
17438** Notes on UTF-16:  (with wwww+1==uuuuu)
17439**
17440**      Word-0               Word-1          Value
17441**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
17442**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
17443**
17444**
17445** BOM or Byte Order Mark:
17446**     0xff 0xfe   little-endian utf-16 follows
17447**     0xfe 0xff   big-endian utf-16 follows
17448**
17449*/
17450/************** Include vdbeInt.h in the middle of utf.c *********************/
17451/************** Begin file vdbeInt.h *****************************************/
17452/*
17453** 2003 September 6
17454**
17455** The author disclaims copyright to this source code.  In place of
17456** a legal notice, here is a blessing:
17457**
17458**    May you do good and not evil.
17459**    May you find forgiveness for yourself and forgive others.
17460**    May you share freely, never taking more than you give.
17461**
17462*************************************************************************
17463** This is the header file for information that is private to the
17464** VDBE.  This information used to all be at the top of the single
17465** source code file "vdbe.c".  When that file became too big (over
17466** 6000 lines long) it was split up into several smaller files and
17467** this header information was factored out.
17468*/
17469#ifndef _VDBEINT_H_
17470#define _VDBEINT_H_
17471
17472/*
17473** SQL is translated into a sequence of instructions to be
17474** executed by a virtual machine.  Each instruction is an instance
17475** of the following structure.
17476*/
17477typedef struct VdbeOp Op;
17478
17479/*
17480** Boolean values
17481*/
17482typedef unsigned char Bool;
17483
17484/*
17485** A cursor is a pointer into a single BTree within a database file.
17486** The cursor can seek to a BTree entry with a particular key, or
17487** loop over all entries of the Btree.  You can also insert new BTree
17488** entries or retrieve the key or data from the entry that the cursor
17489** is currently pointing to.
17490**
17491** Every cursor that the virtual machine has open is represented by an
17492** instance of the following structure.
17493**
17494** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
17495** really a single row that represents the NEW or OLD pseudo-table of
17496** a row trigger.  The data for the row is stored in VdbeCursor.pData and
17497** the rowid is in VdbeCursor.iKey.
17498*/
17499struct VdbeCursor {
17500  BtCursor *pCursor;    /* The cursor structure of the backend */
17501  int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
17502  i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
17503  Bool zeroed;          /* True if zeroed out and ready for reuse */
17504  Bool rowidIsValid;    /* True if lastRowid is valid */
17505  Bool atFirst;         /* True if pointing to first entry */
17506  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
17507  Bool nullRow;         /* True if pointing to a row with no data */
17508  Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
17509  Bool isTable;         /* True if a table requiring integer keys */
17510  Bool isIndex;         /* True if an index containing keys only - no data */
17511  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
17512  Btree *pBt;           /* Separate file holding temporary table */
17513  int pseudoTableReg;   /* Register holding pseudotable content. */
17514  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
17515  int nField;           /* Number of fields in the header */
17516  i64 seqCount;         /* Sequence counter */
17517  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
17518  const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
17519
17520  /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
17521  ** OP_IsUnique opcode on this cursor. */
17522  int seekResult;
17523
17524  /* Cached information about the header for the data record that the
17525  ** cursor is currently pointing to.  Only valid if cacheStatus matches
17526  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
17527  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
17528  ** the cache is out of date.
17529  **
17530  ** aRow might point to (ephemeral) data for the current row, or it might
17531  ** be NULL.
17532  */
17533  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
17534  int payloadSize;      /* Total number of bytes in the record */
17535  u32 *aType;           /* Type values for all entries in the record */
17536  u32 *aOffset;         /* Cached offsets to the start of each columns data */
17537  u8 *aRow;             /* Data for the current row, if all on one page */
17538};
17539typedef struct VdbeCursor VdbeCursor;
17540
17541/*
17542** When a sub-program is executed (OP_Program), a structure of this type
17543** is allocated to store the current value of the program counter, as
17544** well as the current memory cell array and various other frame specific
17545** values stored in the Vdbe struct. When the sub-program is finished,
17546** these values are copied back to the Vdbe from the VdbeFrame structure,
17547** restoring the state of the VM to as it was before the sub-program
17548** began executing.
17549**
17550** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
17551** is the parent of the current frame, or zero if the current frame
17552** is the main Vdbe program.
17553*/
17554typedef struct VdbeFrame VdbeFrame;
17555struct VdbeFrame {
17556  Vdbe *v;                /* VM this frame belongs to */
17557  int pc;                 /* Program Counter */
17558  Op *aOp;                /* Program instructions */
17559  int nOp;                /* Size of aOp array */
17560  Mem *aMem;              /* Array of memory cells */
17561  int nMem;               /* Number of entries in aMem */
17562  VdbeCursor **apCsr;     /* Element of Vdbe cursors */
17563  u16 nCursor;            /* Number of entries in apCsr */
17564  void *token;            /* Copy of SubProgram.token */
17565  int nChildMem;          /* Number of memory cells for child frame */
17566  int nChildCsr;          /* Number of cursors for child frame */
17567  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
17568  int nChange;            /* Statement changes (Vdbe.nChanges)     */
17569  VdbeFrame *pParent;     /* Parent of this frame */
17570};
17571
17572#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
17573
17574/*
17575** A value for VdbeCursor.cacheValid that means the cache is always invalid.
17576*/
17577#define CACHE_STALE 0
17578
17579/*
17580** Internally, the vdbe manipulates nearly all SQL values as Mem
17581** structures. Each Mem struct may cache multiple representations (string,
17582** integer etc.) of the same value.  A value (and therefore Mem structure)
17583** has the following properties:
17584**
17585** Each value has a manifest type. The manifest type of the value stored
17586** in a Mem struct is returned by the MemType(Mem*) macro. The type is
17587** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
17588** SQLITE_BLOB.
17589*/
17590struct Mem {
17591  union {
17592    i64 i;              /* Integer value. */
17593    int nZero;          /* Used when bit MEM_Zero is set in flags */
17594    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
17595    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
17596    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
17597  } u;
17598  double r;           /* Real value */
17599  sqlite3 *db;        /* The associated database connection */
17600  char *z;            /* String or BLOB value */
17601  int n;              /* Number of characters in string value, excluding '\0' */
17602  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17603  u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
17604  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17605  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
17606  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
17607};
17608
17609/* One or more of the following flags are set to indicate the validOK
17610** representations of the value stored in the Mem struct.
17611**
17612** If the MEM_Null flag is set, then the value is an SQL NULL value.
17613** No other flags may be set in this case.
17614**
17615** If the MEM_Str flag is set then Mem.z points at a string representation.
17616** Usually this is encoded in the same unicode encoding as the main
17617** database (see below for exceptions). If the MEM_Term flag is also
17618** set, then the string is nul terminated. The MEM_Int and MEM_Real
17619** flags may coexist with the MEM_Str flag.
17620**
17621** Multiple of these values can appear in Mem.flags.  But only one
17622** at a time can appear in Mem.type.
17623*/
17624#define MEM_Null      0x0001   /* Value is NULL */
17625#define MEM_Str       0x0002   /* Value is a string */
17626#define MEM_Int       0x0004   /* Value is an integer */
17627#define MEM_Real      0x0008   /* Value is a real number */
17628#define MEM_Blob      0x0010   /* Value is a BLOB */
17629#define MEM_RowSet    0x0020   /* Value is a RowSet object */
17630#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
17631#define MEM_TypeMask  0x00ff   /* Mask of type bits */
17632
17633/* Whenever Mem contains a valid string or blob representation, one of
17634** the following flags must be set to determine the memory management
17635** policy for Mem.z.  The MEM_Term flag tells us whether or not the
17636** string is \000 or \u0000 terminated
17637*/
17638#define MEM_Term      0x0200   /* String rep is nul terminated */
17639#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
17640#define MEM_Static    0x0800   /* Mem.z points to a static string */
17641#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
17642#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
17643#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
17644
17645#ifdef SQLITE_OMIT_INCRBLOB
17646  #undef MEM_Zero
17647  #define MEM_Zero 0x0000
17648#endif
17649
17650
17651/*
17652** Clear any existing type flags from a Mem and replace them with f
17653*/
17654#define MemSetTypeFlag(p, f) \
17655   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
17656
17657
17658/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
17659** additional information about auxiliary information bound to arguments
17660** of the function.  This is used to implement the sqlite3_get_auxdata()
17661** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
17662** that can be associated with a constant argument to a function.  This
17663** allows functions such as "regexp" to compile their constant regular
17664** expression argument once and reused the compiled code for multiple
17665** invocations.
17666*/
17667struct VdbeFunc {
17668  FuncDef *pFunc;               /* The definition of the function */
17669  int nAux;                     /* Number of entries allocated for apAux[] */
17670  struct AuxData {
17671    void *pAux;                   /* Aux data for the i-th argument */
17672    void (*xDelete)(void *);      /* Destructor for the aux data */
17673  } apAux[1];                   /* One slot for each function argument */
17674};
17675
17676/*
17677** The "context" argument for a installable function.  A pointer to an
17678** instance of this structure is the first argument to the routines used
17679** implement the SQL functions.
17680**
17681** There is a typedef for this structure in sqlite.h.  So all routines,
17682** even the public interface to SQLite, can use a pointer to this structure.
17683** But this file is the only place where the internal details of this
17684** structure are known.
17685**
17686** This structure is defined inside of vdbeInt.h because it uses substructures
17687** (Mem) which are only defined there.
17688*/
17689struct sqlite3_context {
17690  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
17691  VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
17692  Mem s;                /* The return value is stored here */
17693  Mem *pMem;            /* Memory cell used to store aggregate context */
17694  int isError;          /* Error code returned by the function. */
17695  CollSeq *pColl;       /* Collating sequence */
17696};
17697
17698/*
17699** A Set structure is used for quick testing to see if a value
17700** is part of a small set.  Sets are used to implement code like
17701** this:
17702**            x.y IN ('hi','hoo','hum')
17703*/
17704typedef struct Set Set;
17705struct Set {
17706  Hash hash;             /* A set is just a hash table */
17707  HashElem *prev;        /* Previously accessed hash elemen */
17708};
17709
17710/*
17711** An instance of the virtual machine.  This structure contains the complete
17712** state of the virtual machine.
17713**
17714** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
17715** is really a pointer to an instance of this structure.
17716**
17717** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
17718** any virtual table method invocations made by the vdbe program. It is
17719** set to 2 for xDestroy method calls and 1 for all other methods. This
17720** variable is used for two purposes: to allow xDestroy methods to execute
17721** "DROP TABLE" statements and to prevent some nasty side effects of
17722** malloc failure when SQLite is invoked recursively by a virtual table
17723** method function.
17724*/
17725struct Vdbe {
17726  sqlite3 *db;            /* The database connection that owns this statement */
17727  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
17728  int nOp;                /* Number of instructions in the program */
17729  int nOpAlloc;           /* Number of slots allocated for aOp[] */
17730  Op *aOp;                /* Space to hold the virtual machine's program */
17731  int nLabel;             /* Number of labels used */
17732  int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
17733  int *aLabel;            /* Space to hold the labels */
17734  Mem **apArg;            /* Arguments to currently executing user function */
17735  Mem *aColName;          /* Column names to return */
17736  Mem *pResultSet;        /* Pointer to an array of results */
17737  u16 nResColumn;         /* Number of columns in one row of the result set */
17738  u16 nCursor;            /* Number of slots in apCsr[] */
17739  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
17740  u8 errorAction;         /* Recovery action to do in case of an error */
17741  u8 okVar;               /* True if azVar[] has been initialized */
17742  ynVar nVar;             /* Number of entries in aVar[] */
17743  Mem *aVar;              /* Values for the OP_Variable opcode. */
17744  char **azVar;           /* Name of variables */
17745  u32 magic;              /* Magic number for sanity checking */
17746  int nMem;               /* Number of memory locations currently allocated */
17747  Mem *aMem;              /* The memory locations */
17748  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
17749  int pc;                 /* The program counter */
17750  int rc;                 /* Value to return */
17751  char *zErrMsg;          /* Error message written here */
17752  u8 explain;             /* True if EXPLAIN present on SQL command */
17753  u8 changeCntOn;         /* True to update the change-counter */
17754  u8 expired;             /* True if the VM needs to be recompiled */
17755  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
17756  u8 inVtabMethod;        /* See comments above */
17757  u8 usesStmtJournal;     /* True if uses a statement journal */
17758  u8 readOnly;            /* True for read-only statements */
17759  u8 isPrepareV2;         /* True if prepared with prepare_v2() */
17760  int nChange;            /* Number of db changes made since last reset */
17761  int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
17762  i64 startTime;          /* Time when query started - used for profiling */
17763  BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
17764  int aCounter[2];        /* Counters used by sqlite3_stmt_status() */
17765  char *zSql;             /* Text of the SQL statement that generated this */
17766  void *pFree;            /* Free this when deleting the vdbe */
17767  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
17768  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
17769  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
17770#ifdef SQLITE_DEBUG
17771  FILE *trace;            /* Write an execution trace here, if not NULL */
17772#endif
17773  VdbeFrame *pFrame;      /* Parent frame */
17774  int nFrame;             /* Number of frames in pFrame list */
17775  u32 expmask;            /* Binding to these vars invalidates VM */
17776};
17777
17778/*
17779** The following are allowed values for Vdbe.magic
17780*/
17781#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
17782#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
17783#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
17784#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
17785
17786/*
17787** Function prototypes
17788*/
17789SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
17790void sqliteVdbePopStack(Vdbe*,int);
17791SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
17792#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
17793SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
17794#endif
17795SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
17796SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
17797SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
17798SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
17799SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
17800
17801int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
17802SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
17803SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
17804SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
17805SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
17806SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
17807SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
17808SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
17809SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
17810SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
17811SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
17812SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
17813SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
17814SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
17815SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
17816SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
17817SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
17818SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
17819SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
17820SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
17821SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
17822SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
17823SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
17824SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
17825SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
17826SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
17827SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
17828SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
17829SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
17830SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
17831SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
17832SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
17833SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
17834SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
17835SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
17836SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
17837SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
17838
17839#ifndef SQLITE_OMIT_FOREIGN_KEY
17840SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
17841#else
17842# define sqlite3VdbeCheckFk(p,i) 0
17843#endif
17844
17845#ifndef SQLITE_OMIT_SHARED_CACHE
17846SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
17847#else
17848# define sqlite3VdbeMutexArrayEnter(p)
17849#endif
17850
17851SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
17852#ifdef SQLITE_DEBUG
17853SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
17854SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
17855#endif
17856SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
17857
17858#ifndef SQLITE_OMIT_INCRBLOB
17859SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
17860#else
17861  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
17862#endif
17863
17864#endif /* !defined(_VDBEINT_H_) */
17865
17866/************** End of vdbeInt.h *********************************************/
17867/************** Continuing where we left off in utf.c ************************/
17868
17869#ifndef SQLITE_AMALGAMATION
17870/*
17871** The following constant value is used by the SQLITE_BIGENDIAN and
17872** SQLITE_LITTLEENDIAN macros.
17873*/
17874SQLITE_PRIVATE const int sqlite3one = 1;
17875#endif /* SQLITE_AMALGAMATION */
17876
17877/*
17878** This lookup table is used to help decode the first byte of
17879** a multi-byte UTF8 character.
17880*/
17881static const unsigned char sqlite3Utf8Trans1[] = {
17882  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17883  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
17884  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
17885  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
17886  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17887  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
17888  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
17889  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
17890};
17891
17892
17893#define WRITE_UTF8(zOut, c) {                          \
17894  if( c<0x00080 ){                                     \
17895    *zOut++ = (u8)(c&0xFF);                            \
17896  }                                                    \
17897  else if( c<0x00800 ){                                \
17898    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
17899    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17900  }                                                    \
17901  else if( c<0x10000 ){                                \
17902    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
17903    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
17904    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17905  }else{                                               \
17906    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
17907    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
17908    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
17909    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
17910  }                                                    \
17911}
17912
17913#define WRITE_UTF16LE(zOut, c) {                                    \
17914  if( c<=0xFFFF ){                                                  \
17915    *zOut++ = (u8)(c&0x00FF);                                       \
17916    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
17917  }else{                                                            \
17918    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
17919    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
17920    *zOut++ = (u8)(c&0x00FF);                                       \
17921    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
17922  }                                                                 \
17923}
17924
17925#define WRITE_UTF16BE(zOut, c) {                                    \
17926  if( c<=0xFFFF ){                                                  \
17927    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
17928    *zOut++ = (u8)(c&0x00FF);                                       \
17929  }else{                                                            \
17930    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
17931    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
17932    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
17933    *zOut++ = (u8)(c&0x00FF);                                       \
17934  }                                                                 \
17935}
17936
17937#define READ_UTF16LE(zIn, TERM, c){                                   \
17938  c = (*zIn++);                                                       \
17939  c += ((*zIn++)<<8);                                                 \
17940  if( c>=0xD800 && c<0xE000 && TERM ){                                \
17941    int c2 = (*zIn++);                                                \
17942    c2 += ((*zIn++)<<8);                                              \
17943    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
17944  }                                                                   \
17945}
17946
17947#define READ_UTF16BE(zIn, TERM, c){                                   \
17948  c = ((*zIn++)<<8);                                                  \
17949  c += (*zIn++);                                                      \
17950  if( c>=0xD800 && c<0xE000 && TERM ){                                \
17951    int c2 = ((*zIn++)<<8);                                           \
17952    c2 += (*zIn++);                                                   \
17953    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
17954  }                                                                   \
17955}
17956
17957/*
17958** Translate a single UTF-8 character.  Return the unicode value.
17959**
17960** During translation, assume that the byte that zTerm points
17961** is a 0x00.
17962**
17963** Write a pointer to the next unread byte back into *pzNext.
17964**
17965** Notes On Invalid UTF-8:
17966**
17967**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
17968**     be encoded as a multi-byte character.  Any multi-byte character that
17969**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
17970**
17971**  *  This routine never allows a UTF16 surrogate value to be encoded.
17972**     If a multi-byte character attempts to encode a value between
17973**     0xd800 and 0xe000 then it is rendered as 0xfffd.
17974**
17975**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
17976**     byte of a character are interpreted as single-byte characters
17977**     and rendered as themselves even though they are technically
17978**     invalid characters.
17979**
17980**  *  This routine accepts an infinite number of different UTF8 encodings
17981**     for unicode values 0x80 and greater.  It do not change over-length
17982**     encodings to 0xfffd as some systems recommend.
17983*/
17984#define READ_UTF8(zIn, zTerm, c)                           \
17985  c = *(zIn++);                                            \
17986  if( c>=0xc0 ){                                           \
17987    c = sqlite3Utf8Trans1[c-0xc0];                         \
17988    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
17989      c = (c<<6) + (0x3f & *(zIn++));                      \
17990    }                                                      \
17991    if( c<0x80                                             \
17992        || (c&0xFFFFF800)==0xD800                          \
17993        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
17994  }
17995SQLITE_PRIVATE int sqlite3Utf8Read(
17996  const unsigned char *zIn,       /* First byte of UTF-8 character */
17997  const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
17998){
17999  int c;
18000
18001  /* Same as READ_UTF8() above but without the zTerm parameter.
18002  ** For this routine, we assume the UTF8 string is always zero-terminated.
18003  */
18004  c = *(zIn++);
18005  if( c>=0xc0 ){
18006    c = sqlite3Utf8Trans1[c-0xc0];
18007    while( (*zIn & 0xc0)==0x80 ){
18008      c = (c<<6) + (0x3f & *(zIn++));
18009    }
18010    if( c<0x80
18011        || (c&0xFFFFF800)==0xD800
18012        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
18013  }
18014  *pzNext = zIn;
18015  return c;
18016}
18017
18018
18019
18020
18021/*
18022** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
18023** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
18024*/
18025/* #define TRANSLATE_TRACE 1 */
18026
18027#ifndef SQLITE_OMIT_UTF16
18028/*
18029** This routine transforms the internal text encoding used by pMem to
18030** desiredEnc. It is an error if the string is already of the desired
18031** encoding, or if *pMem does not contain a string value.
18032*/
18033SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
18034  int len;                    /* Maximum length of output string in bytes */
18035  unsigned char *zOut;                  /* Output buffer */
18036  unsigned char *zIn;                   /* Input iterator */
18037  unsigned char *zTerm;                 /* End of input */
18038  unsigned char *z;                     /* Output iterator */
18039  unsigned int c;
18040
18041  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
18042  assert( pMem->flags&MEM_Str );
18043  assert( pMem->enc!=desiredEnc );
18044  assert( pMem->enc!=0 );
18045  assert( pMem->n>=0 );
18046
18047#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18048  {
18049    char zBuf[100];
18050    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18051    fprintf(stderr, "INPUT:  %s\n", zBuf);
18052  }
18053#endif
18054
18055  /* If the translation is between UTF-16 little and big endian, then
18056  ** all that is required is to swap the byte order. This case is handled
18057  ** differently from the others.
18058  */
18059  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
18060    u8 temp;
18061    int rc;
18062    rc = sqlite3VdbeMemMakeWriteable(pMem);
18063    if( rc!=SQLITE_OK ){
18064      assert( rc==SQLITE_NOMEM );
18065      return SQLITE_NOMEM;
18066    }
18067    zIn = (u8*)pMem->z;
18068    zTerm = &zIn[pMem->n&~1];
18069    while( zIn<zTerm ){
18070      temp = *zIn;
18071      *zIn = *(zIn+1);
18072      zIn++;
18073      *zIn++ = temp;
18074    }
18075    pMem->enc = desiredEnc;
18076    goto translate_out;
18077  }
18078
18079  /* Set len to the maximum number of bytes required in the output buffer. */
18080  if( desiredEnc==SQLITE_UTF8 ){
18081    /* When converting from UTF-16, the maximum growth results from
18082    ** translating a 2-byte character to a 4-byte UTF-8 character.
18083    ** A single byte is required for the output string
18084    ** nul-terminator.
18085    */
18086    pMem->n &= ~1;
18087    len = pMem->n * 2 + 1;
18088  }else{
18089    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
18090    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
18091    ** character. Two bytes are required in the output buffer for the
18092    ** nul-terminator.
18093    */
18094    len = pMem->n * 2 + 2;
18095  }
18096
18097  /* Set zIn to point at the start of the input buffer and zTerm to point 1
18098  ** byte past the end.
18099  **
18100  ** Variable zOut is set to point at the output buffer, space obtained
18101  ** from sqlite3_malloc().
18102  */
18103  zIn = (u8*)pMem->z;
18104  zTerm = &zIn[pMem->n];
18105  zOut = sqlite3DbMallocRaw(pMem->db, len);
18106  if( !zOut ){
18107    return SQLITE_NOMEM;
18108  }
18109  z = zOut;
18110
18111  if( pMem->enc==SQLITE_UTF8 ){
18112    if( desiredEnc==SQLITE_UTF16LE ){
18113      /* UTF-8 -> UTF-16 Little-endian */
18114      while( zIn<zTerm ){
18115        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18116        READ_UTF8(zIn, zTerm, c);
18117        WRITE_UTF16LE(z, c);
18118      }
18119    }else{
18120      assert( desiredEnc==SQLITE_UTF16BE );
18121      /* UTF-8 -> UTF-16 Big-endian */
18122      while( zIn<zTerm ){
18123        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18124        READ_UTF8(zIn, zTerm, c);
18125        WRITE_UTF16BE(z, c);
18126      }
18127    }
18128    pMem->n = (int)(z - zOut);
18129    *z++ = 0;
18130  }else{
18131    assert( desiredEnc==SQLITE_UTF8 );
18132    if( pMem->enc==SQLITE_UTF16LE ){
18133      /* UTF-16 Little-endian -> UTF-8 */
18134      while( zIn<zTerm ){
18135        READ_UTF16LE(zIn, zIn<zTerm, c);
18136        WRITE_UTF8(z, c);
18137      }
18138    }else{
18139      /* UTF-16 Big-endian -> UTF-8 */
18140      while( zIn<zTerm ){
18141        READ_UTF16BE(zIn, zIn<zTerm, c);
18142        WRITE_UTF8(z, c);
18143      }
18144    }
18145    pMem->n = (int)(z - zOut);
18146  }
18147  *z = 0;
18148  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
18149
18150  sqlite3VdbeMemRelease(pMem);
18151  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
18152  pMem->enc = desiredEnc;
18153  pMem->flags |= (MEM_Term|MEM_Dyn);
18154  pMem->z = (char*)zOut;
18155  pMem->zMalloc = pMem->z;
18156
18157translate_out:
18158#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18159  {
18160    char zBuf[100];
18161    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18162    fprintf(stderr, "OUTPUT: %s\n", zBuf);
18163  }
18164#endif
18165  return SQLITE_OK;
18166}
18167
18168/*
18169** This routine checks for a byte-order mark at the beginning of the
18170** UTF-16 string stored in *pMem. If one is present, it is removed and
18171** the encoding of the Mem adjusted. This routine does not do any
18172** byte-swapping, it just sets Mem.enc appropriately.
18173**
18174** The allocation (static, dynamic etc.) and encoding of the Mem may be
18175** changed by this function.
18176*/
18177SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
18178  int rc = SQLITE_OK;
18179  u8 bom = 0;
18180
18181  assert( pMem->n>=0 );
18182  if( pMem->n>1 ){
18183    u8 b1 = *(u8 *)pMem->z;
18184    u8 b2 = *(((u8 *)pMem->z) + 1);
18185    if( b1==0xFE && b2==0xFF ){
18186      bom = SQLITE_UTF16BE;
18187    }
18188    if( b1==0xFF && b2==0xFE ){
18189      bom = SQLITE_UTF16LE;
18190    }
18191  }
18192
18193  if( bom ){
18194    rc = sqlite3VdbeMemMakeWriteable(pMem);
18195    if( rc==SQLITE_OK ){
18196      pMem->n -= 2;
18197      memmove(pMem->z, &pMem->z[2], pMem->n);
18198      pMem->z[pMem->n] = '\0';
18199      pMem->z[pMem->n+1] = '\0';
18200      pMem->flags |= MEM_Term;
18201      pMem->enc = bom;
18202    }
18203  }
18204  return rc;
18205}
18206#endif /* SQLITE_OMIT_UTF16 */
18207
18208/*
18209** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
18210** return the number of unicode characters in pZ up to (but not including)
18211** the first 0x00 byte. If nByte is not less than zero, return the
18212** number of unicode characters in the first nByte of pZ (or up to
18213** the first 0x00, whichever comes first).
18214*/
18215SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
18216  int r = 0;
18217  const u8 *z = (const u8*)zIn;
18218  const u8 *zTerm;
18219  if( nByte>=0 ){
18220    zTerm = &z[nByte];
18221  }else{
18222    zTerm = (const u8*)(-1);
18223  }
18224  assert( z<=zTerm );
18225  while( *z!=0 && z<zTerm ){
18226    SQLITE_SKIP_UTF8(z);
18227    r++;
18228  }
18229  return r;
18230}
18231
18232/* This test function is not currently used by the automated test-suite.
18233** Hence it is only available in debug builds.
18234*/
18235#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
18236/*
18237** Translate UTF-8 to UTF-8.
18238**
18239** This has the effect of making sure that the string is well-formed
18240** UTF-8.  Miscoded characters are removed.
18241**
18242** The translation is done in-place (since it is impossible for the
18243** correct UTF-8 encoding to be longer than a malformed encoding).
18244*/
18245SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
18246  unsigned char *zOut = zIn;
18247  unsigned char *zStart = zIn;
18248  u32 c;
18249
18250  while( zIn[0] ){
18251    c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
18252    if( c!=0xfffd ){
18253      WRITE_UTF8(zOut, c);
18254    }
18255  }
18256  *zOut = 0;
18257  return (int)(zOut - zStart);
18258}
18259#endif
18260
18261#ifndef SQLITE_OMIT_UTF16
18262/*
18263** Convert a UTF-16 string in the native encoding into a UTF-8 string.
18264** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
18265** be freed by the calling function.
18266**
18267** NULL is returned if there is an allocation error.
18268*/
18269SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte){
18270  Mem m;
18271  memset(&m, 0, sizeof(m));
18272  m.db = db;
18273  sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
18274  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
18275  if( db->mallocFailed ){
18276    sqlite3VdbeMemRelease(&m);
18277    m.z = 0;
18278  }
18279  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
18280  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
18281  return (m.flags & MEM_Dyn)!=0 ? m.z : sqlite3DbStrDup(db, m.z);
18282}
18283
18284/*
18285** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
18286** enc. A pointer to the new string is returned, and the value of *pnOut
18287** is set to the length of the returned string in bytes. The call should
18288** arrange to call sqlite3DbFree() on the returned pointer when it is
18289** no longer required.
18290**
18291** If a malloc failure occurs, NULL is returned and the db.mallocFailed
18292** flag set.
18293*/
18294#ifdef SQLITE_ENABLE_STAT2
18295SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
18296  Mem m;
18297  memset(&m, 0, sizeof(m));
18298  m.db = db;
18299  sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
18300  if( sqlite3VdbeMemTranslate(&m, enc) ){
18301    assert( db->mallocFailed );
18302    return 0;
18303  }
18304  assert( m.z==m.zMalloc );
18305  *pnOut = m.n;
18306  return m.z;
18307}
18308#endif
18309
18310/*
18311** zIn is a UTF-16 encoded unicode string at least nChar characters long.
18312** Return the number of bytes in the first nChar unicode characters
18313** in pZ.  nChar must be non-negative.
18314*/
18315SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
18316  int c;
18317  unsigned char const *z = zIn;
18318  int n = 0;
18319
18320  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
18321    while( n<nChar ){
18322      READ_UTF16BE(z, 1, c);
18323      n++;
18324    }
18325  }else{
18326    while( n<nChar ){
18327      READ_UTF16LE(z, 1, c);
18328      n++;
18329    }
18330  }
18331  return (int)(z-(unsigned char const *)zIn);
18332}
18333
18334#if defined(SQLITE_TEST)
18335/*
18336** This routine is called from the TCL test function "translate_selftest".
18337** It checks that the primitives for serializing and deserializing
18338** characters in each encoding are inverses of each other.
18339*/
18340SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
18341  unsigned int i, t;
18342  unsigned char zBuf[20];
18343  unsigned char *z;
18344  int n;
18345  unsigned int c;
18346
18347  for(i=0; i<0x00110000; i++){
18348    z = zBuf;
18349    WRITE_UTF8(z, i);
18350    n = (int)(z-zBuf);
18351    assert( n>0 && n<=4 );
18352    z[0] = 0;
18353    z = zBuf;
18354    c = sqlite3Utf8Read(z, (const u8**)&z);
18355    t = i;
18356    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
18357    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
18358    assert( c==t );
18359    assert( (z-zBuf)==n );
18360  }
18361  for(i=0; i<0x00110000; i++){
18362    if( i>=0xD800 && i<0xE000 ) continue;
18363    z = zBuf;
18364    WRITE_UTF16LE(z, i);
18365    n = (int)(z-zBuf);
18366    assert( n>0 && n<=4 );
18367    z[0] = 0;
18368    z = zBuf;
18369    READ_UTF16LE(z, 1, c);
18370    assert( c==i );
18371    assert( (z-zBuf)==n );
18372  }
18373  for(i=0; i<0x00110000; i++){
18374    if( i>=0xD800 && i<0xE000 ) continue;
18375    z = zBuf;
18376    WRITE_UTF16BE(z, i);
18377    n = (int)(z-zBuf);
18378    assert( n>0 && n<=4 );
18379    z[0] = 0;
18380    z = zBuf;
18381    READ_UTF16BE(z, 1, c);
18382    assert( c==i );
18383    assert( (z-zBuf)==n );
18384  }
18385}
18386#endif /* SQLITE_TEST */
18387#endif /* SQLITE_OMIT_UTF16 */
18388
18389/************** End of utf.c *************************************************/
18390/************** Begin file util.c ********************************************/
18391/*
18392** 2001 September 15
18393**
18394** The author disclaims copyright to this source code.  In place of
18395** a legal notice, here is a blessing:
18396**
18397**    May you do good and not evil.
18398**    May you find forgiveness for yourself and forgive others.
18399**    May you share freely, never taking more than you give.
18400**
18401*************************************************************************
18402** Utility functions used throughout sqlite.
18403**
18404** This file contains functions for allocating memory, comparing
18405** strings, and stuff like that.
18406**
18407*/
18408#ifdef SQLITE_HAVE_ISNAN
18409# include <math.h>
18410#endif
18411
18412/*
18413** Routine needed to support the testcase() macro.
18414*/
18415#ifdef SQLITE_COVERAGE_TEST
18416SQLITE_PRIVATE void sqlite3Coverage(int x){
18417  static int dummy = 0;
18418  dummy += x;
18419}
18420#endif
18421
18422/*
18423** Return true if the floating point value is Not a Number (NaN).
18424**
18425** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
18426** Otherwise, we have our own implementation that works on most systems.
18427*/
18428SQLITE_PRIVATE int sqlite3IsNaN(double x){
18429  int rc;   /* The value return */
18430#if !defined(SQLITE_HAVE_ISNAN)
18431  /*
18432  ** Systems that support the isnan() library function should probably
18433  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
18434  ** found that many systems do not have a working isnan() function so
18435  ** this implementation is provided as an alternative.
18436  **
18437  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
18438  ** On the other hand, the use of -ffast-math comes with the following
18439  ** warning:
18440  **
18441  **      This option [-ffast-math] should never be turned on by any
18442  **      -O option since it can result in incorrect output for programs
18443  **      which depend on an exact implementation of IEEE or ISO
18444  **      rules/specifications for math functions.
18445  **
18446  ** Under MSVC, this NaN test may fail if compiled with a floating-
18447  ** point precision mode other than /fp:precise.  From the MSDN
18448  ** documentation:
18449  **
18450  **      The compiler [with /fp:precise] will properly handle comparisons
18451  **      involving NaN. For example, x != x evaluates to true if x is NaN
18452  **      ...
18453  */
18454#ifdef __FAST_MATH__
18455# error SQLite will not work correctly with the -ffast-math option of GCC.
18456#endif
18457  volatile double y = x;
18458  volatile double z = y;
18459  rc = (y!=z);
18460#else  /* if defined(SQLITE_HAVE_ISNAN) */
18461  rc = isnan(x);
18462#endif /* SQLITE_HAVE_ISNAN */
18463  testcase( rc );
18464  return rc;
18465}
18466
18467/*
18468** Compute a string length that is limited to what can be stored in
18469** lower 30 bits of a 32-bit signed integer.
18470**
18471** The value returned will never be negative.  Nor will it ever be greater
18472** than the actual length of the string.  For very long strings (greater
18473** than 1GiB) the value returned might be less than the true string length.
18474*/
18475SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
18476  const char *z2 = z;
18477  if( z==0 ) return 0;
18478  while( *z2 ){ z2++; }
18479  return 0x3fffffff & (int)(z2 - z);
18480}
18481
18482/*
18483** Set the most recent error code and error string for the sqlite
18484** handle "db". The error code is set to "err_code".
18485**
18486** If it is not NULL, string zFormat specifies the format of the
18487** error string in the style of the printf functions: The following
18488** format characters are allowed:
18489**
18490**      %s      Insert a string
18491**      %z      A string that should be freed after use
18492**      %d      Insert an integer
18493**      %T      Insert a token
18494**      %S      Insert the first element of a SrcList
18495**
18496** zFormat and any string tokens that follow it are assumed to be
18497** encoded in UTF-8.
18498**
18499** To clear the most recent error for sqlite handle "db", sqlite3Error
18500** should be called with err_code set to SQLITE_OK and zFormat set
18501** to NULL.
18502*/
18503SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
18504  if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
18505    db->errCode = err_code;
18506    if( zFormat ){
18507      char *z;
18508      va_list ap;
18509      va_start(ap, zFormat);
18510      z = sqlite3VMPrintf(db, zFormat, ap);
18511      va_end(ap);
18512      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
18513    }else{
18514      sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
18515    }
18516  }
18517}
18518
18519/*
18520** Add an error message to pParse->zErrMsg and increment pParse->nErr.
18521** The following formatting characters are allowed:
18522**
18523**      %s      Insert a string
18524**      %z      A string that should be freed after use
18525**      %d      Insert an integer
18526**      %T      Insert a token
18527**      %S      Insert the first element of a SrcList
18528**
18529** This function should be used to report any error that occurs whilst
18530** compiling an SQL statement (i.e. within sqlite3_prepare()). The
18531** last thing the sqlite3_prepare() function does is copy the error
18532** stored by this function into the database handle using sqlite3Error().
18533** Function sqlite3Error() should be used during statement execution
18534** (sqlite3_step() etc.).
18535*/
18536SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
18537  va_list ap;
18538  sqlite3 *db = pParse->db;
18539  pParse->nErr++;
18540  sqlite3DbFree(db, pParse->zErrMsg);
18541  va_start(ap, zFormat);
18542  pParse->zErrMsg = sqlite3VMPrintf(db, zFormat, ap);
18543  va_end(ap);
18544  pParse->rc = SQLITE_ERROR;
18545}
18546
18547/*
18548** Clear the error message in pParse, if any
18549*/
18550SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
18551  sqlite3DbFree(pParse->db, pParse->zErrMsg);
18552  pParse->zErrMsg = 0;
18553  pParse->nErr = 0;
18554}
18555
18556/*
18557** Convert an SQL-style quoted string into a normal string by removing
18558** the quote characters.  The conversion is done in-place.  If the
18559** input does not begin with a quote character, then this routine
18560** is a no-op.
18561**
18562** The input string must be zero-terminated.  A new zero-terminator
18563** is added to the dequoted string.
18564**
18565** The return value is -1 if no dequoting occurs or the length of the
18566** dequoted string, exclusive of the zero terminator, if dequoting does
18567** occur.
18568**
18569** 2002-Feb-14: This routine is extended to remove MS-Access style
18570** brackets from around identifers.  For example:  "[a-b-c]" becomes
18571** "a-b-c".
18572*/
18573SQLITE_PRIVATE int sqlite3Dequote(char *z){
18574  char quote;
18575  int i, j;
18576  if( z==0 ) return -1;
18577  quote = z[0];
18578  switch( quote ){
18579    case '\'':  break;
18580    case '"':   break;
18581    case '`':   break;                /* For MySQL compatibility */
18582    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
18583    default:    return -1;
18584  }
18585  for(i=1, j=0; ALWAYS(z[i]); i++){
18586    if( z[i]==quote ){
18587      if( z[i+1]==quote ){
18588        z[j++] = quote;
18589        i++;
18590      }else{
18591        break;
18592      }
18593    }else{
18594      z[j++] = z[i];
18595    }
18596  }
18597  z[j] = 0;
18598  return j;
18599}
18600
18601/* Convenient short-hand */
18602#define UpperToLower sqlite3UpperToLower
18603
18604/*
18605** Some systems have stricmp().  Others have strcasecmp().  Because
18606** there is no consistency, we will define our own.
18607*/
18608SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
18609  register unsigned char *a, *b;
18610  a = (unsigned char *)zLeft;
18611  b = (unsigned char *)zRight;
18612  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18613  return UpperToLower[*a] - UpperToLower[*b];
18614}
18615SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
18616  register unsigned char *a, *b;
18617  a = (unsigned char *)zLeft;
18618  b = (unsigned char *)zRight;
18619  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
18620  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
18621}
18622
18623/*
18624** Return TRUE if z is a pure numeric string.  Return FALSE and leave
18625** *realnum unchanged if the string contains any character which is not
18626** part of a number.
18627**
18628** If the string is pure numeric, set *realnum to TRUE if the string
18629** contains the '.' character or an "E+000" style exponentiation suffix.
18630** Otherwise set *realnum to FALSE.  Note that just becaue *realnum is
18631** false does not mean that the number can be successfully converted into
18632** an integer - it might be too big.
18633**
18634** An empty string is considered non-numeric.
18635*/
18636SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
18637  int incr = (enc==SQLITE_UTF8?1:2);
18638  if( enc==SQLITE_UTF16BE ) z++;
18639  if( *z=='-' || *z=='+' ) z += incr;
18640  if( !sqlite3Isdigit(*z) ){
18641    return 0;
18642  }
18643  z += incr;
18644  *realnum = 0;
18645  while( sqlite3Isdigit(*z) ){ z += incr; }
18646  if( *z=='.' ){
18647    z += incr;
18648    if( !sqlite3Isdigit(*z) ) return 0;
18649    while( sqlite3Isdigit(*z) ){ z += incr; }
18650    *realnum = 1;
18651  }
18652  if( *z=='e' || *z=='E' ){
18653    z += incr;
18654    if( *z=='+' || *z=='-' ) z += incr;
18655    if( !sqlite3Isdigit(*z) ) return 0;
18656    while( sqlite3Isdigit(*z) ){ z += incr; }
18657    *realnum = 1;
18658  }
18659  return *z==0;
18660}
18661
18662/*
18663** The string z[] is an ASCII representation of a real number.
18664** Convert this string to a double.
18665**
18666** This routine assumes that z[] really is a valid number.  If it
18667** is not, the result is undefined.
18668**
18669** This routine is used instead of the library atof() function because
18670** the library atof() might want to use "," as the decimal point instead
18671** of "." depending on how locale is set.  But that would cause problems
18672** for SQL.  So this routine always uses "." regardless of locale.
18673*/
18674SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
18675#ifndef SQLITE_OMIT_FLOATING_POINT
18676  const char *zBegin = z;
18677  /* sign * significand * (10 ^ (esign * exponent)) */
18678  int sign = 1;   /* sign of significand */
18679  i64 s = 0;      /* significand */
18680  int d = 0;      /* adjust exponent for shifting decimal point */
18681  int esign = 1;  /* sign of exponent */
18682  int e = 0;      /* exponent */
18683  double result;
18684  int nDigits = 0;
18685
18686  /* skip leading spaces */
18687  while( sqlite3Isspace(*z) ) z++;
18688  /* get sign of significand */
18689  if( *z=='-' ){
18690    sign = -1;
18691    z++;
18692  }else if( *z=='+' ){
18693    z++;
18694  }
18695  /* skip leading zeroes */
18696  while( z[0]=='0' ) z++, nDigits++;
18697
18698  /* copy max significant digits to significand */
18699  while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
18700    s = s*10 + (*z - '0');
18701    z++, nDigits++;
18702  }
18703  /* skip non-significant significand digits
18704  ** (increase exponent by d to shift decimal left) */
18705  while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;
18706
18707  /* if decimal point is present */
18708  if( *z=='.' ){
18709    z++;
18710    /* copy digits from after decimal to significand
18711    ** (decrease exponent by d to shift decimal right) */
18712    while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
18713      s = s*10 + (*z - '0');
18714      z++, nDigits++, d--;
18715    }
18716    /* skip non-significant digits */
18717    while( sqlite3Isdigit(*z) ) z++, nDigits++;
18718  }
18719
18720  /* if exponent is present */
18721  if( *z=='e' || *z=='E' ){
18722    z++;
18723    /* get sign of exponent */
18724    if( *z=='-' ){
18725      esign = -1;
18726      z++;
18727    }else if( *z=='+' ){
18728      z++;
18729    }
18730    /* copy digits to exponent */
18731    while( sqlite3Isdigit(*z) ){
18732      e = e*10 + (*z - '0');
18733      z++;
18734    }
18735  }
18736
18737  /* adjust exponent by d, and update sign */
18738  e = (e*esign) + d;
18739  if( e<0 ) {
18740    esign = -1;
18741    e *= -1;
18742  } else {
18743    esign = 1;
18744  }
18745
18746  /* if 0 significand */
18747  if( !s ) {
18748    /* In the IEEE 754 standard, zero is signed.
18749    ** Add the sign if we've seen at least one digit */
18750    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
18751  } else {
18752    /* attempt to reduce exponent */
18753    if( esign>0 ){
18754      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
18755    }else{
18756      while( !(s%10) && e>0 ) e--,s/=10;
18757    }
18758
18759    /* adjust the sign of significand */
18760    s = sign<0 ? -s : s;
18761
18762    /* if exponent, scale significand as appropriate
18763    ** and store in result. */
18764    if( e ){
18765      double scale = 1.0;
18766      /* attempt to handle extremely small/large numbers better */
18767      if( e>307 && e<342 ){
18768        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
18769        if( esign<0 ){
18770          result = s / scale;
18771          result /= 1.0e+308;
18772        }else{
18773          result = s * scale;
18774          result *= 1.0e+308;
18775        }
18776      }else{
18777        /* 1.0e+22 is the largest power of 10 than can be
18778        ** represented exactly. */
18779        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
18780        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
18781        if( esign<0 ){
18782          result = s / scale;
18783        }else{
18784          result = s * scale;
18785        }
18786      }
18787    } else {
18788      result = (double)s;
18789    }
18790  }
18791
18792  /* store the result */
18793  *pResult = result;
18794
18795  /* return number of characters used */
18796  return (int)(z - zBegin);
18797#else
18798  return sqlite3Atoi64(z, pResult);
18799#endif /* SQLITE_OMIT_FLOATING_POINT */
18800}
18801
18802/*
18803** Compare the 19-character string zNum against the text representation
18804** value 2^63:  9223372036854775808.  Return negative, zero, or positive
18805** if zNum is less than, equal to, or greater than the string.
18806**
18807** Unlike memcmp() this routine is guaranteed to return the difference
18808** in the values of the last digit if the only difference is in the
18809** last digit.  So, for example,
18810**
18811**      compare2pow63("9223372036854775800")
18812**
18813** will return -8.
18814*/
18815static int compare2pow63(const char *zNum){
18816  int c;
18817  c = memcmp(zNum,"922337203685477580",18)*10;
18818  if( c==0 ){
18819    c = zNum[18] - '8';
18820  }
18821  return c;
18822}
18823
18824
18825/*
18826** Return TRUE if zNum is a 64-bit signed integer and write
18827** the value of the integer into *pNum.  If zNum is not an integer
18828** or is an integer that is too large to be expressed with 64 bits,
18829** then return false.
18830**
18831** When this routine was originally written it dealt with only
18832** 32-bit numbers.  At that time, it was much faster than the
18833** atoi() library routine in RedHat 7.2.
18834*/
18835SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
18836  i64 v = 0;
18837  int neg;
18838  int i, c;
18839  const char *zStart;
18840  while( sqlite3Isspace(*zNum) ) zNum++;
18841  if( *zNum=='-' ){
18842    neg = 1;
18843    zNum++;
18844  }else if( *zNum=='+' ){
18845    neg = 0;
18846    zNum++;
18847  }else{
18848    neg = 0;
18849  }
18850  zStart = zNum;
18851  while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
18852  for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
18853    v = v*10 + c - '0';
18854  }
18855  *pNum = neg ? -v : v;
18856  if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
18857    /* zNum is empty or contains non-numeric text or is longer
18858    ** than 19 digits (thus guaranting that it is too large) */
18859    return 0;
18860  }else if( i<19 ){
18861    /* Less than 19 digits, so we know that it fits in 64 bits */
18862    return 1;
18863  }else{
18864    /* 19-digit numbers must be no larger than 9223372036854775807 if positive
18865    ** or 9223372036854775808 if negative.  Note that 9223372036854665808
18866    ** is 2^63. */
18867    return compare2pow63(zNum)<neg;
18868  }
18869}
18870
18871/*
18872** The string zNum represents an unsigned integer.  The zNum string
18873** consists of one or more digit characters and is terminated by
18874** a zero character.  Any stray characters in zNum result in undefined
18875** behavior.
18876**
18877** If the unsigned integer that zNum represents will fit in a
18878** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
18879**
18880** If the negFlag parameter is true, that means that zNum really represents
18881** a negative number.  (The leading "-" is omitted from zNum.)  This
18882** parameter is needed to determine a boundary case.  A string
18883** of "9223373036854775808" returns false if negFlag is false or true
18884** if negFlag is true.
18885**
18886** Leading zeros are ignored.
18887*/
18888SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
18889  int i;
18890  int neg = 0;
18891
18892  assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
18893
18894  if( negFlag ) neg = 1-neg;
18895  while( *zNum=='0' ){
18896    zNum++;   /* Skip leading zeros.  Ticket #2454 */
18897  }
18898  for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
18899  if( i<19 ){
18900    /* Guaranteed to fit if less than 19 digits */
18901    return 1;
18902  }else if( i>19 ){
18903    /* Guaranteed to be too big if greater than 19 digits */
18904    return 0;
18905  }else{
18906    /* Compare against 2^63. */
18907    return compare2pow63(zNum)<neg;
18908  }
18909}
18910
18911/*
18912** If zNum represents an integer that will fit in 32-bits, then set
18913** *pValue to that integer and return true.  Otherwise return false.
18914**
18915** Any non-numeric characters that following zNum are ignored.
18916** This is different from sqlite3Atoi64() which requires the
18917** input number to be zero-terminated.
18918*/
18919SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
18920  sqlite_int64 v = 0;
18921  int i, c;
18922  int neg = 0;
18923  if( zNum[0]=='-' ){
18924    neg = 1;
18925    zNum++;
18926  }else if( zNum[0]=='+' ){
18927    zNum++;
18928  }
18929  while( zNum[0]=='0' ) zNum++;
18930  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
18931    v = v*10 + c;
18932  }
18933
18934  /* The longest decimal representation of a 32 bit integer is 10 digits:
18935  **
18936  **             1234567890
18937  **     2^31 -> 2147483648
18938  */
18939  if( i>10 ){
18940    return 0;
18941  }
18942  if( v-neg>2147483647 ){
18943    return 0;
18944  }
18945  if( neg ){
18946    v = -v;
18947  }
18948  *pValue = (int)v;
18949  return 1;
18950}
18951
18952/*
18953** The variable-length integer encoding is as follows:
18954**
18955** KEY:
18956**         A = 0xxxxxxx    7 bits of data and one flag bit
18957**         B = 1xxxxxxx    7 bits of data and one flag bit
18958**         C = xxxxxxxx    8 bits of data
18959**
18960**  7 bits - A
18961** 14 bits - BA
18962** 21 bits - BBA
18963** 28 bits - BBBA
18964** 35 bits - BBBBA
18965** 42 bits - BBBBBA
18966** 49 bits - BBBBBBA
18967** 56 bits - BBBBBBBA
18968** 64 bits - BBBBBBBBC
18969*/
18970
18971/*
18972** Write a 64-bit variable-length integer to memory starting at p[0].
18973** The length of data write will be between 1 and 9 bytes.  The number
18974** of bytes written is returned.
18975**
18976** A variable-length integer consists of the lower 7 bits of each byte
18977** for all bytes that have the 8th bit set and one byte with the 8th
18978** bit clear.  Except, if we get to the 9th byte, it stores the full
18979** 8 bits and is the last byte.
18980*/
18981SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
18982  int i, j, n;
18983  u8 buf[10];
18984  if( v & (((u64)0xff000000)<<32) ){
18985    p[8] = (u8)v;
18986    v >>= 8;
18987    for(i=7; i>=0; i--){
18988      p[i] = (u8)((v & 0x7f) | 0x80);
18989      v >>= 7;
18990    }
18991    return 9;
18992  }
18993  n = 0;
18994  do{
18995    buf[n++] = (u8)((v & 0x7f) | 0x80);
18996    v >>= 7;
18997  }while( v!=0 );
18998  buf[0] &= 0x7f;
18999  assert( n<=9 );
19000  for(i=0, j=n-1; j>=0; j--, i++){
19001    p[i] = buf[j];
19002  }
19003  return n;
19004}
19005
19006/*
19007** This routine is a faster version of sqlite3PutVarint() that only
19008** works for 32-bit positive integers and which is optimized for
19009** the common case of small integers.  A MACRO version, putVarint32,
19010** is provided which inlines the single-byte case.  All code should use
19011** the MACRO version as this function assumes the single-byte case has
19012** already been handled.
19013*/
19014SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
19015#ifndef putVarint32
19016  if( (v & ~0x7f)==0 ){
19017    p[0] = v;
19018    return 1;
19019  }
19020#endif
19021  if( (v & ~0x3fff)==0 ){
19022    p[0] = (u8)((v>>7) | 0x80);
19023    p[1] = (u8)(v & 0x7f);
19024    return 2;
19025  }
19026  return sqlite3PutVarint(p, v);
19027}
19028
19029/*
19030** Read a 64-bit variable-length integer from memory starting at p[0].
19031** Return the number of bytes read.  The value is stored in *v.
19032*/
19033SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
19034  u32 a,b,s;
19035
19036  a = *p;
19037  /* a: p0 (unmasked) */
19038  if (!(a&0x80))
19039  {
19040    *v = a;
19041    return 1;
19042  }
19043
19044  p++;
19045  b = *p;
19046  /* b: p1 (unmasked) */
19047  if (!(b&0x80))
19048  {
19049    a &= 0x7f;
19050    a = a<<7;
19051    a |= b;
19052    *v = a;
19053    return 2;
19054  }
19055
19056  p++;
19057  a = a<<14;
19058  a |= *p;
19059  /* a: p0<<14 | p2 (unmasked) */
19060  if (!(a&0x80))
19061  {
19062    a &= (0x7f<<14)|(0x7f);
19063    b &= 0x7f;
19064    b = b<<7;
19065    a |= b;
19066    *v = a;
19067    return 3;
19068  }
19069
19070  /* CSE1 from below */
19071  a &= (0x7f<<14)|(0x7f);
19072  p++;
19073  b = b<<14;
19074  b |= *p;
19075  /* b: p1<<14 | p3 (unmasked) */
19076  if (!(b&0x80))
19077  {
19078    b &= (0x7f<<14)|(0x7f);
19079    /* moved CSE1 up */
19080    /* a &= (0x7f<<14)|(0x7f); */
19081    a = a<<7;
19082    a |= b;
19083    *v = a;
19084    return 4;
19085  }
19086
19087  /* a: p0<<14 | p2 (masked) */
19088  /* b: p1<<14 | p3 (unmasked) */
19089  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19090  /* moved CSE1 up */
19091  /* a &= (0x7f<<14)|(0x7f); */
19092  b &= (0x7f<<14)|(0x7f);
19093  s = a;
19094  /* s: p0<<14 | p2 (masked) */
19095
19096  p++;
19097  a = a<<14;
19098  a |= *p;
19099  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19100  if (!(a&0x80))
19101  {
19102    /* we can skip these cause they were (effectively) done above in calc'ing s */
19103    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19104    /* b &= (0x7f<<14)|(0x7f); */
19105    b = b<<7;
19106    a |= b;
19107    s = s>>18;
19108    *v = ((u64)s)<<32 | a;
19109    return 5;
19110  }
19111
19112  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19113  s = s<<7;
19114  s |= b;
19115  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19116
19117  p++;
19118  b = b<<14;
19119  b |= *p;
19120  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
19121  if (!(b&0x80))
19122  {
19123    /* we can skip this cause it was (effectively) done above in calc'ing s */
19124    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19125    a &= (0x7f<<14)|(0x7f);
19126    a = a<<7;
19127    a |= b;
19128    s = s>>18;
19129    *v = ((u64)s)<<32 | a;
19130    return 6;
19131  }
19132
19133  p++;
19134  a = a<<14;
19135  a |= *p;
19136  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
19137  if (!(a&0x80))
19138  {
19139    a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19140    b &= (0x7f<<14)|(0x7f);
19141    b = b<<7;
19142    a |= b;
19143    s = s>>11;
19144    *v = ((u64)s)<<32 | a;
19145    return 7;
19146  }
19147
19148  /* CSE2 from below */
19149  a &= (0x7f<<14)|(0x7f);
19150  p++;
19151  b = b<<14;
19152  b |= *p;
19153  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
19154  if (!(b&0x80))
19155  {
19156    b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19157    /* moved CSE2 up */
19158    /* a &= (0x7f<<14)|(0x7f); */
19159    a = a<<7;
19160    a |= b;
19161    s = s>>4;
19162    *v = ((u64)s)<<32 | a;
19163    return 8;
19164  }
19165
19166  p++;
19167  a = a<<15;
19168  a |= *p;
19169  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
19170
19171  /* moved CSE2 up */
19172  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
19173  b &= (0x7f<<14)|(0x7f);
19174  b = b<<8;
19175  a |= b;
19176
19177  s = s<<4;
19178  b = p[-4];
19179  b &= 0x7f;
19180  b = b>>3;
19181  s |= b;
19182
19183  *v = ((u64)s)<<32 | a;
19184
19185  return 9;
19186}
19187
19188/*
19189** Read a 32-bit variable-length integer from memory starting at p[0].
19190** Return the number of bytes read.  The value is stored in *v.
19191**
19192** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
19193** integer, then set *v to 0xffffffff.
19194**
19195** A MACRO version, getVarint32, is provided which inlines the
19196** single-byte case.  All code should use the MACRO version as
19197** this function assumes the single-byte case has already been handled.
19198*/
19199SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
19200  u32 a,b;
19201
19202  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
19203  ** by the getVarin32() macro */
19204  a = *p;
19205  /* a: p0 (unmasked) */
19206#ifndef getVarint32
19207  if (!(a&0x80))
19208  {
19209    /* Values between 0 and 127 */
19210    *v = a;
19211    return 1;
19212  }
19213#endif
19214
19215  /* The 2-byte case */
19216  p++;
19217  b = *p;
19218  /* b: p1 (unmasked) */
19219  if (!(b&0x80))
19220  {
19221    /* Values between 128 and 16383 */
19222    a &= 0x7f;
19223    a = a<<7;
19224    *v = a | b;
19225    return 2;
19226  }
19227
19228  /* The 3-byte case */
19229  p++;
19230  a = a<<14;
19231  a |= *p;
19232  /* a: p0<<14 | p2 (unmasked) */
19233  if (!(a&0x80))
19234  {
19235    /* Values between 16384 and 2097151 */
19236    a &= (0x7f<<14)|(0x7f);
19237    b &= 0x7f;
19238    b = b<<7;
19239    *v = a | b;
19240    return 3;
19241  }
19242
19243  /* A 32-bit varint is used to store size information in btrees.
19244  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
19245  ** A 3-byte varint is sufficient, for example, to record the size
19246  ** of a 1048569-byte BLOB or string.
19247  **
19248  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
19249  ** rare larger cases can be handled by the slower 64-bit varint
19250  ** routine.
19251  */
19252#if 1
19253  {
19254    u64 v64;
19255    u8 n;
19256
19257    p -= 2;
19258    n = sqlite3GetVarint(p, &v64);
19259    assert( n>3 && n<=9 );
19260    if( (v64 & SQLITE_MAX_U32)!=v64 ){
19261      *v = 0xffffffff;
19262    }else{
19263      *v = (u32)v64;
19264    }
19265    return n;
19266  }
19267
19268#else
19269  /* For following code (kept for historical record only) shows an
19270  ** unrolling for the 3- and 4-byte varint cases.  This code is
19271  ** slightly faster, but it is also larger and much harder to test.
19272  */
19273  p++;
19274  b = b<<14;
19275  b |= *p;
19276  /* b: p1<<14 | p3 (unmasked) */
19277  if (!(b&0x80))
19278  {
19279    /* Values between 2097152 and 268435455 */
19280    b &= (0x7f<<14)|(0x7f);
19281    a &= (0x7f<<14)|(0x7f);
19282    a = a<<7;
19283    *v = a | b;
19284    return 4;
19285  }
19286
19287  p++;
19288  a = a<<14;
19289  a |= *p;
19290  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19291  if (!(a&0x80))
19292  {
19293    /* Walues  between 268435456 and 34359738367 */
19294    a &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19295    b &= (0x1f<<28)|(0x7f<<14)|(0x7f);
19296    b = b<<7;
19297    *v = a | b;
19298    return 5;
19299  }
19300
19301  /* We can only reach this point when reading a corrupt database
19302  ** file.  In that case we are not in any hurry.  Use the (relatively
19303  ** slow) general-purpose sqlite3GetVarint() routine to extract the
19304  ** value. */
19305  {
19306    u64 v64;
19307    u8 n;
19308
19309    p -= 4;
19310    n = sqlite3GetVarint(p, &v64);
19311    assert( n>5 && n<=9 );
19312    *v = (u32)v64;
19313    return n;
19314  }
19315#endif
19316}
19317
19318/*
19319** Return the number of bytes that will be needed to store the given
19320** 64-bit integer.
19321*/
19322SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
19323  int i = 0;
19324  do{
19325    i++;
19326    v >>= 7;
19327  }while( v!=0 && ALWAYS(i<9) );
19328  return i;
19329}
19330
19331
19332/*
19333** Read or write a four-byte big-endian integer value.
19334*/
19335SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
19336  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
19337}
19338SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
19339  p[0] = (u8)(v>>24);
19340  p[1] = (u8)(v>>16);
19341  p[2] = (u8)(v>>8);
19342  p[3] = (u8)v;
19343}
19344
19345
19346
19347#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19348/*
19349** Translate a single byte of Hex into an integer.
19350** This routine only works if h really is a valid hexadecimal
19351** character:  0..9a..fA..F
19352*/
19353static u8 hexToInt(int h){
19354  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
19355#ifdef SQLITE_ASCII
19356  h += 9*(1&(h>>6));
19357#endif
19358#ifdef SQLITE_EBCDIC
19359  h += 9*(1&~(h>>4));
19360#endif
19361  return (u8)(h & 0xf);
19362}
19363#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19364
19365#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19366/*
19367** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
19368** value.  Return a pointer to its binary value.  Space to hold the
19369** binary value has been obtained from malloc and must be freed by
19370** the calling routine.
19371*/
19372SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
19373  char *zBlob;
19374  int i;
19375
19376  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
19377  n--;
19378  if( zBlob ){
19379    for(i=0; i<n; i+=2){
19380      zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
19381    }
19382    zBlob[i/2] = 0;
19383  }
19384  return zBlob;
19385}
19386#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19387
19388
19389/*
19390** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
19391** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
19392** when this routine is called.
19393**
19394** This routine is called when entering an SQLite API.  The SQLITE_MAGIC_OPEN
19395** value indicates that the database connection passed into the API is
19396** open and is not being used by another thread.  By changing the value
19397** to SQLITE_MAGIC_BUSY we indicate that the connection is in use.
19398** sqlite3SafetyOff() below will change the value back to SQLITE_MAGIC_OPEN
19399** when the API exits.
19400**
19401** This routine is a attempt to detect if two threads use the
19402** same sqlite* pointer at the same time.  There is a race
19403** condition so it is possible that the error is not detected.
19404** But usually the problem will be seen.  The result will be an
19405** error which can be used to debug the application that is
19406** using SQLite incorrectly.
19407**
19408** Ticket #202:  If db->magic is not a valid open value, take care not
19409** to modify the db structure at all.  It could be that db is a stale
19410** pointer.  In other words, it could be that there has been a prior
19411** call to sqlite3_close(db) and db has been deallocated.  And we do
19412** not want to write into deallocated memory.
19413*/
19414#ifdef SQLITE_DEBUG
19415SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
19416  if( db->magic==SQLITE_MAGIC_OPEN ){
19417    db->magic = SQLITE_MAGIC_BUSY;
19418    assert( sqlite3_mutex_held(db->mutex) );
19419    return 0;
19420  }else if( db->magic==SQLITE_MAGIC_BUSY ){
19421    db->magic = SQLITE_MAGIC_ERROR;
19422    db->u1.isInterrupted = 1;
19423  }
19424  return 1;
19425}
19426#endif
19427
19428/*
19429** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
19430** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
19431** when this routine is called.
19432*/
19433#ifdef SQLITE_DEBUG
19434SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
19435  if( db->magic==SQLITE_MAGIC_BUSY ){
19436    db->magic = SQLITE_MAGIC_OPEN;
19437    assert( sqlite3_mutex_held(db->mutex) );
19438    return 0;
19439  }else{
19440    db->magic = SQLITE_MAGIC_ERROR;
19441    db->u1.isInterrupted = 1;
19442    return 1;
19443  }
19444}
19445#endif
19446
19447/*
19448** Check to make sure we have a valid db pointer.  This test is not
19449** foolproof but it does provide some measure of protection against
19450** misuse of the interface such as passing in db pointers that are
19451** NULL or which have been previously closed.  If this routine returns
19452** 1 it means that the db pointer is valid and 0 if it should not be
19453** dereferenced for any reason.  The calling function should invoke
19454** SQLITE_MISUSE immediately.
19455**
19456** sqlite3SafetyCheckOk() requires that the db pointer be valid for
19457** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
19458** open properly and is not fit for general use but which can be
19459** used as an argument to sqlite3_errmsg() or sqlite3_close().
19460*/
19461SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
19462  u32 magic;
19463  if( db==0 ) return 0;
19464  magic = db->magic;
19465  if( magic!=SQLITE_MAGIC_OPEN
19466#ifdef SQLITE_DEBUG
19467     && magic!=SQLITE_MAGIC_BUSY
19468#endif
19469  ){
19470    return 0;
19471  }else{
19472    return 1;
19473  }
19474}
19475SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
19476  u32 magic;
19477  magic = db->magic;
19478  if( magic!=SQLITE_MAGIC_SICK &&
19479      magic!=SQLITE_MAGIC_OPEN &&
19480      magic!=SQLITE_MAGIC_BUSY ) return 0;
19481  return 1;
19482}
19483
19484/************** End of util.c ************************************************/
19485/************** Begin file hash.c ********************************************/
19486/*
19487** 2001 September 22
19488**
19489** The author disclaims copyright to this source code.  In place of
19490** a legal notice, here is a blessing:
19491**
19492**    May you do good and not evil.
19493**    May you find forgiveness for yourself and forgive others.
19494**    May you share freely, never taking more than you give.
19495**
19496*************************************************************************
19497** This is the implementation of generic hash-tables
19498** used in SQLite.
19499*/
19500
19501/* Turn bulk memory into a hash table object by initializing the
19502** fields of the Hash structure.
19503**
19504** "pNew" is a pointer to the hash table that is to be initialized.
19505*/
19506SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
19507  assert( pNew!=0 );
19508  pNew->first = 0;
19509  pNew->count = 0;
19510  pNew->htsize = 0;
19511  pNew->ht = 0;
19512}
19513
19514/* Remove all entries from a hash table.  Reclaim all memory.
19515** Call this routine to delete a hash table or to reset a hash table
19516** to the empty state.
19517*/
19518SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
19519  HashElem *elem;         /* For looping over all elements of the table */
19520
19521  assert( pH!=0 );
19522  elem = pH->first;
19523  pH->first = 0;
19524  sqlite3_free(pH->ht);
19525  pH->ht = 0;
19526  pH->htsize = 0;
19527  while( elem ){
19528    HashElem *next_elem = elem->next;
19529    sqlite3_free(elem);
19530    elem = next_elem;
19531  }
19532  pH->count = 0;
19533}
19534
19535/*
19536** The hashing function.
19537*/
19538static unsigned int strHash(const char *z, int nKey){
19539  int h = 0;
19540  assert( nKey>=0 );
19541  while( nKey > 0  ){
19542    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
19543    nKey--;
19544  }
19545  return h;
19546}
19547
19548
19549/* Link pNew element into the hash table pH.  If pEntry!=0 then also
19550** insert pNew into the pEntry hash bucket.
19551*/
19552static void insertElement(
19553  Hash *pH,              /* The complete hash table */
19554  struct _ht *pEntry,    /* The entry into which pNew is inserted */
19555  HashElem *pNew         /* The element to be inserted */
19556){
19557  HashElem *pHead;       /* First element already in pEntry */
19558  if( pEntry ){
19559    pHead = pEntry->count ? pEntry->chain : 0;
19560    pEntry->count++;
19561    pEntry->chain = pNew;
19562  }else{
19563    pHead = 0;
19564  }
19565  if( pHead ){
19566    pNew->next = pHead;
19567    pNew->prev = pHead->prev;
19568    if( pHead->prev ){ pHead->prev->next = pNew; }
19569    else             { pH->first = pNew; }
19570    pHead->prev = pNew;
19571  }else{
19572    pNew->next = pH->first;
19573    if( pH->first ){ pH->first->prev = pNew; }
19574    pNew->prev = 0;
19575    pH->first = pNew;
19576  }
19577}
19578
19579
19580/* Resize the hash table so that it cantains "new_size" buckets.
19581**
19582** The hash table might fail to resize if sqlite3_malloc() fails or
19583** if the new size is the same as the prior size.
19584** Return TRUE if the resize occurs and false if not.
19585*/
19586static int rehash(Hash *pH, unsigned int new_size){
19587  struct _ht *new_ht;            /* The new hash table */
19588  HashElem *elem, *next_elem;    /* For looping over existing elements */
19589
19590#if SQLITE_MALLOC_SOFT_LIMIT>0
19591  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
19592    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
19593  }
19594  if( new_size==pH->htsize ) return 0;
19595#endif
19596
19597  /* The inability to allocates space for a larger hash table is
19598  ** a performance hit but it is not a fatal error.  So mark the
19599  ** allocation as a benign.
19600  */
19601  sqlite3BeginBenignMalloc();
19602  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
19603  sqlite3EndBenignMalloc();
19604
19605  if( new_ht==0 ) return 0;
19606  sqlite3_free(pH->ht);
19607  pH->ht = new_ht;
19608  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
19609  memset(new_ht, 0, new_size*sizeof(struct _ht));
19610  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
19611    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
19612    next_elem = elem->next;
19613    insertElement(pH, &new_ht[h], elem);
19614  }
19615  return 1;
19616}
19617
19618/* This function (for internal use only) locates an element in an
19619** hash table that matches the given key.  The hash for this key has
19620** already been computed and is passed as the 4th parameter.
19621*/
19622static HashElem *findElementGivenHash(
19623  const Hash *pH,     /* The pH to be searched */
19624  const char *pKey,   /* The key we are searching for */
19625  int nKey,           /* Bytes in key (not counting zero terminator) */
19626  unsigned int h      /* The hash for this key. */
19627){
19628  HashElem *elem;                /* Used to loop thru the element list */
19629  int count;                     /* Number of elements left to test */
19630
19631  if( pH->ht ){
19632    struct _ht *pEntry = &pH->ht[h];
19633    elem = pEntry->chain;
19634    count = pEntry->count;
19635  }else{
19636    elem = pH->first;
19637    count = pH->count;
19638  }
19639  while( count-- && ALWAYS(elem) ){
19640    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
19641      return elem;
19642    }
19643    elem = elem->next;
19644  }
19645  return 0;
19646}
19647
19648/* Remove a single entry from the hash table given a pointer to that
19649** element and a hash on the element's key.
19650*/
19651static void removeElementGivenHash(
19652  Hash *pH,         /* The pH containing "elem" */
19653  HashElem* elem,   /* The element to be removed from the pH */
19654  unsigned int h    /* Hash value for the element */
19655){
19656  struct _ht *pEntry;
19657  if( elem->prev ){
19658    elem->prev->next = elem->next;
19659  }else{
19660    pH->first = elem->next;
19661  }
19662  if( elem->next ){
19663    elem->next->prev = elem->prev;
19664  }
19665  if( pH->ht ){
19666    pEntry = &pH->ht[h];
19667    if( pEntry->chain==elem ){
19668      pEntry->chain = elem->next;
19669    }
19670    pEntry->count--;
19671    assert( pEntry->count>=0 );
19672  }
19673  sqlite3_free( elem );
19674  pH->count--;
19675  if( pH->count<=0 ){
19676    assert( pH->first==0 );
19677    assert( pH->count==0 );
19678    sqlite3HashClear(pH);
19679  }
19680}
19681
19682/* Attempt to locate an element of the hash table pH with a key
19683** that matches pKey,nKey.  Return the data for this element if it is
19684** found, or NULL if there is no match.
19685*/
19686SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
19687  HashElem *elem;    /* The element that matches key */
19688  unsigned int h;    /* A hash on key */
19689
19690  assert( pH!=0 );
19691  assert( pKey!=0 );
19692  assert( nKey>=0 );
19693  if( pH->ht ){
19694    h = strHash(pKey, nKey) % pH->htsize;
19695  }else{
19696    h = 0;
19697  }
19698  elem = findElementGivenHash(pH, pKey, nKey, h);
19699  return elem ? elem->data : 0;
19700}
19701
19702/* Insert an element into the hash table pH.  The key is pKey,nKey
19703** and the data is "data".
19704**
19705** If no element exists with a matching key, then a new
19706** element is created and NULL is returned.
19707**
19708** If another element already exists with the same key, then the
19709** new data replaces the old data and the old data is returned.
19710** The key is not copied in this instance.  If a malloc fails, then
19711** the new data is returned and the hash table is unchanged.
19712**
19713** If the "data" parameter to this function is NULL, then the
19714** element corresponding to "key" is removed from the hash table.
19715*/
19716SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
19717  unsigned int h;       /* the hash of the key modulo hash table size */
19718  HashElem *elem;       /* Used to loop thru the element list */
19719  HashElem *new_elem;   /* New element added to the pH */
19720
19721  assert( pH!=0 );
19722  assert( pKey!=0 );
19723  assert( nKey>=0 );
19724  if( pH->htsize ){
19725    h = strHash(pKey, nKey) % pH->htsize;
19726  }else{
19727    h = 0;
19728  }
19729  elem = findElementGivenHash(pH,pKey,nKey,h);
19730  if( elem ){
19731    void *old_data = elem->data;
19732    if( data==0 ){
19733      removeElementGivenHash(pH,elem,h);
19734    }else{
19735      elem->data = data;
19736      elem->pKey = pKey;
19737      assert(nKey==elem->nKey);
19738    }
19739    return old_data;
19740  }
19741  if( data==0 ) return 0;
19742  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
19743  if( new_elem==0 ) return data;
19744  new_elem->pKey = pKey;
19745  new_elem->nKey = nKey;
19746  new_elem->data = data;
19747  pH->count++;
19748  if( pH->count>=10 && pH->count > 2*pH->htsize ){
19749    if( rehash(pH, pH->count*2) ){
19750      assert( pH->htsize>0 );
19751      h = strHash(pKey, nKey) % pH->htsize;
19752    }
19753  }
19754  if( pH->ht ){
19755    insertElement(pH, &pH->ht[h], new_elem);
19756  }else{
19757    insertElement(pH, 0, new_elem);
19758  }
19759  return 0;
19760}
19761
19762/************** End of hash.c ************************************************/
19763/************** Begin file opcodes.c *****************************************/
19764/* Automatically generated.  Do not edit */
19765/* See the mkopcodec.awk script for details. */
19766#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
19767SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
19768 static const char *const azName[] = { "?",
19769     /*   1 */ "Goto",
19770     /*   2 */ "Gosub",
19771     /*   3 */ "Return",
19772     /*   4 */ "Yield",
19773     /*   5 */ "HaltIfNull",
19774     /*   6 */ "Halt",
19775     /*   7 */ "Integer",
19776     /*   8 */ "Int64",
19777     /*   9 */ "String",
19778     /*  10 */ "Null",
19779     /*  11 */ "Blob",
19780     /*  12 */ "Variable",
19781     /*  13 */ "Move",
19782     /*  14 */ "Copy",
19783     /*  15 */ "SCopy",
19784     /*  16 */ "ResultRow",
19785     /*  17 */ "CollSeq",
19786     /*  18 */ "Function",
19787     /*  19 */ "Not",
19788     /*  20 */ "AddImm",
19789     /*  21 */ "MustBeInt",
19790     /*  22 */ "RealAffinity",
19791     /*  23 */ "Permutation",
19792     /*  24 */ "Compare",
19793     /*  25 */ "Jump",
19794     /*  26 */ "If",
19795     /*  27 */ "IfNot",
19796     /*  28 */ "Column",
19797     /*  29 */ "Affinity",
19798     /*  30 */ "MakeRecord",
19799     /*  31 */ "Count",
19800     /*  32 */ "Savepoint",
19801     /*  33 */ "AutoCommit",
19802     /*  34 */ "Transaction",
19803     /*  35 */ "ReadCookie",
19804     /*  36 */ "SetCookie",
19805     /*  37 */ "VerifyCookie",
19806     /*  38 */ "OpenRead",
19807     /*  39 */ "OpenWrite",
19808     /*  40 */ "OpenEphemeral",
19809     /*  41 */ "OpenPseudo",
19810     /*  42 */ "Close",
19811     /*  43 */ "SeekLt",
19812     /*  44 */ "SeekLe",
19813     /*  45 */ "SeekGe",
19814     /*  46 */ "SeekGt",
19815     /*  47 */ "Seek",
19816     /*  48 */ "NotFound",
19817     /*  49 */ "Found",
19818     /*  50 */ "IsUnique",
19819     /*  51 */ "NotExists",
19820     /*  52 */ "Sequence",
19821     /*  53 */ "NewRowid",
19822     /*  54 */ "Insert",
19823     /*  55 */ "InsertInt",
19824     /*  56 */ "Delete",
19825     /*  57 */ "ResetCount",
19826     /*  58 */ "RowKey",
19827     /*  59 */ "RowData",
19828     /*  60 */ "Rowid",
19829     /*  61 */ "NullRow",
19830     /*  62 */ "Last",
19831     /*  63 */ "Sort",
19832     /*  64 */ "Rewind",
19833     /*  65 */ "Prev",
19834     /*  66 */ "Next",
19835     /*  67 */ "IdxInsert",
19836     /*  68 */ "Or",
19837     /*  69 */ "And",
19838     /*  70 */ "IdxDelete",
19839     /*  71 */ "IdxRowid",
19840     /*  72 */ "IdxLT",
19841     /*  73 */ "IsNull",
19842     /*  74 */ "NotNull",
19843     /*  75 */ "Ne",
19844     /*  76 */ "Eq",
19845     /*  77 */ "Gt",
19846     /*  78 */ "Le",
19847     /*  79 */ "Lt",
19848     /*  80 */ "Ge",
19849     /*  81 */ "IdxGE",
19850     /*  82 */ "BitAnd",
19851     /*  83 */ "BitOr",
19852     /*  84 */ "ShiftLeft",
19853     /*  85 */ "ShiftRight",
19854     /*  86 */ "Add",
19855     /*  87 */ "Subtract",
19856     /*  88 */ "Multiply",
19857     /*  89 */ "Divide",
19858     /*  90 */ "Remainder",
19859     /*  91 */ "Concat",
19860     /*  92 */ "Destroy",
19861     /*  93 */ "BitNot",
19862     /*  94 */ "String8",
19863     /*  95 */ "Clear",
19864     /*  96 */ "CreateIndex",
19865     /*  97 */ "CreateTable",
19866     /*  98 */ "ParseSchema",
19867     /*  99 */ "LoadAnalysis",
19868     /* 100 */ "DropTable",
19869     /* 101 */ "DropIndex",
19870     /* 102 */ "DropTrigger",
19871     /* 103 */ "IntegrityCk",
19872     /* 104 */ "RowSetAdd",
19873     /* 105 */ "RowSetRead",
19874     /* 106 */ "RowSetTest",
19875     /* 107 */ "Program",
19876     /* 108 */ "Param",
19877     /* 109 */ "FkCounter",
19878     /* 110 */ "FkIfZero",
19879     /* 111 */ "MemMax",
19880     /* 112 */ "IfPos",
19881     /* 113 */ "IfNeg",
19882     /* 114 */ "IfZero",
19883     /* 115 */ "AggStep",
19884     /* 116 */ "AggFinal",
19885     /* 117 */ "Vacuum",
19886     /* 118 */ "IncrVacuum",
19887     /* 119 */ "Expire",
19888     /* 120 */ "TableLock",
19889     /* 121 */ "VBegin",
19890     /* 122 */ "VCreate",
19891     /* 123 */ "VDestroy",
19892     /* 124 */ "VOpen",
19893     /* 125 */ "VFilter",
19894     /* 126 */ "VColumn",
19895     /* 127 */ "VNext",
19896     /* 128 */ "VRename",
19897     /* 129 */ "VUpdate",
19898     /* 130 */ "Real",
19899     /* 131 */ "Pagecount",
19900     /* 132 */ "Trace",
19901     /* 133 */ "Noop",
19902     /* 134 */ "Explain",
19903     /* 135 */ "NotUsed_135",
19904     /* 136 */ "NotUsed_136",
19905     /* 137 */ "NotUsed_137",
19906     /* 138 */ "NotUsed_138",
19907     /* 139 */ "NotUsed_139",
19908     /* 140 */ "NotUsed_140",
19909     /* 141 */ "ToText",
19910     /* 142 */ "ToBlob",
19911     /* 143 */ "ToNumeric",
19912     /* 144 */ "ToInt",
19913     /* 145 */ "ToReal",
19914  };
19915  return azName[i];
19916}
19917#endif
19918
19919/************** End of opcodes.c *********************************************/
19920/************** Begin file os_os2.c ******************************************/
19921/*
19922** 2006 Feb 14
19923**
19924** The author disclaims copyright to this source code.  In place of
19925** a legal notice, here is a blessing:
19926**
19927**    May you do good and not evil.
19928**    May you find forgiveness for yourself and forgive others.
19929**    May you share freely, never taking more than you give.
19930**
19931******************************************************************************
19932**
19933** This file contains code that is specific to OS/2.
19934*/
19935
19936
19937#if SQLITE_OS_OS2
19938
19939/*
19940** A Note About Memory Allocation:
19941**
19942** This driver uses malloc()/free() directly rather than going through
19943** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
19944** are designed for use on embedded systems where memory is scarce and
19945** malloc failures happen frequently.  OS/2 does not typically run on
19946** embedded systems, and when it does the developers normally have bigger
19947** problems to worry about than running out of memory.  So there is not
19948** a compelling need to use the wrappers.
19949**
19950** But there is a good reason to not use the wrappers.  If we use the
19951** wrappers then we will get simulated malloc() failures within this
19952** driver.  And that causes all kinds of problems for our tests.  We
19953** could enhance SQLite to deal with simulated malloc failures within
19954** the OS driver, but the code to deal with those failure would not
19955** be exercised on Linux (which does not need to malloc() in the driver)
19956** and so we would have difficulty writing coverage tests for that
19957** code.  Better to leave the code out, we think.
19958**
19959** The point of this discussion is as follows:  When creating a new
19960** OS layer for an embedded system, if you use this file as an example,
19961** avoid the use of malloc()/free().  Those routines work ok on OS/2
19962** desktops but not so well in embedded systems.
19963*/
19964
19965/*
19966** Macros used to determine whether or not to use threads.
19967*/
19968#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
19969# define SQLITE_OS2_THREADS 1
19970#endif
19971
19972/*
19973** Include code that is common to all os_*.c files
19974*/
19975/************** Include os_common.h in the middle of os_os2.c ****************/
19976/************** Begin file os_common.h ***************************************/
19977/*
19978** 2004 May 22
19979**
19980** The author disclaims copyright to this source code.  In place of
19981** a legal notice, here is a blessing:
19982**
19983**    May you do good and not evil.
19984**    May you find forgiveness for yourself and forgive others.
19985**    May you share freely, never taking more than you give.
19986**
19987******************************************************************************
19988**
19989** This file contains macros and a little bit of code that is common to
19990** all of the platform-specific files (os_*.c) and is #included into those
19991** files.
19992**
19993** This file should be #included by the os_*.c files only.  It is not a
19994** general purpose header file.
19995*/
19996#ifndef _OS_COMMON_H_
19997#define _OS_COMMON_H_
19998
19999/*
20000** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20001** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20002** switch.  The following code should catch this problem at compile-time.
20003*/
20004#ifdef MEMORY_DEBUG
20005# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20006#endif
20007
20008#ifdef SQLITE_DEBUG
20009SQLITE_PRIVATE int sqlite3OSTrace = 0;
20010#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
20011#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
20012#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
20013#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
20014#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
20015#define OSTRACE6(X,Y,Z,A,B,C) \
20016    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
20017#define OSTRACE7(X,Y,Z,A,B,C,D) \
20018    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
20019#else
20020#define OSTRACE1(X)
20021#define OSTRACE2(X,Y)
20022#define OSTRACE3(X,Y,Z)
20023#define OSTRACE4(X,Y,Z,A)
20024#define OSTRACE5(X,Y,Z,A,B)
20025#define OSTRACE6(X,Y,Z,A,B,C)
20026#define OSTRACE7(X,Y,Z,A,B,C,D)
20027#endif
20028
20029/*
20030** Macros for performance tracing.  Normally turned off.  Only works
20031** on i486 hardware.
20032*/
20033#ifdef SQLITE_PERFORMANCE_TRACE
20034
20035/*
20036** hwtime.h contains inline assembler code for implementing
20037** high-performance timing routines.
20038*/
20039/************** Include hwtime.h in the middle of os_common.h ****************/
20040/************** Begin file hwtime.h ******************************************/
20041/*
20042** 2008 May 27
20043**
20044** The author disclaims copyright to this source code.  In place of
20045** a legal notice, here is a blessing:
20046**
20047**    May you do good and not evil.
20048**    May you find forgiveness for yourself and forgive others.
20049**    May you share freely, never taking more than you give.
20050**
20051******************************************************************************
20052**
20053** This file contains inline asm code for retrieving "high-performance"
20054** counters for x86 class CPUs.
20055*/
20056#ifndef _HWTIME_H_
20057#define _HWTIME_H_
20058
20059/*
20060** The following routine only works on pentium-class (or newer) processors.
20061** It uses the RDTSC opcode to read the cycle count value out of the
20062** processor and returns that value.  This can be used for high-res
20063** profiling.
20064*/
20065#if (defined(__GNUC__) || defined(_MSC_VER)) && \
20066      (defined(i386) || defined(__i386__) || defined(_M_IX86))
20067
20068  #if defined(__GNUC__)
20069
20070  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20071     unsigned int lo, hi;
20072     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
20073     return (sqlite_uint64)hi << 32 | lo;
20074  }
20075
20076  #elif defined(_MSC_VER)
20077
20078  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
20079     __asm {
20080        rdtsc
20081        ret       ; return value at EDX:EAX
20082     }
20083  }
20084
20085  #endif
20086
20087#elif (defined(__GNUC__) && defined(__x86_64__))
20088
20089  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20090      unsigned long val;
20091      __asm__ __volatile__ ("rdtsc" : "=A" (val));
20092      return val;
20093  }
20094
20095#elif (defined(__GNUC__) && defined(__ppc__))
20096
20097  __inline__ sqlite_uint64 sqlite3Hwtime(void){
20098      unsigned long long retval;
20099      unsigned long junk;
20100      __asm__ __volatile__ ("\n\
20101          1:      mftbu   %1\n\
20102                  mftb    %L0\n\
20103                  mftbu   %0\n\
20104                  cmpw    %0,%1\n\
20105                  bne     1b"
20106                  : "=r" (retval), "=r" (junk));
20107      return retval;
20108  }
20109
20110#else
20111
20112  #error Need implementation of sqlite3Hwtime() for your platform.
20113
20114  /*
20115  ** To compile without implementing sqlite3Hwtime() for your platform,
20116  ** you can remove the above #error and use the following
20117  ** stub function.  You will lose timing support for many
20118  ** of the debugging and testing utilities, but it should at
20119  ** least compile and run.
20120  */
20121SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
20122
20123#endif
20124
20125#endif /* !defined(_HWTIME_H_) */
20126
20127/************** End of hwtime.h **********************************************/
20128/************** Continuing where we left off in os_common.h ******************/
20129
20130static sqlite_uint64 g_start;
20131static sqlite_uint64 g_elapsed;
20132#define TIMER_START       g_start=sqlite3Hwtime()
20133#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
20134#define TIMER_ELAPSED     g_elapsed
20135#else
20136#define TIMER_START
20137#define TIMER_END
20138#define TIMER_ELAPSED     ((sqlite_uint64)0)
20139#endif
20140
20141/*
20142** If we compile with the SQLITE_TEST macro set, then the following block
20143** of code will give us the ability to simulate a disk I/O error.  This
20144** is used for testing the I/O recovery logic.
20145*/
20146#ifdef SQLITE_TEST
20147SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20148SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20149SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20150SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20151SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20152SQLITE_API int sqlite3_diskfull_pending = 0;
20153SQLITE_API int sqlite3_diskfull = 0;
20154#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
20155#define SimulateIOError(CODE)  \
20156  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
20157       || sqlite3_io_error_pending-- == 1 )  \
20158              { local_ioerr(); CODE; }
20159static void local_ioerr(){
20160  IOTRACE(("IOERR\n"));
20161  sqlite3_io_error_hit++;
20162  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
20163}
20164#define SimulateDiskfullError(CODE) \
20165   if( sqlite3_diskfull_pending ){ \
20166     if( sqlite3_diskfull_pending == 1 ){ \
20167       local_ioerr(); \
20168       sqlite3_diskfull = 1; \
20169       sqlite3_io_error_hit = 1; \
20170       CODE; \
20171     }else{ \
20172       sqlite3_diskfull_pending--; \
20173     } \
20174   }
20175#else
20176#define SimulateIOErrorBenign(X)
20177#define SimulateIOError(A)
20178#define SimulateDiskfullError(A)
20179#endif
20180
20181/*
20182** When testing, keep a count of the number of open files.
20183*/
20184#ifdef SQLITE_TEST
20185SQLITE_API int sqlite3_open_file_count = 0;
20186#define OpenCounter(X)  sqlite3_open_file_count+=(X)
20187#else
20188#define OpenCounter(X)
20189#endif
20190
20191#endif /* !defined(_OS_COMMON_H_) */
20192
20193/************** End of os_common.h *******************************************/
20194/************** Continuing where we left off in os_os2.c *********************/
20195
20196/*
20197** The os2File structure is subclass of sqlite3_file specific for the OS/2
20198** protability layer.
20199*/
20200typedef struct os2File os2File;
20201struct os2File {
20202  const sqlite3_io_methods *pMethod;  /* Always the first entry */
20203  HFILE h;                  /* Handle for accessing the file */
20204  char* pathToDel;          /* Name of file to delete on close, NULL if not */
20205  unsigned char locktype;   /* Type of lock currently held on this file */
20206};
20207
20208#define LOCK_TIMEOUT 10L /* the default locking timeout */
20209
20210/*****************************************************************************
20211** The next group of routines implement the I/O methods specified
20212** by the sqlite3_io_methods object.
20213******************************************************************************/
20214
20215/*
20216** Close a file.
20217*/
20218static int os2Close( sqlite3_file *id ){
20219  APIRET rc = NO_ERROR;
20220  os2File *pFile;
20221  if( id && (pFile = (os2File*)id) != 0 ){
20222    OSTRACE2( "CLOSE %d\n", pFile->h );
20223    rc = DosClose( pFile->h );
20224    pFile->locktype = NO_LOCK;
20225    if( pFile->pathToDel != NULL ){
20226      rc = DosForceDelete( (PSZ)pFile->pathToDel );
20227      free( pFile->pathToDel );
20228      pFile->pathToDel = NULL;
20229    }
20230    id = 0;
20231    OpenCounter( -1 );
20232  }
20233
20234  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20235}
20236
20237/*
20238** Read data from a file into a buffer.  Return SQLITE_OK if all
20239** bytes were read successfully and SQLITE_IOERR if anything goes
20240** wrong.
20241*/
20242static int os2Read(
20243  sqlite3_file *id,               /* File to read from */
20244  void *pBuf,                     /* Write content into this buffer */
20245  int amt,                        /* Number of bytes to read */
20246  sqlite3_int64 offset            /* Begin reading at this offset */
20247){
20248  ULONG fileLocation = 0L;
20249  ULONG got;
20250  os2File *pFile = (os2File*)id;
20251  assert( id!=0 );
20252  SimulateIOError( return SQLITE_IOERR_READ );
20253  OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
20254  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20255    return SQLITE_IOERR;
20256  }
20257  if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
20258    return SQLITE_IOERR_READ;
20259  }
20260  if( got == (ULONG)amt )
20261    return SQLITE_OK;
20262  else {
20263    /* Unread portions of the input buffer must be zero-filled */
20264    memset(&((char*)pBuf)[got], 0, amt-got);
20265    return SQLITE_IOERR_SHORT_READ;
20266  }
20267}
20268
20269/*
20270** Write data from a buffer into a file.  Return SQLITE_OK on success
20271** or some other error code on failure.
20272*/
20273static int os2Write(
20274  sqlite3_file *id,               /* File to write into */
20275  const void *pBuf,               /* The bytes to be written */
20276  int amt,                        /* Number of bytes to write */
20277  sqlite3_int64 offset            /* Offset into the file to begin writing at */
20278){
20279  ULONG fileLocation = 0L;
20280  APIRET rc = NO_ERROR;
20281  ULONG wrote;
20282  os2File *pFile = (os2File*)id;
20283  assert( id!=0 );
20284  SimulateIOError( return SQLITE_IOERR_WRITE );
20285  SimulateDiskfullError( return SQLITE_FULL );
20286  OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
20287  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20288    return SQLITE_IOERR;
20289  }
20290  assert( amt>0 );
20291  while( amt > 0 &&
20292         ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
20293         wrote > 0
20294  ){
20295    amt -= wrote;
20296    pBuf = &((char*)pBuf)[wrote];
20297  }
20298
20299  return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
20300}
20301
20302/*
20303** Truncate an open file to a specified size
20304*/
20305static int os2Truncate( sqlite3_file *id, i64 nByte ){
20306  APIRET rc = NO_ERROR;
20307  os2File *pFile = (os2File*)id;
20308  OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
20309  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
20310  rc = DosSetFileSize( pFile->h, nByte );
20311  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
20312}
20313
20314#ifdef SQLITE_TEST
20315/*
20316** Count the number of fullsyncs and normal syncs.  This is used to test
20317** that syncs and fullsyncs are occuring at the right times.
20318*/
20319SQLITE_API int sqlite3_sync_count = 0;
20320SQLITE_API int sqlite3_fullsync_count = 0;
20321#endif
20322
20323/*
20324** Make sure all writes to a particular file are committed to disk.
20325*/
20326static int os2Sync( sqlite3_file *id, int flags ){
20327  os2File *pFile = (os2File*)id;
20328  OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
20329#ifdef SQLITE_TEST
20330  if( flags & SQLITE_SYNC_FULL){
20331    sqlite3_fullsync_count++;
20332  }
20333  sqlite3_sync_count++;
20334#endif
20335  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
20336  ** no-op
20337  */
20338#ifdef SQLITE_NO_SYNC
20339  UNUSED_PARAMETER(pFile);
20340  return SQLITE_OK;
20341#else
20342  return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20343#endif
20344}
20345
20346/*
20347** Determine the current size of a file in bytes
20348*/
20349static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
20350  APIRET rc = NO_ERROR;
20351  FILESTATUS3 fsts3FileInfo;
20352  memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
20353  assert( id!=0 );
20354  SimulateIOError( return SQLITE_IOERR_FSTAT );
20355  rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
20356  if( rc == NO_ERROR ){
20357    *pSize = fsts3FileInfo.cbFile;
20358    return SQLITE_OK;
20359  }else{
20360    return SQLITE_IOERR_FSTAT;
20361  }
20362}
20363
20364/*
20365** Acquire a reader lock.
20366*/
20367static int getReadLock( os2File *pFile ){
20368  FILELOCK  LockArea,
20369            UnlockArea;
20370  APIRET res;
20371  memset(&LockArea, 0, sizeof(LockArea));
20372  memset(&UnlockArea, 0, sizeof(UnlockArea));
20373  LockArea.lOffset = SHARED_FIRST;
20374  LockArea.lRange = SHARED_SIZE;
20375  UnlockArea.lOffset = 0L;
20376  UnlockArea.lRange = 0L;
20377  res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20378  OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
20379  return res;
20380}
20381
20382/*
20383** Undo a readlock
20384*/
20385static int unlockReadLock( os2File *id ){
20386  FILELOCK  LockArea,
20387            UnlockArea;
20388  APIRET res;
20389  memset(&LockArea, 0, sizeof(LockArea));
20390  memset(&UnlockArea, 0, sizeof(UnlockArea));
20391  LockArea.lOffset = 0L;
20392  LockArea.lRange = 0L;
20393  UnlockArea.lOffset = SHARED_FIRST;
20394  UnlockArea.lRange = SHARED_SIZE;
20395  res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20396  OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
20397  return res;
20398}
20399
20400/*
20401** Lock the file with the lock specified by parameter locktype - one
20402** of the following:
20403**
20404**     (1) SHARED_LOCK
20405**     (2) RESERVED_LOCK
20406**     (3) PENDING_LOCK
20407**     (4) EXCLUSIVE_LOCK
20408**
20409** Sometimes when requesting one lock state, additional lock states
20410** are inserted in between.  The locking might fail on one of the later
20411** transitions leaving the lock state different from what it started but
20412** still short of its goal.  The following chart shows the allowed
20413** transitions and the inserted intermediate states:
20414**
20415**    UNLOCKED -> SHARED
20416**    SHARED -> RESERVED
20417**    SHARED -> (PENDING) -> EXCLUSIVE
20418**    RESERVED -> (PENDING) -> EXCLUSIVE
20419**    PENDING -> EXCLUSIVE
20420**
20421** This routine will only increase a lock.  The os2Unlock() routine
20422** erases all locks at once and returns us immediately to locking level 0.
20423** It is not possible to lower the locking level one step at a time.  You
20424** must go straight to locking level 0.
20425*/
20426static int os2Lock( sqlite3_file *id, int locktype ){
20427  int rc = SQLITE_OK;       /* Return code from subroutines */
20428  APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
20429  int newLocktype;       /* Set pFile->locktype to this value before exiting */
20430  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
20431  FILELOCK  LockArea,
20432            UnlockArea;
20433  os2File *pFile = (os2File*)id;
20434  memset(&LockArea, 0, sizeof(LockArea));
20435  memset(&UnlockArea, 0, sizeof(UnlockArea));
20436  assert( pFile!=0 );
20437  OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
20438
20439  /* If there is already a lock of this type or more restrictive on the
20440  ** os2File, do nothing. Don't use the end_lock: exit path, as
20441  ** sqlite3_mutex_enter() hasn't been called yet.
20442  */
20443  if( pFile->locktype>=locktype ){
20444    OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
20445    return SQLITE_OK;
20446  }
20447
20448  /* Make sure the locking sequence is correct
20449  */
20450  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
20451  assert( locktype!=PENDING_LOCK );
20452  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
20453
20454  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
20455  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
20456  ** the PENDING_LOCK byte is temporary.
20457  */
20458  newLocktype = pFile->locktype;
20459  if( pFile->locktype==NO_LOCK
20460      || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
20461  ){
20462    LockArea.lOffset = PENDING_BYTE;
20463    LockArea.lRange = 1L;
20464    UnlockArea.lOffset = 0L;
20465    UnlockArea.lRange = 0L;
20466
20467    /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
20468    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
20469    if( res == NO_ERROR ){
20470      gotPendingLock = 1;
20471      OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
20472    }
20473  }
20474
20475  /* Acquire a shared lock
20476  */
20477  if( locktype==SHARED_LOCK && res == NO_ERROR ){
20478    assert( pFile->locktype==NO_LOCK );
20479    res = getReadLock(pFile);
20480    if( res == NO_ERROR ){
20481      newLocktype = SHARED_LOCK;
20482    }
20483    OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
20484  }
20485
20486  /* Acquire a RESERVED lock
20487  */
20488  if( locktype==RESERVED_LOCK && res == NO_ERROR ){
20489    assert( pFile->locktype==SHARED_LOCK );
20490    LockArea.lOffset = RESERVED_BYTE;
20491    LockArea.lRange = 1L;
20492    UnlockArea.lOffset = 0L;
20493    UnlockArea.lRange = 0L;
20494    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20495    if( res == NO_ERROR ){
20496      newLocktype = RESERVED_LOCK;
20497    }
20498    OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
20499  }
20500
20501  /* Acquire a PENDING lock
20502  */
20503  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20504    newLocktype = PENDING_LOCK;
20505    gotPendingLock = 0;
20506    OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
20507  }
20508
20509  /* Acquire an EXCLUSIVE lock
20510  */
20511  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
20512    assert( pFile->locktype>=SHARED_LOCK );
20513    res = unlockReadLock(pFile);
20514    OSTRACE2( "unreadlock = %d\n", res );
20515    LockArea.lOffset = SHARED_FIRST;
20516    LockArea.lRange = SHARED_SIZE;
20517    UnlockArea.lOffset = 0L;
20518    UnlockArea.lRange = 0L;
20519    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20520    if( res == NO_ERROR ){
20521      newLocktype = EXCLUSIVE_LOCK;
20522    }else{
20523      OSTRACE2( "OS/2 error-code = %d\n", res );
20524      getReadLock(pFile);
20525    }
20526    OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
20527  }
20528
20529  /* If we are holding a PENDING lock that ought to be released, then
20530  ** release it now.
20531  */
20532  if( gotPendingLock && locktype==SHARED_LOCK ){
20533    int r;
20534    LockArea.lOffset = 0L;
20535    LockArea.lRange = 0L;
20536    UnlockArea.lOffset = PENDING_BYTE;
20537    UnlockArea.lRange = 1L;
20538    r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20539    OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
20540  }
20541
20542  /* Update the state of the lock has held in the file descriptor then
20543  ** return the appropriate result code.
20544  */
20545  if( res == NO_ERROR ){
20546    rc = SQLITE_OK;
20547  }else{
20548    OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
20549              locktype, newLocktype );
20550    rc = SQLITE_BUSY;
20551  }
20552  pFile->locktype = newLocktype;
20553  OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
20554  return rc;
20555}
20556
20557/*
20558** This routine checks if there is a RESERVED lock held on the specified
20559** file by this or any other process. If such a lock is held, return
20560** non-zero, otherwise zero.
20561*/
20562static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
20563  int r = 0;
20564  os2File *pFile = (os2File*)id;
20565  assert( pFile!=0 );
20566  if( pFile->locktype>=RESERVED_LOCK ){
20567    r = 1;
20568    OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
20569  }else{
20570    FILELOCK  LockArea,
20571              UnlockArea;
20572    APIRET rc = NO_ERROR;
20573    memset(&LockArea, 0, sizeof(LockArea));
20574    memset(&UnlockArea, 0, sizeof(UnlockArea));
20575    LockArea.lOffset = RESERVED_BYTE;
20576    LockArea.lRange = 1L;
20577    UnlockArea.lOffset = 0L;
20578    UnlockArea.lRange = 0L;
20579    rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20580    OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
20581    if( rc == NO_ERROR ){
20582      APIRET rcu = NO_ERROR; /* return code for unlocking */
20583      LockArea.lOffset = 0L;
20584      LockArea.lRange = 0L;
20585      UnlockArea.lOffset = RESERVED_BYTE;
20586      UnlockArea.lRange = 1L;
20587      rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20588      OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
20589    }
20590    r = !(rc == NO_ERROR);
20591    OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
20592  }
20593  *pOut = r;
20594  return SQLITE_OK;
20595}
20596
20597/*
20598** Lower the locking level on file descriptor id to locktype.  locktype
20599** must be either NO_LOCK or SHARED_LOCK.
20600**
20601** If the locking level of the file descriptor is already at or below
20602** the requested locking level, this routine is a no-op.
20603**
20604** It is not possible for this routine to fail if the second argument
20605** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
20606** might return SQLITE_IOERR;
20607*/
20608static int os2Unlock( sqlite3_file *id, int locktype ){
20609  int type;
20610  os2File *pFile = (os2File*)id;
20611  APIRET rc = SQLITE_OK;
20612  APIRET res = NO_ERROR;
20613  FILELOCK  LockArea,
20614            UnlockArea;
20615  memset(&LockArea, 0, sizeof(LockArea));
20616  memset(&UnlockArea, 0, sizeof(UnlockArea));
20617  assert( pFile!=0 );
20618  assert( locktype<=SHARED_LOCK );
20619  OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
20620  type = pFile->locktype;
20621  if( type>=EXCLUSIVE_LOCK ){
20622    LockArea.lOffset = 0L;
20623    LockArea.lRange = 0L;
20624    UnlockArea.lOffset = SHARED_FIRST;
20625    UnlockArea.lRange = SHARED_SIZE;
20626    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20627    OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
20628    if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
20629      /* This should never happen.  We should always be able to
20630      ** reacquire the read lock */
20631      OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
20632      rc = SQLITE_IOERR_UNLOCK;
20633    }
20634  }
20635  if( type>=RESERVED_LOCK ){
20636    LockArea.lOffset = 0L;
20637    LockArea.lRange = 0L;
20638    UnlockArea.lOffset = RESERVED_BYTE;
20639    UnlockArea.lRange = 1L;
20640    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20641    OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
20642  }
20643  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
20644    res = unlockReadLock(pFile);
20645    OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
20646  }
20647  if( type>=PENDING_LOCK ){
20648    LockArea.lOffset = 0L;
20649    LockArea.lRange = 0L;
20650    UnlockArea.lOffset = PENDING_BYTE;
20651    UnlockArea.lRange = 1L;
20652    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
20653    OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
20654  }
20655  pFile->locktype = locktype;
20656  OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
20657  return rc;
20658}
20659
20660/*
20661** Control and query of the open file handle.
20662*/
20663static int os2FileControl(sqlite3_file *id, int op, void *pArg){
20664  switch( op ){
20665    case SQLITE_FCNTL_LOCKSTATE: {
20666      *(int*)pArg = ((os2File*)id)->locktype;
20667      OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
20668      return SQLITE_OK;
20669    }
20670  }
20671  return SQLITE_ERROR;
20672}
20673
20674/*
20675** Return the sector size in bytes of the underlying block device for
20676** the specified file. This is almost always 512 bytes, but may be
20677** larger for some devices.
20678**
20679** SQLite code assumes this function cannot fail. It also assumes that
20680** if two files are created in the same file-system directory (i.e.
20681** a database and its journal file) that the sector size will be the
20682** same for both.
20683*/
20684static int os2SectorSize(sqlite3_file *id){
20685  return SQLITE_DEFAULT_SECTOR_SIZE;
20686}
20687
20688/*
20689** Return a vector of device characteristics.
20690*/
20691static int os2DeviceCharacteristics(sqlite3_file *id){
20692  return 0;
20693}
20694
20695
20696/*
20697** Character set conversion objects used by conversion routines.
20698*/
20699static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
20700static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
20701
20702/*
20703** Helper function to initialize the conversion objects from and to UTF-8.
20704*/
20705static void initUconvObjects( void ){
20706  if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
20707    ucUtf8 = NULL;
20708  if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
20709    uclCp = NULL;
20710}
20711
20712/*
20713** Helper function to free the conversion objects from and to UTF-8.
20714*/
20715static void freeUconvObjects( void ){
20716  if ( ucUtf8 )
20717    UniFreeUconvObject( ucUtf8 );
20718  if ( uclCp )
20719    UniFreeUconvObject( uclCp );
20720  ucUtf8 = NULL;
20721  uclCp = NULL;
20722}
20723
20724/*
20725** Helper function to convert UTF-8 filenames to local OS/2 codepage.
20726** The two-step process: first convert the incoming UTF-8 string
20727** into UCS-2 and then from UCS-2 to the current codepage.
20728** The returned char pointer has to be freed.
20729*/
20730static char *convertUtf8PathToCp( const char *in ){
20731  UniChar tempPath[CCHMAXPATH];
20732  char *out = (char *)calloc( CCHMAXPATH, 1 );
20733
20734  if( !out )
20735    return NULL;
20736
20737  if( !ucUtf8 || !uclCp )
20738    initUconvObjects();
20739
20740  /* determine string for the conversion of UTF-8 which is CP1208 */
20741  if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20742    return out; /* if conversion fails, return the empty string */
20743
20744  /* conversion for current codepage which can be used for paths */
20745  UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
20746
20747  return out;
20748}
20749
20750/*
20751** Helper function to convert filenames from local codepage to UTF-8.
20752** The two-step process: first convert the incoming codepage-specific
20753** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
20754** The returned char pointer has to be freed.
20755**
20756** This function is non-static to be able to use this in shell.c and
20757** similar applications that take command line arguments.
20758*/
20759char *convertCpPathToUtf8( const char *in ){
20760  UniChar tempPath[CCHMAXPATH];
20761  char *out = (char *)calloc( CCHMAXPATH, 1 );
20762
20763  if( !out )
20764    return NULL;
20765
20766  if( !ucUtf8 || !uclCp )
20767    initUconvObjects();
20768
20769  /* conversion for current codepage which can be used for paths */
20770  if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
20771    return out; /* if conversion fails, return the empty string */
20772
20773  /* determine string for the conversion of UTF-8 which is CP1208 */
20774  UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
20775
20776  return out;
20777}
20778
20779/*
20780** This vector defines all the methods that can operate on an
20781** sqlite3_file for os2.
20782*/
20783static const sqlite3_io_methods os2IoMethod = {
20784  1,                        /* iVersion */
20785  os2Close,
20786  os2Read,
20787  os2Write,
20788  os2Truncate,
20789  os2Sync,
20790  os2FileSize,
20791  os2Lock,
20792  os2Unlock,
20793  os2CheckReservedLock,
20794  os2FileControl,
20795  os2SectorSize,
20796  os2DeviceCharacteristics
20797};
20798
20799/***************************************************************************
20800** Here ends the I/O methods that form the sqlite3_io_methods object.
20801**
20802** The next block of code implements the VFS methods.
20803****************************************************************************/
20804
20805/*
20806** Create a temporary file name in zBuf.  zBuf must be big enough to
20807** hold at pVfs->mxPathname characters.
20808*/
20809static int getTempname(int nBuf, char *zBuf ){
20810  static const unsigned char zChars[] =
20811    "abcdefghijklmnopqrstuvwxyz"
20812    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
20813    "0123456789";
20814  int i, j;
20815  char zTempPathBuf[3];
20816  PSZ zTempPath = (PSZ)&zTempPathBuf;
20817  if( sqlite3_temp_directory ){
20818    zTempPath = sqlite3_temp_directory;
20819  }else{
20820    if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
20821      if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
20822        if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
20823           ULONG ulDriveNum = 0, ulDriveMap = 0;
20824           DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
20825           sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
20826        }
20827      }
20828    }
20829  }
20830  /* Strip off a trailing slashes or backslashes, otherwise we would get *
20831   * multiple (back)slashes which causes DosOpen() to fail.              *
20832   * Trailing spaces are not allowed, either.                            */
20833  j = sqlite3Strlen30(zTempPath);
20834  while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
20835                    || zTempPath[j-1] == ' ' ) ){
20836    j--;
20837  }
20838  zTempPath[j] = '\0';
20839  if( !sqlite3_temp_directory ){
20840    char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
20841    sqlite3_snprintf( nBuf-30, zBuf,
20842                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
20843    free( zTempPathUTF );
20844  }else{
20845    sqlite3_snprintf( nBuf-30, zBuf,
20846                      "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
20847  }
20848  j = sqlite3Strlen30( zBuf );
20849  sqlite3_randomness( 20, &zBuf[j] );
20850  for( i = 0; i < 20; i++, j++ ){
20851    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
20852  }
20853  zBuf[j] = 0;
20854  OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
20855  return SQLITE_OK;
20856}
20857
20858
20859/*
20860** Turn a relative pathname into a full pathname.  Write the full
20861** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
20862** bytes in size.
20863*/
20864static int os2FullPathname(
20865  sqlite3_vfs *pVfs,          /* Pointer to vfs object */
20866  const char *zRelative,      /* Possibly relative input path */
20867  int nFull,                  /* Size of output buffer in bytes */
20868  char *zFull                 /* Output buffer */
20869){
20870  char *zRelativeCp = convertUtf8PathToCp( zRelative );
20871  char zFullCp[CCHMAXPATH] = "\0";
20872  char *zFullUTF;
20873  APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
20874                                CCHMAXPATH );
20875  free( zRelativeCp );
20876  zFullUTF = convertCpPathToUtf8( zFullCp );
20877  sqlite3_snprintf( nFull, zFull, zFullUTF );
20878  free( zFullUTF );
20879  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20880}
20881
20882
20883/*
20884** Open a file.
20885*/
20886static int os2Open(
20887  sqlite3_vfs *pVfs,            /* Not used */
20888  const char *zName,            /* Name of the file */
20889  sqlite3_file *id,             /* Write the SQLite file handle here */
20890  int flags,                    /* Open mode flags */
20891  int *pOutFlags                /* Status return flags */
20892){
20893  HFILE h;
20894  ULONG ulFileAttribute = FILE_NORMAL;
20895  ULONG ulOpenFlags = 0;
20896  ULONG ulOpenMode = 0;
20897  os2File *pFile = (os2File*)id;
20898  APIRET rc = NO_ERROR;
20899  ULONG ulAction;
20900  char *zNameCp;
20901  char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
20902
20903  /* If the second argument to this function is NULL, generate a
20904  ** temporary file name to use
20905  */
20906  if( !zName ){
20907    int rc = getTempname(CCHMAXPATH+1, zTmpname);
20908    if( rc!=SQLITE_OK ){
20909      return rc;
20910    }
20911    zName = zTmpname;
20912  }
20913
20914
20915  memset( pFile, 0, sizeof(*pFile) );
20916
20917  OSTRACE2( "OPEN want %d\n", flags );
20918
20919  if( flags & SQLITE_OPEN_READWRITE ){
20920    ulOpenMode |= OPEN_ACCESS_READWRITE;
20921    OSTRACE1( "OPEN read/write\n" );
20922  }else{
20923    ulOpenMode |= OPEN_ACCESS_READONLY;
20924    OSTRACE1( "OPEN read only\n" );
20925  }
20926
20927  if( flags & SQLITE_OPEN_CREATE ){
20928    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
20929    OSTRACE1( "OPEN open new/create\n" );
20930  }else{
20931    ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
20932    OSTRACE1( "OPEN open existing\n" );
20933  }
20934
20935  if( flags & SQLITE_OPEN_MAIN_DB ){
20936    ulOpenMode |= OPEN_SHARE_DENYNONE;
20937    OSTRACE1( "OPEN share read/write\n" );
20938  }else{
20939    ulOpenMode |= OPEN_SHARE_DENYWRITE;
20940    OSTRACE1( "OPEN share read only\n" );
20941  }
20942
20943  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
20944    char pathUtf8[CCHMAXPATH];
20945#ifdef NDEBUG /* when debugging we want to make sure it is deleted */
20946    ulFileAttribute = FILE_HIDDEN;
20947#endif
20948    os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
20949    pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
20950    OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
20951  }else{
20952    pFile->pathToDel = NULL;
20953    OSTRACE1( "OPEN normal file attribute\n" );
20954  }
20955
20956  /* always open in random access mode for possibly better speed */
20957  ulOpenMode |= OPEN_FLAGS_RANDOM;
20958  ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
20959  ulOpenMode |= OPEN_FLAGS_NOINHERIT;
20960
20961  zNameCp = convertUtf8PathToCp( zName );
20962  rc = DosOpen( (PSZ)zNameCp,
20963                &h,
20964                &ulAction,
20965                0L,
20966                ulFileAttribute,
20967                ulOpenFlags,
20968                ulOpenMode,
20969                (PEAOP2)NULL );
20970  free( zNameCp );
20971  if( rc != NO_ERROR ){
20972    OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
20973              rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
20974    if( pFile->pathToDel )
20975      free( pFile->pathToDel );
20976    pFile->pathToDel = NULL;
20977    if( flags & SQLITE_OPEN_READWRITE ){
20978      OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
20979      return os2Open( pVfs, zName, id,
20980                      ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
20981                      pOutFlags );
20982    }else{
20983      return SQLITE_CANTOPEN;
20984    }
20985  }
20986
20987  if( pOutFlags ){
20988    *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
20989  }
20990
20991  pFile->pMethod = &os2IoMethod;
20992  pFile->h = h;
20993  OpenCounter(+1);
20994  OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
20995  return SQLITE_OK;
20996}
20997
20998/*
20999** Delete the named file.
21000*/
21001static int os2Delete(
21002  sqlite3_vfs *pVfs,                     /* Not used on os2 */
21003  const char *zFilename,                 /* Name of file to delete */
21004  int syncDir                            /* Not used on os2 */
21005){
21006  APIRET rc = NO_ERROR;
21007  char *zFilenameCp = convertUtf8PathToCp( zFilename );
21008  SimulateIOError( return SQLITE_IOERR_DELETE );
21009  rc = DosDelete( (PSZ)zFilenameCp );
21010  free( zFilenameCp );
21011  OSTRACE2( "DELETE \"%s\"\n", zFilename );
21012  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
21013}
21014
21015/*
21016** Check the existance and status of a file.
21017*/
21018static int os2Access(
21019  sqlite3_vfs *pVfs,        /* Not used on os2 */
21020  const char *zFilename,    /* Name of file to check */
21021  int flags,                /* Type of test to make on this file */
21022  int *pOut                 /* Write results here */
21023){
21024  FILESTATUS3 fsts3ConfigInfo;
21025  APIRET rc = NO_ERROR;
21026  char *zFilenameCp = convertUtf8PathToCp( zFilename );
21027
21028  memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
21029  rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
21030                         &fsts3ConfigInfo, sizeof(FILESTATUS3) );
21031  free( zFilenameCp );
21032  OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
21033            fsts3ConfigInfo.attrFile, flags, rc );
21034  switch( flags ){
21035    case SQLITE_ACCESS_READ:
21036    case SQLITE_ACCESS_EXISTS:
21037      rc = (rc == NO_ERROR);
21038      OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
21039      break;
21040    case SQLITE_ACCESS_READWRITE:
21041      rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
21042      OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
21043      break;
21044    default:
21045      assert( !"Invalid flags argument" );
21046  }
21047  *pOut = rc;
21048  return SQLITE_OK;
21049}
21050
21051
21052#ifndef SQLITE_OMIT_LOAD_EXTENSION
21053/*
21054** Interfaces for opening a shared library, finding entry points
21055** within the shared library, and closing the shared library.
21056*/
21057/*
21058** Interfaces for opening a shared library, finding entry points
21059** within the shared library, and closing the shared library.
21060*/
21061static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
21062  UCHAR loadErr[256];
21063  HMODULE hmod;
21064  APIRET rc;
21065  char *zFilenameCp = convertUtf8PathToCp(zFilename);
21066  rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
21067  free(zFilenameCp);
21068  return rc != NO_ERROR ? 0 : (void*)hmod;
21069}
21070/*
21071** A no-op since the error code is returned on the DosLoadModule call.
21072** os2Dlopen returns zero if DosLoadModule is not successful.
21073*/
21074static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
21075/* no-op */
21076}
21077static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
21078  PFN pfn;
21079  APIRET rc;
21080  rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
21081  if( rc != NO_ERROR ){
21082    /* if the symbol itself was not found, search again for the same
21083     * symbol with an extra underscore, that might be needed depending
21084     * on the calling convention */
21085    char _zSymbol[256] = "_";
21086    strncat(_zSymbol, zSymbol, 255);
21087    rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
21088  }
21089  return rc != NO_ERROR ? 0 : (void*)pfn;
21090}
21091static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
21092  DosFreeModule((HMODULE)pHandle);
21093}
21094#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
21095  #define os2DlOpen 0
21096  #define os2DlError 0
21097  #define os2DlSym 0
21098  #define os2DlClose 0
21099#endif
21100
21101
21102/*
21103** Write up to nBuf bytes of randomness into zBuf.
21104*/
21105static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
21106  int n = 0;
21107#if defined(SQLITE_TEST)
21108  n = nBuf;
21109  memset(zBuf, 0, nBuf);
21110#else
21111  int sizeofULong = sizeof(ULONG);
21112  if( (int)sizeof(DATETIME) <= nBuf - n ){
21113    DATETIME x;
21114    DosGetDateTime(&x);
21115    memcpy(&zBuf[n], &x, sizeof(x));
21116    n += sizeof(x);
21117  }
21118
21119  if( sizeofULong <= nBuf - n ){
21120    PPIB ppib;
21121    DosGetInfoBlocks(NULL, &ppib);
21122    memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
21123    n += sizeofULong;
21124  }
21125
21126  if( sizeofULong <= nBuf - n ){
21127    PTIB ptib;
21128    DosGetInfoBlocks(&ptib, NULL);
21129    memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
21130    n += sizeofULong;
21131  }
21132
21133  /* if we still haven't filled the buffer yet the following will */
21134  /* grab everything once instead of making several calls for a single item */
21135  if( sizeofULong <= nBuf - n ){
21136    ULONG ulSysInfo[QSV_MAX];
21137    DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
21138
21139    memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
21140    n += sizeofULong;
21141
21142    if( sizeofULong <= nBuf - n ){
21143      memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
21144      n += sizeofULong;
21145    }
21146    if( sizeofULong <= nBuf - n ){
21147      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
21148      n += sizeofULong;
21149    }
21150    if( sizeofULong <= nBuf - n ){
21151      memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
21152      n += sizeofULong;
21153    }
21154    if( sizeofULong <= nBuf - n ){
21155      memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
21156      n += sizeofULong;
21157    }
21158  }
21159#endif
21160
21161  return n;
21162}
21163
21164/*
21165** Sleep for a little while.  Return the amount of time slept.
21166** The argument is the number of microseconds we want to sleep.
21167** The return value is the number of microseconds of sleep actually
21168** requested from the underlying operating system, a number which
21169** might be greater than or equal to the argument, but not less
21170** than the argument.
21171*/
21172static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
21173  DosSleep( (microsec/1000) );
21174  return microsec;
21175}
21176
21177/*
21178** The following variable, if set to a non-zero value, becomes the result
21179** returned from sqlite3OsCurrentTime().  This is used for testing.
21180*/
21181#ifdef SQLITE_TEST
21182SQLITE_API int sqlite3_current_time = 0;
21183#endif
21184
21185/*
21186** Find the current time (in Universal Coordinated Time).  Write the
21187** current time and date as a Julian Day number into *prNow and
21188** return 0.  Return 1 if the time and date cannot be found.
21189*/
21190int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
21191  double now;
21192  SHORT minute; /* needs to be able to cope with negative timezone offset */
21193  USHORT second, hour,
21194         day, month, year;
21195  DATETIME dt;
21196  DosGetDateTime( &dt );
21197  second = (USHORT)dt.seconds;
21198  minute = (SHORT)dt.minutes + dt.timezone;
21199  hour = (USHORT)dt.hours;
21200  day = (USHORT)dt.day;
21201  month = (USHORT)dt.month;
21202  year = (USHORT)dt.year;
21203
21204  /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
21205     http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
21206  /* Calculate the Julian days */
21207  now = day - 32076 +
21208    1461*(year + 4800 + (month - 14)/12)/4 +
21209    367*(month - 2 - (month - 14)/12*12)/12 -
21210    3*((year + 4900 + (month - 14)/12)/100)/4;
21211
21212  /* Add the fractional hours, mins and seconds */
21213  now += (hour + 12.0)/24.0;
21214  now += minute/1440.0;
21215  now += second/86400.0;
21216  *prNow = now;
21217#ifdef SQLITE_TEST
21218  if( sqlite3_current_time ){
21219    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
21220  }
21221#endif
21222  return 0;
21223}
21224
21225static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
21226  return 0;
21227}
21228
21229/*
21230** Initialize and deinitialize the operating system interface.
21231*/
21232SQLITE_API int sqlite3_os_init(void){
21233  static sqlite3_vfs os2Vfs = {
21234    1,                 /* iVersion */
21235    sizeof(os2File),   /* szOsFile */
21236    CCHMAXPATH,        /* mxPathname */
21237    0,                 /* pNext */
21238    "os2",             /* zName */
21239    0,                 /* pAppData */
21240
21241    os2Open,           /* xOpen */
21242    os2Delete,         /* xDelete */
21243    os2Access,         /* xAccess */
21244    os2FullPathname,   /* xFullPathname */
21245    os2DlOpen,         /* xDlOpen */
21246    os2DlError,        /* xDlError */
21247    os2DlSym,          /* xDlSym */
21248    os2DlClose,        /* xDlClose */
21249    os2Randomness,     /* xRandomness */
21250    os2Sleep,          /* xSleep */
21251    os2CurrentTime,    /* xCurrentTime */
21252    os2GetLastError    /* xGetLastError */
21253  };
21254  sqlite3_vfs_register(&os2Vfs, 1);
21255  initUconvObjects();
21256  return SQLITE_OK;
21257}
21258SQLITE_API int sqlite3_os_end(void){
21259  freeUconvObjects();
21260  return SQLITE_OK;
21261}
21262
21263#endif /* SQLITE_OS_OS2 */
21264
21265/************** End of os_os2.c **********************************************/
21266/************** Begin file os_unix.c *****************************************/
21267/*
21268** 2004 May 22
21269**
21270** The author disclaims copyright to this source code.  In place of
21271** a legal notice, here is a blessing:
21272**
21273**    May you do good and not evil.
21274**    May you find forgiveness for yourself and forgive others.
21275**    May you share freely, never taking more than you give.
21276**
21277******************************************************************************
21278**
21279** This file contains the VFS implementation for unix-like operating systems
21280** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
21281**
21282** There are actually several different VFS implementations in this file.
21283** The differences are in the way that file locking is done.  The default
21284** implementation uses Posix Advisory Locks.  Alternative implementations
21285** use flock(), dot-files, various proprietary locking schemas, or simply
21286** skip locking all together.
21287**
21288** This source file is organized into divisions where the logic for various
21289** subfunctions is contained within the appropriate division.  PLEASE
21290** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
21291** in the correct division and should be clearly labeled.
21292**
21293** The layout of divisions is as follows:
21294**
21295**   *  General-purpose declarations and utility functions.
21296**   *  Unique file ID logic used by VxWorks.
21297**   *  Various locking primitive implementations (all except proxy locking):
21298**      + for Posix Advisory Locks
21299**      + for no-op locks
21300**      + for dot-file locks
21301**      + for flock() locking
21302**      + for named semaphore locks (VxWorks only)
21303**      + for AFP filesystem locks (MacOSX only)
21304**   *  sqlite3_file methods not associated with locking.
21305**   *  Definitions of sqlite3_io_methods objects for all locking
21306**      methods plus "finder" functions for each locking method.
21307**   *  sqlite3_vfs method implementations.
21308**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
21309**   *  Definitions of sqlite3_vfs objects for all locking methods
21310**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
21311*/
21312#if SQLITE_OS_UNIX              /* This file is used on unix only */
21313
21314/*
21315** There are various methods for file locking used for concurrency
21316** control:
21317**
21318**   1. POSIX locking (the default),
21319**   2. No locking,
21320**   3. Dot-file locking,
21321**   4. flock() locking,
21322**   5. AFP locking (OSX only),
21323**   6. Named POSIX semaphores (VXWorks only),
21324**   7. proxy locking. (OSX only)
21325**
21326** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
21327** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
21328** selection of the appropriate locking style based on the filesystem
21329** where the database is located.
21330*/
21331#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
21332#  if defined(__APPLE__)
21333#    define SQLITE_ENABLE_LOCKING_STYLE 1
21334#  else
21335#    define SQLITE_ENABLE_LOCKING_STYLE 0
21336#  endif
21337#endif
21338
21339/*
21340** Define the OS_VXWORKS pre-processor macro to 1 if building on
21341** vxworks, or 0 otherwise.
21342*/
21343#ifndef OS_VXWORKS
21344#  if defined(__RTP__) || defined(_WRS_KERNEL)
21345#    define OS_VXWORKS 1
21346#  else
21347#    define OS_VXWORKS 0
21348#  endif
21349#endif
21350
21351/*
21352** These #defines should enable >2GB file support on Posix if the
21353** underlying operating system supports it.  If the OS lacks
21354** large file support, these should be no-ops.
21355**
21356** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
21357** on the compiler command line.  This is necessary if you are compiling
21358** on a recent machine (ex: RedHat 7.2) but you want your code to work
21359** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
21360** without this option, LFS is enable.  But LFS does not exist in the kernel
21361** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
21362** portability you should omit LFS.
21363**
21364** The previous paragraph was written in 2005.  (This paragraph is written
21365** on 2008-11-28.) These days, all Linux kernels support large files, so
21366** you should probably leave LFS enabled.  But some embedded platforms might
21367** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
21368*/
21369#ifndef SQLITE_DISABLE_LFS
21370# define _LARGE_FILE       1
21371# ifndef _FILE_OFFSET_BITS
21372#   define _FILE_OFFSET_BITS 64
21373# endif
21374# define _LARGEFILE_SOURCE 1
21375#endif
21376
21377/*
21378** standard include files.
21379*/
21380#include <sys/types.h>
21381#include <sys/stat.h>
21382#include <fcntl.h>
21383#include <unistd.h>
21384#include <sys/time.h>
21385#include <errno.h>
21386
21387#if SQLITE_ENABLE_LOCKING_STYLE
21388# include <sys/ioctl.h>
21389# if OS_VXWORKS
21390#  include <semaphore.h>
21391#  include <limits.h>
21392# else
21393#  include <sys/file.h>
21394#  include <sys/param.h>
21395#  include <sys/mount.h>
21396# endif
21397#endif /* SQLITE_ENABLE_LOCKING_STYLE */
21398
21399/*
21400** If we are to be thread-safe, include the pthreads header and define
21401** the SQLITE_UNIX_THREADS macro.
21402*/
21403#if SQLITE_THREADSAFE
21404# define SQLITE_UNIX_THREADS 1
21405#endif
21406
21407/*
21408** Default permissions when creating a new file
21409*/
21410#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
21411# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
21412#endif
21413
21414/*
21415 ** Default permissions when creating auto proxy dir
21416 */
21417#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
21418# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
21419#endif
21420
21421/*
21422** Maximum supported path-length.
21423*/
21424#define MAX_PATHNAME 512
21425
21426/*
21427** Only set the lastErrno if the error code is a real error and not
21428** a normal expected return code of SQLITE_BUSY or SQLITE_OK
21429*/
21430#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
21431
21432
21433/*
21434** Sometimes, after a file handle is closed by SQLite, the file descriptor
21435** cannot be closed immediately. In these cases, instances of the following
21436** structure are used to store the file descriptor while waiting for an
21437** opportunity to either close or reuse it.
21438*/
21439typedef struct UnixUnusedFd UnixUnusedFd;
21440struct UnixUnusedFd {
21441  int fd;                   /* File descriptor to close */
21442  int flags;                /* Flags this file descriptor was opened with */
21443  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
21444};
21445
21446/*
21447** The unixFile structure is subclass of sqlite3_file specific to the unix
21448** VFS implementations.
21449*/
21450typedef struct unixFile unixFile;
21451struct unixFile {
21452  sqlite3_io_methods const *pMethod;  /* Always the first entry */
21453  struct unixOpenCnt *pOpen;       /* Info about all open fd's on this inode */
21454  struct unixLockInfo *pLock;      /* Info about locks on this inode */
21455  int h;                           /* The file descriptor */
21456  int dirfd;                       /* File descriptor for the directory */
21457  unsigned char locktype;          /* The type of lock held on this fd */
21458  int lastErrno;                   /* The unix errno from the last I/O error */
21459  void *lockingContext;            /* Locking style specific state */
21460  UnixUnusedFd *pUnused;           /* Pre-allocated UnixUnusedFd */
21461  int fileFlags;                   /* Miscellanous flags */
21462#if SQLITE_ENABLE_LOCKING_STYLE
21463  int openFlags;                   /* The flags specified at open() */
21464#endif
21465#if SQLITE_THREADSAFE && defined(__linux__)
21466  pthread_t tid;                   /* The thread that "owns" this unixFile */
21467#endif
21468#if OS_VXWORKS
21469  int isDelete;                    /* Delete on close if true */
21470  struct vxworksFileId *pId;       /* Unique file ID */
21471#endif
21472#ifndef NDEBUG
21473  /* The next group of variables are used to track whether or not the
21474  ** transaction counter in bytes 24-27 of database files are updated
21475  ** whenever any part of the database changes.  An assertion fault will
21476  ** occur if a file is updated without also updating the transaction
21477  ** counter.  This test is made to avoid new problems similar to the
21478  ** one described by ticket #3584.
21479  */
21480  unsigned char transCntrChng;   /* True if the transaction counter changed */
21481  unsigned char dbUpdate;        /* True if any part of database file changed */
21482  unsigned char inNormalWrite;   /* True if in a normal write operation */
21483#endif
21484#ifdef SQLITE_TEST
21485  /* In test mode, increase the size of this structure a bit so that
21486  ** it is larger than the struct CrashFile defined in test6.c.
21487  */
21488  char aPadding[32];
21489#endif
21490};
21491
21492/*
21493** The following macros define bits in unixFile.fileFlags
21494*/
21495#define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
21496
21497/*
21498** Include code that is common to all os_*.c files
21499*/
21500/************** Include os_common.h in the middle of os_unix.c ***************/
21501/************** Begin file os_common.h ***************************************/
21502/*
21503** 2004 May 22
21504**
21505** The author disclaims copyright to this source code.  In place of
21506** a legal notice, here is a blessing:
21507**
21508**    May you do good and not evil.
21509**    May you find forgiveness for yourself and forgive others.
21510**    May you share freely, never taking more than you give.
21511**
21512******************************************************************************
21513**
21514** This file contains macros and a little bit of code that is common to
21515** all of the platform-specific files (os_*.c) and is #included into those
21516** files.
21517**
21518** This file should be #included by the os_*.c files only.  It is not a
21519** general purpose header file.
21520*/
21521#ifndef _OS_COMMON_H_
21522#define _OS_COMMON_H_
21523
21524/*
21525** At least two bugs have slipped in because we changed the MEMORY_DEBUG
21526** macro to SQLITE_DEBUG and some older makefiles have not yet made the
21527** switch.  The following code should catch this problem at compile-time.
21528*/
21529#ifdef MEMORY_DEBUG
21530# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
21531#endif
21532
21533#ifdef SQLITE_DEBUG
21534SQLITE_PRIVATE int sqlite3OSTrace = 0;
21535#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
21536#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
21537#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
21538#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
21539#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
21540#define OSTRACE6(X,Y,Z,A,B,C) \
21541    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
21542#define OSTRACE7(X,Y,Z,A,B,C,D) \
21543    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
21544#else
21545#define OSTRACE1(X)
21546#define OSTRACE2(X,Y)
21547#define OSTRACE3(X,Y,Z)
21548#define OSTRACE4(X,Y,Z,A)
21549#define OSTRACE5(X,Y,Z,A,B)
21550#define OSTRACE6(X,Y,Z,A,B,C)
21551#define OSTRACE7(X,Y,Z,A,B,C,D)
21552#endif
21553
21554/*
21555** Macros for performance tracing.  Normally turned off.  Only works
21556** on i486 hardware.
21557*/
21558#ifdef SQLITE_PERFORMANCE_TRACE
21559
21560/*
21561** hwtime.h contains inline assembler code for implementing
21562** high-performance timing routines.
21563*/
21564/************** Include hwtime.h in the middle of os_common.h ****************/
21565/************** Begin file hwtime.h ******************************************/
21566/*
21567** 2008 May 27
21568**
21569** The author disclaims copyright to this source code.  In place of
21570** a legal notice, here is a blessing:
21571**
21572**    May you do good and not evil.
21573**    May you find forgiveness for yourself and forgive others.
21574**    May you share freely, never taking more than you give.
21575**
21576******************************************************************************
21577**
21578** This file contains inline asm code for retrieving "high-performance"
21579** counters for x86 class CPUs.
21580*/
21581#ifndef _HWTIME_H_
21582#define _HWTIME_H_
21583
21584/*
21585** The following routine only works on pentium-class (or newer) processors.
21586** It uses the RDTSC opcode to read the cycle count value out of the
21587** processor and returns that value.  This can be used for high-res
21588** profiling.
21589*/
21590#if (defined(__GNUC__) || defined(_MSC_VER)) && \
21591      (defined(i386) || defined(__i386__) || defined(_M_IX86))
21592
21593  #if defined(__GNUC__)
21594
21595  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21596     unsigned int lo, hi;
21597     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
21598     return (sqlite_uint64)hi << 32 | lo;
21599  }
21600
21601  #elif defined(_MSC_VER)
21602
21603  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
21604     __asm {
21605        rdtsc
21606        ret       ; return value at EDX:EAX
21607     }
21608  }
21609
21610  #endif
21611
21612#elif (defined(__GNUC__) && defined(__x86_64__))
21613
21614  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21615      unsigned long val;
21616      __asm__ __volatile__ ("rdtsc" : "=A" (val));
21617      return val;
21618  }
21619
21620#elif (defined(__GNUC__) && defined(__ppc__))
21621
21622  __inline__ sqlite_uint64 sqlite3Hwtime(void){
21623      unsigned long long retval;
21624      unsigned long junk;
21625      __asm__ __volatile__ ("\n\
21626          1:      mftbu   %1\n\
21627                  mftb    %L0\n\
21628                  mftbu   %0\n\
21629                  cmpw    %0,%1\n\
21630                  bne     1b"
21631                  : "=r" (retval), "=r" (junk));
21632      return retval;
21633  }
21634
21635#else
21636
21637  #error Need implementation of sqlite3Hwtime() for your platform.
21638
21639  /*
21640  ** To compile without implementing sqlite3Hwtime() for your platform,
21641  ** you can remove the above #error and use the following
21642  ** stub function.  You will lose timing support for many
21643  ** of the debugging and testing utilities, but it should at
21644  ** least compile and run.
21645  */
21646SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
21647
21648#endif
21649
21650#endif /* !defined(_HWTIME_H_) */
21651
21652/************** End of hwtime.h **********************************************/
21653/************** Continuing where we left off in os_common.h ******************/
21654
21655static sqlite_uint64 g_start;
21656static sqlite_uint64 g_elapsed;
21657#define TIMER_START       g_start=sqlite3Hwtime()
21658#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
21659#define TIMER_ELAPSED     g_elapsed
21660#else
21661#define TIMER_START
21662#define TIMER_END
21663#define TIMER_ELAPSED     ((sqlite_uint64)0)
21664#endif
21665
21666/*
21667** If we compile with the SQLITE_TEST macro set, then the following block
21668** of code will give us the ability to simulate a disk I/O error.  This
21669** is used for testing the I/O recovery logic.
21670*/
21671#ifdef SQLITE_TEST
21672SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
21673SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
21674SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
21675SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
21676SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
21677SQLITE_API int sqlite3_diskfull_pending = 0;
21678SQLITE_API int sqlite3_diskfull = 0;
21679#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
21680#define SimulateIOError(CODE)  \
21681  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
21682       || sqlite3_io_error_pending-- == 1 )  \
21683              { local_ioerr(); CODE; }
21684static void local_ioerr(){
21685  IOTRACE(("IOERR\n"));
21686  sqlite3_io_error_hit++;
21687  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
21688}
21689#define SimulateDiskfullError(CODE) \
21690   if( sqlite3_diskfull_pending ){ \
21691     if( sqlite3_diskfull_pending == 1 ){ \
21692       local_ioerr(); \
21693       sqlite3_diskfull = 1; \
21694       sqlite3_io_error_hit = 1; \
21695       CODE; \
21696     }else{ \
21697       sqlite3_diskfull_pending--; \
21698     } \
21699   }
21700#else
21701#define SimulateIOErrorBenign(X)
21702#define SimulateIOError(A)
21703#define SimulateDiskfullError(A)
21704#endif
21705
21706/*
21707** When testing, keep a count of the number of open files.
21708*/
21709#ifdef SQLITE_TEST
21710SQLITE_API int sqlite3_open_file_count = 0;
21711#define OpenCounter(X)  sqlite3_open_file_count+=(X)
21712#else
21713#define OpenCounter(X)
21714#endif
21715
21716#endif /* !defined(_OS_COMMON_H_) */
21717
21718/************** End of os_common.h *******************************************/
21719/************** Continuing where we left off in os_unix.c ********************/
21720
21721/*
21722** Define various macros that are missing from some systems.
21723*/
21724#ifndef O_LARGEFILE
21725# define O_LARGEFILE 0
21726#endif
21727#ifdef SQLITE_DISABLE_LFS
21728# undef O_LARGEFILE
21729# define O_LARGEFILE 0
21730#endif
21731#ifndef O_NOFOLLOW
21732# define O_NOFOLLOW 0
21733#endif
21734#ifndef O_BINARY
21735# define O_BINARY 0
21736#endif
21737
21738/*
21739** The DJGPP compiler environment looks mostly like Unix, but it
21740** lacks the fcntl() system call.  So redefine fcntl() to be something
21741** that always succeeds.  This means that locking does not occur under
21742** DJGPP.  But it is DOS - what did you expect?
21743*/
21744#ifdef __DJGPP__
21745# define fcntl(A,B,C) 0
21746#endif
21747
21748/*
21749** The threadid macro resolves to the thread-id or to 0.  Used for
21750** testing and debugging only.
21751*/
21752#if SQLITE_THREADSAFE
21753#define threadid pthread_self()
21754#else
21755#define threadid 0
21756#endif
21757
21758
21759/*
21760** Helper functions to obtain and relinquish the global mutex. The
21761** global mutex is used to protect the unixOpenCnt, unixLockInfo and
21762** vxworksFileId objects used by this file, all of which may be
21763** shared by multiple threads.
21764**
21765** Function unixMutexHeld() is used to assert() that the global mutex
21766** is held when required. This function is only used as part of assert()
21767** statements. e.g.
21768**
21769**   unixEnterMutex()
21770**     assert( unixMutexHeld() );
21771**   unixEnterLeave()
21772*/
21773static void unixEnterMutex(void){
21774  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21775}
21776static void unixLeaveMutex(void){
21777  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21778}
21779#ifdef SQLITE_DEBUG
21780static int unixMutexHeld(void) {
21781  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
21782}
21783#endif
21784
21785
21786#ifdef SQLITE_DEBUG
21787/*
21788** Helper function for printing out trace information from debugging
21789** binaries. This returns the string represetation of the supplied
21790** integer lock-type.
21791*/
21792static const char *locktypeName(int locktype){
21793  switch( locktype ){
21794    case NO_LOCK: return "NONE";
21795    case SHARED_LOCK: return "SHARED";
21796    case RESERVED_LOCK: return "RESERVED";
21797    case PENDING_LOCK: return "PENDING";
21798    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
21799  }
21800  return "ERROR";
21801}
21802#endif
21803
21804#ifdef SQLITE_LOCK_TRACE
21805/*
21806** Print out information about all locking operations.
21807**
21808** This routine is used for troubleshooting locks on multithreaded
21809** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
21810** command-line option on the compiler.  This code is normally
21811** turned off.
21812*/
21813static int lockTrace(int fd, int op, struct flock *p){
21814  char *zOpName, *zType;
21815  int s;
21816  int savedErrno;
21817  if( op==F_GETLK ){
21818    zOpName = "GETLK";
21819  }else if( op==F_SETLK ){
21820    zOpName = "SETLK";
21821  }else{
21822    s = fcntl(fd, op, p);
21823    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
21824    return s;
21825  }
21826  if( p->l_type==F_RDLCK ){
21827    zType = "RDLCK";
21828  }else if( p->l_type==F_WRLCK ){
21829    zType = "WRLCK";
21830  }else if( p->l_type==F_UNLCK ){
21831    zType = "UNLCK";
21832  }else{
21833    assert( 0 );
21834  }
21835  assert( p->l_whence==SEEK_SET );
21836  s = fcntl(fd, op, p);
21837  savedErrno = errno;
21838  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
21839     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
21840     (int)p->l_pid, s);
21841  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
21842    struct flock l2;
21843    l2 = *p;
21844    fcntl(fd, F_GETLK, &l2);
21845    if( l2.l_type==F_RDLCK ){
21846      zType = "RDLCK";
21847    }else if( l2.l_type==F_WRLCK ){
21848      zType = "WRLCK";
21849    }else if( l2.l_type==F_UNLCK ){
21850      zType = "UNLCK";
21851    }else{
21852      assert( 0 );
21853    }
21854    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
21855       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
21856  }
21857  errno = savedErrno;
21858  return s;
21859}
21860#define fcntl lockTrace
21861#endif /* SQLITE_LOCK_TRACE */
21862
21863
21864
21865/*
21866** This routine translates a standard POSIX errno code into something
21867** useful to the clients of the sqlite3 functions.  Specifically, it is
21868** intended to translate a variety of "try again" errors into SQLITE_BUSY
21869** and a variety of "please close the file descriptor NOW" errors into
21870** SQLITE_IOERR
21871**
21872** Errors during initialization of locks, or file system support for locks,
21873** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
21874*/
21875static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
21876  switch (posixError) {
21877  case 0:
21878    return SQLITE_OK;
21879
21880  case EAGAIN:
21881  case ETIMEDOUT:
21882  case EBUSY:
21883  case EINTR:
21884  case ENOLCK:
21885    /* random NFS retry error, unless during file system support
21886     * introspection, in which it actually means what it says */
21887    return SQLITE_BUSY;
21888
21889  case EACCES:
21890    /* EACCES is like EAGAIN during locking operations, but not any other time*/
21891    if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
21892	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
21893	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
21894	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
21895      return SQLITE_BUSY;
21896    }
21897    /* else fall through */
21898  case EPERM:
21899    return SQLITE_PERM;
21900
21901  case EDEADLK:
21902    return SQLITE_IOERR_BLOCKED;
21903
21904#if EOPNOTSUPP!=ENOTSUP
21905  case EOPNOTSUPP:
21906    /* something went terribly awry, unless during file system support
21907     * introspection, in which it actually means what it says */
21908#endif
21909#ifdef ENOTSUP
21910  case ENOTSUP:
21911    /* invalid fd, unless during file system support introspection, in which
21912     * it actually means what it says */
21913#endif
21914  case EIO:
21915  case EBADF:
21916  case EINVAL:
21917  case ENOTCONN:
21918  case ENODEV:
21919  case ENXIO:
21920  case ENOENT:
21921  case ESTALE:
21922  case ENOSYS:
21923    /* these should force the client to close the file and reconnect */
21924
21925  default:
21926    return sqliteIOErr;
21927  }
21928}
21929
21930
21931
21932/******************************************************************************
21933****************** Begin Unique File ID Utility Used By VxWorks ***************
21934**
21935** On most versions of unix, we can get a unique ID for a file by concatenating
21936** the device number and the inode number.  But this does not work on VxWorks.
21937** On VxWorks, a unique file id must be based on the canonical filename.
21938**
21939** A pointer to an instance of the following structure can be used as a
21940** unique file ID in VxWorks.  Each instance of this structure contains
21941** a copy of the canonical filename.  There is also a reference count.
21942** The structure is reclaimed when the number of pointers to it drops to
21943** zero.
21944**
21945** There are never very many files open at one time and lookups are not
21946** a performance-critical path, so it is sufficient to put these
21947** structures on a linked list.
21948*/
21949struct vxworksFileId {
21950  struct vxworksFileId *pNext;  /* Next in a list of them all */
21951  int nRef;                     /* Number of references to this one */
21952  int nName;                    /* Length of the zCanonicalName[] string */
21953  char *zCanonicalName;         /* Canonical filename */
21954};
21955
21956#if OS_VXWORKS
21957/*
21958** All unique filenames are held on a linked list headed by this
21959** variable:
21960*/
21961static struct vxworksFileId *vxworksFileList = 0;
21962
21963/*
21964** Simplify a filename into its canonical form
21965** by making the following changes:
21966**
21967**  * removing any trailing and duplicate /
21968**  * convert /./ into just /
21969**  * convert /A/../ where A is any simple name into just /
21970**
21971** Changes are made in-place.  Return the new name length.
21972**
21973** The original filename is in z[0..n-1].  Return the number of
21974** characters in the simplified name.
21975*/
21976static int vxworksSimplifyName(char *z, int n){
21977  int i, j;
21978  while( n>1 && z[n-1]=='/' ){ n--; }
21979  for(i=j=0; i<n; i++){
21980    if( z[i]=='/' ){
21981      if( z[i+1]=='/' ) continue;
21982      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
21983        i += 1;
21984        continue;
21985      }
21986      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
21987        while( j>0 && z[j-1]!='/' ){ j--; }
21988        if( j>0 ){ j--; }
21989        i += 2;
21990        continue;
21991      }
21992    }
21993    z[j++] = z[i];
21994  }
21995  z[j] = 0;
21996  return j;
21997}
21998
21999/*
22000** Find a unique file ID for the given absolute pathname.  Return
22001** a pointer to the vxworksFileId object.  This pointer is the unique
22002** file ID.
22003**
22004** The nRef field of the vxworksFileId object is incremented before
22005** the object is returned.  A new vxworksFileId object is created
22006** and added to the global list if necessary.
22007**
22008** If a memory allocation error occurs, return NULL.
22009*/
22010static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
22011  struct vxworksFileId *pNew;         /* search key and new file ID */
22012  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
22013  int n;                              /* Length of zAbsoluteName string */
22014
22015  assert( zAbsoluteName[0]=='/' );
22016  n = (int)strlen(zAbsoluteName);
22017  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
22018  if( pNew==0 ) return 0;
22019  pNew->zCanonicalName = (char*)&pNew[1];
22020  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
22021  n = vxworksSimplifyName(pNew->zCanonicalName, n);
22022
22023  /* Search for an existing entry that matching the canonical name.
22024  ** If found, increment the reference count and return a pointer to
22025  ** the existing file ID.
22026  */
22027  unixEnterMutex();
22028  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
22029    if( pCandidate->nName==n
22030     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
22031    ){
22032       sqlite3_free(pNew);
22033       pCandidate->nRef++;
22034       unixLeaveMutex();
22035       return pCandidate;
22036    }
22037  }
22038
22039  /* No match was found.  We will make a new file ID */
22040  pNew->nRef = 1;
22041  pNew->nName = n;
22042  pNew->pNext = vxworksFileList;
22043  vxworksFileList = pNew;
22044  unixLeaveMutex();
22045  return pNew;
22046}
22047
22048/*
22049** Decrement the reference count on a vxworksFileId object.  Free
22050** the object when the reference count reaches zero.
22051*/
22052static void vxworksReleaseFileId(struct vxworksFileId *pId){
22053  unixEnterMutex();
22054  assert( pId->nRef>0 );
22055  pId->nRef--;
22056  if( pId->nRef==0 ){
22057    struct vxworksFileId **pp;
22058    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
22059    assert( *pp==pId );
22060    *pp = pId->pNext;
22061    sqlite3_free(pId);
22062  }
22063  unixLeaveMutex();
22064}
22065#endif /* OS_VXWORKS */
22066/*************** End of Unique File ID Utility Used By VxWorks ****************
22067******************************************************************************/
22068
22069
22070/******************************************************************************
22071*************************** Posix Advisory Locking ****************************
22072**
22073** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
22074** section 6.5.2.2 lines 483 through 490 specify that when a process
22075** sets or clears a lock, that operation overrides any prior locks set
22076** by the same process.  It does not explicitly say so, but this implies
22077** that it overrides locks set by the same process using a different
22078** file descriptor.  Consider this test case:
22079**
22080**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
22081**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
22082**
22083** Suppose ./file1 and ./file2 are really the same file (because
22084** one is a hard or symbolic link to the other) then if you set
22085** an exclusive lock on fd1, then try to get an exclusive lock
22086** on fd2, it works.  I would have expected the second lock to
22087** fail since there was already a lock on the file due to fd1.
22088** But not so.  Since both locks came from the same process, the
22089** second overrides the first, even though they were on different
22090** file descriptors opened on different file names.
22091**
22092** This means that we cannot use POSIX locks to synchronize file access
22093** among competing threads of the same process.  POSIX locks will work fine
22094** to synchronize access for threads in separate processes, but not
22095** threads within the same process.
22096**
22097** To work around the problem, SQLite has to manage file locks internally
22098** on its own.  Whenever a new database is opened, we have to find the
22099** specific inode of the database file (the inode is determined by the
22100** st_dev and st_ino fields of the stat structure that fstat() fills in)
22101** and check for locks already existing on that inode.  When locks are
22102** created or removed, we have to look at our own internal record of the
22103** locks to see if another thread has previously set a lock on that same
22104** inode.
22105**
22106** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
22107** For VxWorks, we have to use the alternative unique ID system based on
22108** canonical filename and implemented in the previous division.)
22109**
22110** The sqlite3_file structure for POSIX is no longer just an integer file
22111** descriptor.  It is now a structure that holds the integer file
22112** descriptor and a pointer to a structure that describes the internal
22113** locks on the corresponding inode.  There is one locking structure
22114** per inode, so if the same inode is opened twice, both unixFile structures
22115** point to the same locking structure.  The locking structure keeps
22116** a reference count (so we will know when to delete it) and a "cnt"
22117** field that tells us its internal lock status.  cnt==0 means the
22118** file is unlocked.  cnt==-1 means the file has an exclusive lock.
22119** cnt>0 means there are cnt shared locks on the file.
22120**
22121** Any attempt to lock or unlock a file first checks the locking
22122** structure.  The fcntl() system call is only invoked to set a
22123** POSIX lock if the internal lock structure transitions between
22124** a locked and an unlocked state.
22125**
22126** But wait:  there are yet more problems with POSIX advisory locks.
22127**
22128** If you close a file descriptor that points to a file that has locks,
22129** all locks on that file that are owned by the current process are
22130** released.  To work around this problem, each unixFile structure contains
22131** a pointer to an unixOpenCnt structure.  There is one unixOpenCnt structure
22132** per open inode, which means that multiple unixFile can point to a single
22133** unixOpenCnt.  When an attempt is made to close an unixFile, if there are
22134** other unixFile open on the same inode that are holding locks, the call
22135** to close() the file descriptor is deferred until all of the locks clear.
22136** The unixOpenCnt structure keeps a list of file descriptors that need to
22137** be closed and that list is walked (and cleared) when the last lock
22138** clears.
22139**
22140** Yet another problem:  LinuxThreads do not play well with posix locks.
22141**
22142** Many older versions of linux use the LinuxThreads library which is
22143** not posix compliant.  Under LinuxThreads, a lock created by thread
22144** A cannot be modified or overridden by a different thread B.
22145** Only thread A can modify the lock.  Locking behavior is correct
22146** if the appliation uses the newer Native Posix Thread Library (NPTL)
22147** on linux - with NPTL a lock created by thread A can override locks
22148** in thread B.  But there is no way to know at compile-time which
22149** threading library is being used.  So there is no way to know at
22150** compile-time whether or not thread A can override locks on thread B.
22151** We have to do a run-time check to discover the behavior of the
22152** current process.
22153**
22154** On systems where thread A is unable to modify locks created by
22155** thread B, we have to keep track of which thread created each
22156** lock.  Hence there is an extra field in the key to the unixLockInfo
22157** structure to record this information.  And on those systems it
22158** is illegal to begin a transaction in one thread and finish it
22159** in another.  For this latter restriction, there is no work-around.
22160** It is a limitation of LinuxThreads.
22161*/
22162
22163/*
22164** Set or check the unixFile.tid field.  This field is set when an unixFile
22165** is first opened.  All subsequent uses of the unixFile verify that the
22166** same thread is operating on the unixFile.  Some operating systems do
22167** not allow locks to be overridden by other threads and that restriction
22168** means that sqlite3* database handles cannot be moved from one thread
22169** to another while locks are held.
22170**
22171** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
22172** another as long as we are running on a system that supports threads
22173** overriding each others locks (which is now the most common behavior)
22174** or if no locks are held.  But the unixFile.pLock field needs to be
22175** recomputed because its key includes the thread-id.  See the
22176** transferOwnership() function below for additional information
22177*/
22178#if SQLITE_THREADSAFE && defined(__linux__)
22179# define SET_THREADID(X)   (X)->tid = pthread_self()
22180# define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
22181                            !pthread_equal((X)->tid, pthread_self()))
22182#else
22183# define SET_THREADID(X)
22184# define CHECK_THREADID(X) 0
22185#endif
22186
22187/*
22188** An instance of the following structure serves as the key used
22189** to locate a particular unixOpenCnt structure given its inode.  This
22190** is the same as the unixLockKey except that the thread ID is omitted.
22191*/
22192struct unixFileId {
22193  dev_t dev;                  /* Device number */
22194#if OS_VXWORKS
22195  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
22196#else
22197  ino_t ino;                  /* Inode number */
22198#endif
22199};
22200
22201/*
22202** An instance of the following structure serves as the key used
22203** to locate a particular unixLockInfo structure given its inode.
22204**
22205** If threads cannot override each others locks (LinuxThreads), then we
22206** set the unixLockKey.tid field to the thread ID.  If threads can override
22207** each others locks (Posix and NPTL) then tid is always set to zero.
22208** tid is omitted if we compile without threading support or on an OS
22209** other than linux.
22210*/
22211struct unixLockKey {
22212  struct unixFileId fid;  /* Unique identifier for the file */
22213#if SQLITE_THREADSAFE && defined(__linux__)
22214  pthread_t tid;  /* Thread ID of lock owner. Zero if not using LinuxThreads */
22215#endif
22216};
22217
22218/*
22219** An instance of the following structure is allocated for each open
22220** inode.  Or, on LinuxThreads, there is one of these structures for
22221** each inode opened by each thread.
22222**
22223** A single inode can have multiple file descriptors, so each unixFile
22224** structure contains a pointer to an instance of this object and this
22225** object keeps a count of the number of unixFile pointing to it.
22226*/
22227struct unixLockInfo {
22228  struct unixLockKey lockKey;     /* The lookup key */
22229  int cnt;                        /* Number of SHARED locks held */
22230  int locktype;                   /* One of SHARED_LOCK, RESERVED_LOCK etc. */
22231  int nRef;                       /* Number of pointers to this structure */
22232  struct unixLockInfo *pNext;     /* List of all unixLockInfo objects */
22233  struct unixLockInfo *pPrev;     /*    .... doubly linked */
22234};
22235
22236/*
22237** An instance of the following structure is allocated for each open
22238** inode.  This structure keeps track of the number of locks on that
22239** inode.  If a close is attempted against an inode that is holding
22240** locks, the close is deferred until all locks clear by adding the
22241** file descriptor to be closed to the pending list.
22242**
22243** TODO:  Consider changing this so that there is only a single file
22244** descriptor for each open file, even when it is opened multiple times.
22245** The close() system call would only occur when the last database
22246** using the file closes.
22247*/
22248struct unixOpenCnt {
22249  struct unixFileId fileId;   /* The lookup key */
22250  int nRef;                   /* Number of pointers to this structure */
22251  int nLock;                  /* Number of outstanding locks */
22252  UnixUnusedFd *pUnused;      /* Unused file descriptors to close */
22253#if OS_VXWORKS
22254  sem_t *pSem;                     /* Named POSIX semaphore */
22255  char aSemName[MAX_PATHNAME+2];   /* Name of that semaphore */
22256#endif
22257  struct unixOpenCnt *pNext, *pPrev;   /* List of all unixOpenCnt objects */
22258};
22259
22260/*
22261** Lists of all unixLockInfo and unixOpenCnt objects.  These used to be hash
22262** tables.  But the number of objects is rarely more than a dozen and
22263** never exceeds a few thousand.  And lookup is not on a critical
22264** path so a simple linked list will suffice.
22265*/
22266static struct unixLockInfo *lockList = 0;
22267static struct unixOpenCnt *openList = 0;
22268
22269/*
22270** This variable remembers whether or not threads can override each others
22271** locks.
22272**
22273**    0:  No.  Threads cannot override each others locks.  (LinuxThreads)
22274**    1:  Yes.  Threads can override each others locks.  (Posix & NLPT)
22275**   -1:  We don't know yet.
22276**
22277** On some systems, we know at compile-time if threads can override each
22278** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
22279** will be set appropriately.  On other systems, we have to check at
22280** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
22281** undefined.
22282**
22283** This variable normally has file scope only.  But during testing, we make
22284** it a global so that the test code can change its value in order to verify
22285** that the right stuff happens in either case.
22286*/
22287#if SQLITE_THREADSAFE && defined(__linux__)
22288#  ifndef SQLITE_THREAD_OVERRIDE_LOCK
22289#    define SQLITE_THREAD_OVERRIDE_LOCK -1
22290#  endif
22291#  ifdef SQLITE_TEST
22292int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22293#  else
22294static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22295#  endif
22296#endif
22297
22298/*
22299** This structure holds information passed into individual test
22300** threads by the testThreadLockingBehavior() routine.
22301*/
22302struct threadTestData {
22303  int fd;                /* File to be locked */
22304  struct flock lock;     /* The locking operation */
22305  int result;            /* Result of the locking operation */
22306};
22307
22308#if SQLITE_THREADSAFE && defined(__linux__)
22309/*
22310** This function is used as the main routine for a thread launched by
22311** testThreadLockingBehavior(). It tests whether the shared-lock obtained
22312** by the main thread in testThreadLockingBehavior() conflicts with a
22313** hypothetical write-lock obtained by this thread on the same file.
22314**
22315** The write-lock is not actually acquired, as this is not possible if
22316** the file is open in read-only mode (see ticket #3472).
22317*/
22318static void *threadLockingTest(void *pArg){
22319  struct threadTestData *pData = (struct threadTestData*)pArg;
22320  pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
22321  return pArg;
22322}
22323#endif /* SQLITE_THREADSAFE && defined(__linux__) */
22324
22325
22326#if SQLITE_THREADSAFE && defined(__linux__)
22327/*
22328** This procedure attempts to determine whether or not threads
22329** can override each others locks then sets the
22330** threadsOverrideEachOthersLocks variable appropriately.
22331*/
22332static void testThreadLockingBehavior(int fd_orig){
22333  int fd;
22334  int rc;
22335  struct threadTestData d;
22336  struct flock l;
22337  pthread_t t;
22338
22339  fd = dup(fd_orig);
22340  if( fd<0 ) return;
22341  memset(&l, 0, sizeof(l));
22342  l.l_type = F_RDLCK;
22343  l.l_len = 1;
22344  l.l_start = 0;
22345  l.l_whence = SEEK_SET;
22346  rc = fcntl(fd_orig, F_SETLK, &l);
22347  if( rc!=0 ) return;
22348  memset(&d, 0, sizeof(d));
22349  d.fd = fd;
22350  d.lock = l;
22351  d.lock.l_type = F_WRLCK;
22352  if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
22353    pthread_join(t, 0);
22354  }
22355  close(fd);
22356  if( d.result!=0 ) return;
22357  threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
22358}
22359#endif /* SQLITE_THREADSAFE && defined(__linux__) */
22360
22361/*
22362** Release a unixLockInfo structure previously allocated by findLockInfo().
22363**
22364** The mutex entered using the unixEnterMutex() function must be held
22365** when this function is called.
22366*/
22367static void releaseLockInfo(struct unixLockInfo *pLock){
22368  assert( unixMutexHeld() );
22369  if( pLock ){
22370    pLock->nRef--;
22371    if( pLock->nRef==0 ){
22372      if( pLock->pPrev ){
22373        assert( pLock->pPrev->pNext==pLock );
22374        pLock->pPrev->pNext = pLock->pNext;
22375      }else{
22376        assert( lockList==pLock );
22377        lockList = pLock->pNext;
22378      }
22379      if( pLock->pNext ){
22380        assert( pLock->pNext->pPrev==pLock );
22381        pLock->pNext->pPrev = pLock->pPrev;
22382      }
22383      sqlite3_free(pLock);
22384    }
22385  }
22386}
22387
22388/*
22389** Release a unixOpenCnt structure previously allocated by findLockInfo().
22390**
22391** The mutex entered using the unixEnterMutex() function must be held
22392** when this function is called.
22393*/
22394static void releaseOpenCnt(struct unixOpenCnt *pOpen){
22395  assert( unixMutexHeld() );
22396  if( pOpen ){
22397    pOpen->nRef--;
22398    if( pOpen->nRef==0 ){
22399      if( pOpen->pPrev ){
22400        assert( pOpen->pPrev->pNext==pOpen );
22401        pOpen->pPrev->pNext = pOpen->pNext;
22402      }else{
22403        assert( openList==pOpen );
22404        openList = pOpen->pNext;
22405      }
22406      if( pOpen->pNext ){
22407        assert( pOpen->pNext->pPrev==pOpen );
22408        pOpen->pNext->pPrev = pOpen->pPrev;
22409      }
22410#if SQLITE_THREADSAFE && defined(__linux__)
22411      assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
22412#endif
22413
22414      /* If pOpen->pUnused is not null, then memory and file-descriptors
22415      ** are leaked.
22416      **
22417      ** This will only happen if, under Linuxthreads, the user has opened
22418      ** a transaction in one thread, then attempts to close the database
22419      ** handle from another thread (without first unlocking the db file).
22420      ** This is a misuse.  */
22421      sqlite3_free(pOpen);
22422    }
22423  }
22424}
22425
22426/*
22427** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
22428** describes that file descriptor.  Create new ones if necessary.  The
22429** return values might be uninitialized if an error occurs.
22430**
22431** The mutex entered using the unixEnterMutex() function must be held
22432** when this function is called.
22433**
22434** Return an appropriate error code.
22435*/
22436static int findLockInfo(
22437  unixFile *pFile,               /* Unix file with file desc used in the key */
22438  struct unixLockInfo **ppLock,  /* Return the unixLockInfo structure here */
22439  struct unixOpenCnt **ppOpen    /* Return the unixOpenCnt structure here */
22440){
22441  int rc;                        /* System call return code */
22442  int fd;                        /* The file descriptor for pFile */
22443  struct unixLockKey lockKey;    /* Lookup key for the unixLockInfo structure */
22444  struct unixFileId fileId;      /* Lookup key for the unixOpenCnt struct */
22445  struct stat statbuf;           /* Low-level file information */
22446  struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
22447  struct unixOpenCnt *pOpen;     /* Candidate unixOpenCnt object */
22448
22449  assert( unixMutexHeld() );
22450
22451  /* Get low-level information about the file that we can used to
22452  ** create a unique name for the file.
22453  */
22454  fd = pFile->h;
22455  rc = fstat(fd, &statbuf);
22456  if( rc!=0 ){
22457    pFile->lastErrno = errno;
22458#ifdef EOVERFLOW
22459    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
22460#endif
22461    return SQLITE_IOERR;
22462  }
22463
22464#ifdef __APPLE__
22465  /* On OS X on an msdos filesystem, the inode number is reported
22466  ** incorrectly for zero-size files.  See ticket #3260.  To work
22467  ** around this problem (we consider it a bug in OS X, not SQLite)
22468  ** we always increase the file size to 1 by writing a single byte
22469  ** prior to accessing the inode number.  The one byte written is
22470  ** an ASCII 'S' character which also happens to be the first byte
22471  ** in the header of every SQLite database.  In this way, if there
22472  ** is a race condition such that another thread has already populated
22473  ** the first page of the database, no damage is done.
22474  */
22475  if( statbuf.st_size==0 ){
22476    rc = write(fd, "S", 1);
22477    if( rc!=1 ){
22478      return SQLITE_IOERR;
22479    }
22480    rc = fstat(fd, &statbuf);
22481    if( rc!=0 ){
22482      pFile->lastErrno = errno;
22483      return SQLITE_IOERR;
22484    }
22485  }
22486#endif
22487
22488  memset(&lockKey, 0, sizeof(lockKey));
22489  lockKey.fid.dev = statbuf.st_dev;
22490#if OS_VXWORKS
22491  lockKey.fid.pId = pFile->pId;
22492#else
22493  lockKey.fid.ino = statbuf.st_ino;
22494#endif
22495#if SQLITE_THREADSAFE && defined(__linux__)
22496  if( threadsOverrideEachOthersLocks<0 ){
22497    testThreadLockingBehavior(fd);
22498  }
22499  lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
22500#endif
22501  fileId = lockKey.fid;
22502  if( ppLock!=0 ){
22503    pLock = lockList;
22504    while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
22505      pLock = pLock->pNext;
22506    }
22507    if( pLock==0 ){
22508      pLock = sqlite3_malloc( sizeof(*pLock) );
22509      if( pLock==0 ){
22510        rc = SQLITE_NOMEM;
22511        goto exit_findlockinfo;
22512      }
22513      memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
22514      pLock->nRef = 1;
22515      pLock->cnt = 0;
22516      pLock->locktype = 0;
22517      pLock->pNext = lockList;
22518      pLock->pPrev = 0;
22519      if( lockList ) lockList->pPrev = pLock;
22520      lockList = pLock;
22521    }else{
22522      pLock->nRef++;
22523    }
22524    *ppLock = pLock;
22525  }
22526  if( ppOpen!=0 ){
22527    pOpen = openList;
22528    while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
22529      pOpen = pOpen->pNext;
22530    }
22531    if( pOpen==0 ){
22532      pOpen = sqlite3_malloc( sizeof(*pOpen) );
22533      if( pOpen==0 ){
22534        releaseLockInfo(pLock);
22535        rc = SQLITE_NOMEM;
22536        goto exit_findlockinfo;
22537      }
22538      memset(pOpen, 0, sizeof(*pOpen));
22539      pOpen->fileId = fileId;
22540      pOpen->nRef = 1;
22541      pOpen->pNext = openList;
22542      if( openList ) openList->pPrev = pOpen;
22543      openList = pOpen;
22544    }else{
22545      pOpen->nRef++;
22546    }
22547    *ppOpen = pOpen;
22548  }
22549
22550exit_findlockinfo:
22551  return rc;
22552}
22553
22554/*
22555** If we are currently in a different thread than the thread that the
22556** unixFile argument belongs to, then transfer ownership of the unixFile
22557** over to the current thread.
22558**
22559** A unixFile is only owned by a thread on systems that use LinuxThreads.
22560**
22561** Ownership transfer is only allowed if the unixFile is currently unlocked.
22562** If the unixFile is locked and an ownership is wrong, then return
22563** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
22564*/
22565#if SQLITE_THREADSAFE && defined(__linux__)
22566static int transferOwnership(unixFile *pFile){
22567  int rc;
22568  pthread_t hSelf;
22569  if( threadsOverrideEachOthersLocks ){
22570    /* Ownership transfers not needed on this system */
22571    return SQLITE_OK;
22572  }
22573  hSelf = pthread_self();
22574  if( pthread_equal(pFile->tid, hSelf) ){
22575    /* We are still in the same thread */
22576    OSTRACE1("No-transfer, same thread\n");
22577    return SQLITE_OK;
22578  }
22579  if( pFile->locktype!=NO_LOCK ){
22580    /* We cannot change ownership while we are holding a lock! */
22581    return SQLITE_MISUSE;
22582  }
22583  OSTRACE4("Transfer ownership of %d from %d to %d\n",
22584            pFile->h, pFile->tid, hSelf);
22585  pFile->tid = hSelf;
22586  if (pFile->pLock != NULL) {
22587    releaseLockInfo(pFile->pLock);
22588    rc = findLockInfo(pFile, &pFile->pLock, 0);
22589    OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
22590           locktypeName(pFile->locktype),
22591           locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
22592    return rc;
22593  } else {
22594    return SQLITE_OK;
22595  }
22596}
22597#else  /* if not SQLITE_THREADSAFE */
22598  /* On single-threaded builds, ownership transfer is a no-op */
22599# define transferOwnership(X) SQLITE_OK
22600#endif /* SQLITE_THREADSAFE */
22601
22602
22603/*
22604** This routine checks if there is a RESERVED lock held on the specified
22605** file by this or any other process. If such a lock is held, set *pResOut
22606** to a non-zero value otherwise *pResOut is set to zero.  The return value
22607** is set to SQLITE_OK unless an I/O error occurs during lock checking.
22608*/
22609static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
22610  int rc = SQLITE_OK;
22611  int reserved = 0;
22612  unixFile *pFile = (unixFile*)id;
22613
22614  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
22615
22616  assert( pFile );
22617  unixEnterMutex(); /* Because pFile->pLock is shared across threads */
22618
22619  /* Check if a thread in this process holds such a lock */
22620  if( pFile->pLock->locktype>SHARED_LOCK ){
22621    reserved = 1;
22622  }
22623
22624  /* Otherwise see if some other process holds it.
22625  */
22626#ifndef __DJGPP__
22627  if( !reserved ){
22628    struct flock lock;
22629    lock.l_whence = SEEK_SET;
22630    lock.l_start = RESERVED_BYTE;
22631    lock.l_len = 1;
22632    lock.l_type = F_WRLCK;
22633    if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
22634      int tErrno = errno;
22635      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
22636      pFile->lastErrno = tErrno;
22637    } else if( lock.l_type!=F_UNLCK ){
22638      reserved = 1;
22639    }
22640  }
22641#endif
22642
22643  unixLeaveMutex();
22644  OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved);
22645
22646  *pResOut = reserved;
22647  return rc;
22648}
22649
22650/*
22651** Perform a file locking operation on a range of bytes in a file.
22652** The "op" parameter should be one of F_RDLCK, F_WRLCK, or F_UNLCK.
22653** Return 0 on success or -1 for failure.  On failure, write the error
22654** code into *pErrcode.
22655**
22656** If the SQLITE_WHOLE_FILE_LOCKING bit is clear, then only lock
22657** the range of bytes on the locking page between SHARED_FIRST and
22658** SHARED_SIZE.  If SQLITE_WHOLE_FILE_LOCKING is set, then lock all
22659** bytes from 0 up to but not including PENDING_BYTE, and all bytes
22660** that follow SHARED_FIRST.
22661**
22662** In other words, of SQLITE_WHOLE_FILE_LOCKING if false (the historical
22663** default case) then only lock a small range of bytes from SHARED_FIRST
22664** through SHARED_FIRST+SHARED_SIZE-1.  But if SQLITE_WHOLE_FILE_LOCKING is
22665** true then lock every byte in the file except for PENDING_BYTE and
22666** RESERVED_BYTE.
22667**
22668** SQLITE_WHOLE_FILE_LOCKING=true overlaps SQLITE_WHOLE_FILE_LOCKING=false
22669** and so the locking schemes are compatible.  One type of lock will
22670** effectively exclude the other type.  The reason for using the
22671** SQLITE_WHOLE_FILE_LOCKING=true is that by indicating the full range
22672** of bytes to be read or written, we give hints to NFS to help it
22673** maintain cache coherency.  On the other hand, whole file locking
22674** is slower, so we don't want to use it except for NFS.
22675*/
22676static int rangeLock(unixFile *pFile, int op, int *pErrcode){
22677  struct flock lock;
22678  int rc;
22679  lock.l_type = op;
22680  lock.l_start = SHARED_FIRST;
22681  lock.l_whence = SEEK_SET;
22682  if( (pFile->fileFlags & SQLITE_WHOLE_FILE_LOCKING)==0 ){
22683    lock.l_len = SHARED_SIZE;
22684    rc = fcntl(pFile->h, F_SETLK, &lock);
22685    *pErrcode = errno;
22686  }else{
22687    lock.l_len = 0;
22688    rc = fcntl(pFile->h, F_SETLK, &lock);
22689    *pErrcode = errno;
22690    if( NEVER(op==F_UNLCK) || rc!=(-1) ){
22691      lock.l_start = 0;
22692      lock.l_len = PENDING_BYTE;
22693      rc = fcntl(pFile->h, F_SETLK, &lock);
22694      if( ALWAYS(op!=F_UNLCK) && rc==(-1) ){
22695        *pErrcode = errno;
22696        lock.l_type = F_UNLCK;
22697        lock.l_start = SHARED_FIRST;
22698        lock.l_len = 0;
22699        fcntl(pFile->h, F_SETLK, &lock);
22700      }
22701    }
22702  }
22703  return rc;
22704}
22705
22706/*
22707** Lock the file with the lock specified by parameter locktype - one
22708** of the following:
22709**
22710**     (1) SHARED_LOCK
22711**     (2) RESERVED_LOCK
22712**     (3) PENDING_LOCK
22713**     (4) EXCLUSIVE_LOCK
22714**
22715** Sometimes when requesting one lock state, additional lock states
22716** are inserted in between.  The locking might fail on one of the later
22717** transitions leaving the lock state different from what it started but
22718** still short of its goal.  The following chart shows the allowed
22719** transitions and the inserted intermediate states:
22720**
22721**    UNLOCKED -> SHARED
22722**    SHARED -> RESERVED
22723**    SHARED -> (PENDING) -> EXCLUSIVE
22724**    RESERVED -> (PENDING) -> EXCLUSIVE
22725**    PENDING -> EXCLUSIVE
22726**
22727** This routine will only increase a lock.  Use the sqlite3OsUnlock()
22728** routine to lower a locking level.
22729*/
22730static int unixLock(sqlite3_file *id, int locktype){
22731  /* The following describes the implementation of the various locks and
22732  ** lock transitions in terms of the POSIX advisory shared and exclusive
22733  ** lock primitives (called read-locks and write-locks below, to avoid
22734  ** confusion with SQLite lock names). The algorithms are complicated
22735  ** slightly in order to be compatible with windows systems simultaneously
22736  ** accessing the same database file, in case that is ever required.
22737  **
22738  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
22739  ** byte', each single bytes at well known offsets, and the 'shared byte
22740  ** range', a range of 510 bytes at a well known offset.
22741  **
22742  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
22743  ** byte'.  If this is successful, a random byte from the 'shared byte
22744  ** range' is read-locked and the lock on the 'pending byte' released.
22745  **
22746  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
22747  ** A RESERVED lock is implemented by grabbing a write-lock on the
22748  ** 'reserved byte'.
22749  **
22750  ** A process may only obtain a PENDING lock after it has obtained a
22751  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
22752  ** on the 'pending byte'. This ensures that no new SHARED locks can be
22753  ** obtained, but existing SHARED locks are allowed to persist. A process
22754  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
22755  ** This property is used by the algorithm for rolling back a journal file
22756  ** after a crash.
22757  **
22758  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
22759  ** implemented by obtaining a write-lock on the entire 'shared byte
22760  ** range'. Since all other locks require a read-lock on one of the bytes
22761  ** within this range, this ensures that no other locks are held on the
22762  ** database.
22763  **
22764  ** The reason a single byte cannot be used instead of the 'shared byte
22765  ** range' is that some versions of windows do not support read-locks. By
22766  ** locking a random byte from a range, concurrent SHARED locks may exist
22767  ** even if the locking primitive used is always a write-lock.
22768  */
22769  int rc = SQLITE_OK;
22770  unixFile *pFile = (unixFile*)id;
22771  struct unixLockInfo *pLock = pFile->pLock;
22772  struct flock lock;
22773  int s = 0;
22774  int tErrno;
22775
22776  assert( pFile );
22777  OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
22778      locktypeName(locktype), locktypeName(pFile->locktype),
22779      locktypeName(pLock->locktype), pLock->cnt , getpid());
22780
22781  /* If there is already a lock of this type or more restrictive on the
22782  ** unixFile, do nothing. Don't use the end_lock: exit path, as
22783  ** unixEnterMutex() hasn't been called yet.
22784  */
22785  if( pFile->locktype>=locktype ){
22786    OSTRACE3("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
22787            locktypeName(locktype));
22788    return SQLITE_OK;
22789  }
22790
22791  /* Make sure the locking sequence is correct.
22792  **  (1) We never move from unlocked to anything higher than shared lock.
22793  **  (2) SQLite never explicitly requests a pendig lock.
22794  **  (3) A shared lock is always held when a reserve lock is requested.
22795  */
22796  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
22797  assert( locktype!=PENDING_LOCK );
22798  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
22799
22800  /* This mutex is needed because pFile->pLock is shared across threads
22801  */
22802  unixEnterMutex();
22803
22804  /* Make sure the current thread owns the pFile.
22805  */
22806  rc = transferOwnership(pFile);
22807  if( rc!=SQLITE_OK ){
22808    unixLeaveMutex();
22809    return rc;
22810  }
22811  pLock = pFile->pLock;
22812
22813  /* If some thread using this PID has a lock via a different unixFile*
22814  ** handle that precludes the requested lock, return BUSY.
22815  */
22816  if( (pFile->locktype!=pLock->locktype &&
22817          (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
22818  ){
22819    rc = SQLITE_BUSY;
22820    goto end_lock;
22821  }
22822
22823  /* If a SHARED lock is requested, and some thread using this PID already
22824  ** has a SHARED or RESERVED lock, then increment reference counts and
22825  ** return SQLITE_OK.
22826  */
22827  if( locktype==SHARED_LOCK &&
22828      (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
22829    assert( locktype==SHARED_LOCK );
22830    assert( pFile->locktype==0 );
22831    assert( pLock->cnt>0 );
22832    pFile->locktype = SHARED_LOCK;
22833    pLock->cnt++;
22834    pFile->pOpen->nLock++;
22835    goto end_lock;
22836  }
22837
22838
22839  /* A PENDING lock is needed before acquiring a SHARED lock and before
22840  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
22841  ** be released.
22842  */
22843  lock.l_len = 1L;
22844  lock.l_whence = SEEK_SET;
22845  if( locktype==SHARED_LOCK
22846      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
22847  ){
22848    lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
22849    lock.l_start = PENDING_BYTE;
22850    s = fcntl(pFile->h, F_SETLK, &lock);
22851    if( s==(-1) ){
22852      tErrno = errno;
22853      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22854      if( IS_LOCK_ERROR(rc) ){
22855        pFile->lastErrno = tErrno;
22856      }
22857      goto end_lock;
22858    }
22859  }
22860
22861
22862  /* If control gets to this point, then actually go ahead and make
22863  ** operating system calls for the specified lock.
22864  */
22865  if( locktype==SHARED_LOCK ){
22866    assert( pLock->cnt==0 );
22867    assert( pLock->locktype==0 );
22868
22869    /* Now get the read-lock */
22870    s = rangeLock(pFile, F_RDLCK, &tErrno);
22871
22872    /* Drop the temporary PENDING lock */
22873    lock.l_start = PENDING_BYTE;
22874    lock.l_len = 1L;
22875    lock.l_type = F_UNLCK;
22876    if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
22877      if( s != -1 ){
22878        /* This could happen with a network mount */
22879        tErrno = errno;
22880        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
22881        if( IS_LOCK_ERROR(rc) ){
22882          pFile->lastErrno = tErrno;
22883        }
22884        goto end_lock;
22885      }
22886    }
22887    if( s==(-1) ){
22888      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22889      if( IS_LOCK_ERROR(rc) ){
22890        pFile->lastErrno = tErrno;
22891      }
22892    }else{
22893      pFile->locktype = SHARED_LOCK;
22894      pFile->pOpen->nLock++;
22895      pLock->cnt = 1;
22896    }
22897  }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
22898    /* We are trying for an exclusive lock but another thread in this
22899    ** same process is still holding a shared lock. */
22900    rc = SQLITE_BUSY;
22901  }else{
22902    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
22903    ** assumed that there is a SHARED or greater lock on the file
22904    ** already.
22905    */
22906    assert( 0!=pFile->locktype );
22907    lock.l_type = F_WRLCK;
22908    switch( locktype ){
22909      case RESERVED_LOCK:
22910        lock.l_start = RESERVED_BYTE;
22911        s = fcntl(pFile->h, F_SETLK, &lock);
22912        tErrno = errno;
22913        break;
22914      case EXCLUSIVE_LOCK:
22915        s = rangeLock(pFile, F_WRLCK, &tErrno);
22916        break;
22917      default:
22918        assert(0);
22919    }
22920    if( s==(-1) ){
22921      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
22922      if( IS_LOCK_ERROR(rc) ){
22923        pFile->lastErrno = tErrno;
22924      }
22925    }
22926  }
22927
22928
22929#ifndef NDEBUG
22930  /* Set up the transaction-counter change checking flags when
22931  ** transitioning from a SHARED to a RESERVED lock.  The change
22932  ** from SHARED to RESERVED marks the beginning of a normal
22933  ** write operation (not a hot journal rollback).
22934  */
22935  if( rc==SQLITE_OK
22936   && pFile->locktype<=SHARED_LOCK
22937   && locktype==RESERVED_LOCK
22938  ){
22939    pFile->transCntrChng = 0;
22940    pFile->dbUpdate = 0;
22941    pFile->inNormalWrite = 1;
22942  }
22943#endif
22944
22945
22946  if( rc==SQLITE_OK ){
22947    pFile->locktype = locktype;
22948    pLock->locktype = locktype;
22949  }else if( locktype==EXCLUSIVE_LOCK ){
22950    pFile->locktype = PENDING_LOCK;
22951    pLock->locktype = PENDING_LOCK;
22952  }
22953
22954end_lock:
22955  unixLeaveMutex();
22956  OSTRACE4("LOCK    %d %s %s (unix)\n", pFile->h, locktypeName(locktype),
22957      rc==SQLITE_OK ? "ok" : "failed");
22958  return rc;
22959}
22960
22961/*
22962** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
22963** If all such file descriptors are closed without error, the list is
22964** cleared and SQLITE_OK returned.
22965**
22966** Otherwise, if an error occurs, then successfully closed file descriptor
22967** entries are removed from the list, and SQLITE_IOERR_CLOSE returned.
22968** not deleted and SQLITE_IOERR_CLOSE returned.
22969*/
22970static int closePendingFds(unixFile *pFile){
22971  int rc = SQLITE_OK;
22972  struct unixOpenCnt *pOpen = pFile->pOpen;
22973  UnixUnusedFd *pError = 0;
22974  UnixUnusedFd *p;
22975  UnixUnusedFd *pNext;
22976  for(p=pOpen->pUnused; p; p=pNext){
22977    pNext = p->pNext;
22978    if( close(p->fd) ){
22979      pFile->lastErrno = errno;
22980      rc = SQLITE_IOERR_CLOSE;
22981      p->pNext = pError;
22982      pError = p;
22983    }else{
22984      sqlite3_free(p);
22985    }
22986  }
22987  pOpen->pUnused = pError;
22988  return rc;
22989}
22990
22991/*
22992** Add the file descriptor used by file handle pFile to the corresponding
22993** pUnused list.
22994*/
22995static void setPendingFd(unixFile *pFile){
22996  struct unixOpenCnt *pOpen = pFile->pOpen;
22997  UnixUnusedFd *p = pFile->pUnused;
22998  p->pNext = pOpen->pUnused;
22999  pOpen->pUnused = p;
23000  pFile->h = -1;
23001  pFile->pUnused = 0;
23002}
23003
23004/*
23005** Lower the locking level on file descriptor pFile to locktype.  locktype
23006** must be either NO_LOCK or SHARED_LOCK.
23007**
23008** If the locking level of the file descriptor is already at or below
23009** the requested locking level, this routine is a no-op.
23010*/
23011static int unixUnlock(sqlite3_file *id, int locktype){
23012  unixFile *pFile = (unixFile*)id; /* The open file */
23013  struct unixLockInfo *pLock;      /* Structure describing current lock state */
23014  struct flock lock;               /* Information passed into fcntl() */
23015  int rc = SQLITE_OK;              /* Return code from this interface */
23016  int h;                           /* The underlying file descriptor */
23017  int tErrno;                      /* Error code from system call errors */
23018
23019  assert( pFile );
23020  OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
23021      pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
23022
23023  assert( locktype<=SHARED_LOCK );
23024  if( pFile->locktype<=locktype ){
23025    return SQLITE_OK;
23026  }
23027  if( CHECK_THREADID(pFile) ){
23028    return SQLITE_MISUSE;
23029  }
23030  unixEnterMutex();
23031  h = pFile->h;
23032  pLock = pFile->pLock;
23033  assert( pLock->cnt!=0 );
23034  if( pFile->locktype>SHARED_LOCK ){
23035    assert( pLock->locktype==pFile->locktype );
23036    SimulateIOErrorBenign(1);
23037    SimulateIOError( h=(-1) )
23038    SimulateIOErrorBenign(0);
23039
23040#ifndef NDEBUG
23041    /* When reducing a lock such that other processes can start
23042    ** reading the database file again, make sure that the
23043    ** transaction counter was updated if any part of the database
23044    ** file changed.  If the transaction counter is not updated,
23045    ** other connections to the same file might not realize that
23046    ** the file has changed and hence might not know to flush their
23047    ** cache.  The use of a stale cache can lead to database corruption.
23048    */
23049    assert( pFile->inNormalWrite==0
23050         || pFile->dbUpdate==0
23051         || pFile->transCntrChng==1 );
23052    pFile->inNormalWrite = 0;
23053#endif
23054
23055
23056    if( locktype==SHARED_LOCK ){
23057      if( rangeLock(pFile, F_RDLCK, &tErrno)==(-1) ){
23058        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23059        if( IS_LOCK_ERROR(rc) ){
23060          pFile->lastErrno = tErrno;
23061        }
23062        goto end_unlock;
23063      }
23064    }
23065    lock.l_type = F_UNLCK;
23066    lock.l_whence = SEEK_SET;
23067    lock.l_start = PENDING_BYTE;
23068    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23069    if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23070      pLock->locktype = SHARED_LOCK;
23071    }else{
23072      tErrno = errno;
23073      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23074      if( IS_LOCK_ERROR(rc) ){
23075        pFile->lastErrno = tErrno;
23076      }
23077      goto end_unlock;
23078    }
23079  }
23080  if( locktype==NO_LOCK ){
23081    struct unixOpenCnt *pOpen;
23082
23083    /* Decrement the shared lock counter.  Release the lock using an
23084    ** OS call only when all threads in this same process have released
23085    ** the lock.
23086    */
23087    pLock->cnt--;
23088    if( pLock->cnt==0 ){
23089      lock.l_type = F_UNLCK;
23090      lock.l_whence = SEEK_SET;
23091      lock.l_start = lock.l_len = 0L;
23092      SimulateIOErrorBenign(1);
23093      SimulateIOError( h=(-1) )
23094      SimulateIOErrorBenign(0);
23095      if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23096        pLock->locktype = NO_LOCK;
23097      }else{
23098        tErrno = errno;
23099        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23100        if( IS_LOCK_ERROR(rc) ){
23101          pFile->lastErrno = tErrno;
23102        }
23103        pLock->locktype = NO_LOCK;
23104        pFile->locktype = NO_LOCK;
23105      }
23106    }
23107
23108    /* Decrement the count of locks against this same file.  When the
23109    ** count reaches zero, close any other file descriptors whose close
23110    ** was deferred because of outstanding locks.
23111    */
23112    pOpen = pFile->pOpen;
23113    pOpen->nLock--;
23114    assert( pOpen->nLock>=0 );
23115    if( pOpen->nLock==0 ){
23116      int rc2 = closePendingFds(pFile);
23117      if( rc==SQLITE_OK ){
23118        rc = rc2;
23119      }
23120    }
23121  }
23122
23123end_unlock:
23124  unixLeaveMutex();
23125  if( rc==SQLITE_OK ) pFile->locktype = locktype;
23126  return rc;
23127}
23128
23129/*
23130** This function performs the parts of the "close file" operation
23131** common to all locking schemes. It closes the directory and file
23132** handles, if they are valid, and sets all fields of the unixFile
23133** structure to 0.
23134**
23135** It is *not* necessary to hold the mutex when this routine is called,
23136** even on VxWorks.  A mutex will be acquired on VxWorks by the
23137** vxworksReleaseFileId() routine.
23138*/
23139static int closeUnixFile(sqlite3_file *id){
23140  unixFile *pFile = (unixFile*)id;
23141  if( pFile ){
23142    if( pFile->dirfd>=0 ){
23143      int err = close(pFile->dirfd);
23144      if( err ){
23145        pFile->lastErrno = errno;
23146        return SQLITE_IOERR_DIR_CLOSE;
23147      }else{
23148        pFile->dirfd=-1;
23149      }
23150    }
23151    if( pFile->h>=0 ){
23152      int err = close(pFile->h);
23153      if( err ){
23154        pFile->lastErrno = errno;
23155        return SQLITE_IOERR_CLOSE;
23156      }
23157    }
23158#if OS_VXWORKS
23159    if( pFile->pId ){
23160      if( pFile->isDelete ){
23161        unlink(pFile->pId->zCanonicalName);
23162      }
23163      vxworksReleaseFileId(pFile->pId);
23164      pFile->pId = 0;
23165    }
23166#endif
23167    OSTRACE2("CLOSE   %-3d\n", pFile->h);
23168    OpenCounter(-1);
23169    sqlite3_free(pFile->pUnused);
23170    memset(pFile, 0, sizeof(unixFile));
23171  }
23172  return SQLITE_OK;
23173}
23174
23175/*
23176** Close a file.
23177*/
23178static int unixClose(sqlite3_file *id){
23179  int rc = SQLITE_OK;
23180  if( id ){
23181    unixFile *pFile = (unixFile *)id;
23182    unixUnlock(id, NO_LOCK);
23183    unixEnterMutex();
23184    if( pFile->pOpen && pFile->pOpen->nLock ){
23185      /* If there are outstanding locks, do not actually close the file just
23186      ** yet because that would clear those locks.  Instead, add the file
23187      ** descriptor to pOpen->pUnused list.  It will be automatically closed
23188      ** when the last lock is cleared.
23189      */
23190      setPendingFd(pFile);
23191    }
23192    releaseLockInfo(pFile->pLock);
23193    releaseOpenCnt(pFile->pOpen);
23194    rc = closeUnixFile(id);
23195    unixLeaveMutex();
23196  }
23197  return rc;
23198}
23199
23200/************** End of the posix advisory lock implementation *****************
23201******************************************************************************/
23202
23203/******************************************************************************
23204****************************** No-op Locking **********************************
23205**
23206** Of the various locking implementations available, this is by far the
23207** simplest:  locking is ignored.  No attempt is made to lock the database
23208** file for reading or writing.
23209**
23210** This locking mode is appropriate for use on read-only databases
23211** (ex: databases that are burned into CD-ROM, for example.)  It can
23212** also be used if the application employs some external mechanism to
23213** prevent simultaneous access of the same database by two or more
23214** database connections.  But there is a serious risk of database
23215** corruption if this locking mode is used in situations where multiple
23216** database connections are accessing the same database file at the same
23217** time and one or more of those connections are writing.
23218*/
23219
23220static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
23221  UNUSED_PARAMETER(NotUsed);
23222  *pResOut = 0;
23223  return SQLITE_OK;
23224}
23225static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
23226  UNUSED_PARAMETER2(NotUsed, NotUsed2);
23227  return SQLITE_OK;
23228}
23229static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
23230  UNUSED_PARAMETER2(NotUsed, NotUsed2);
23231  return SQLITE_OK;
23232}
23233
23234/*
23235** Close the file.
23236*/
23237static int nolockClose(sqlite3_file *id) {
23238  return closeUnixFile(id);
23239}
23240
23241/******************* End of the no-op lock implementation *********************
23242******************************************************************************/
23243
23244/******************************************************************************
23245************************* Begin dot-file Locking ******************************
23246**
23247** The dotfile locking implementation uses the existance of separate lock
23248** files in order to control access to the database.  This works on just
23249** about every filesystem imaginable.  But there are serious downsides:
23250**
23251**    (1)  There is zero concurrency.  A single reader blocks all other
23252**         connections from reading or writing the database.
23253**
23254**    (2)  An application crash or power loss can leave stale lock files
23255**         sitting around that need to be cleared manually.
23256**
23257** Nevertheless, a dotlock is an appropriate locking mode for use if no
23258** other locking strategy is available.
23259**
23260** Dotfile locking works by creating a file in the same directory as the
23261** database and with the same name but with a ".lock" extension added.
23262** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
23263** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
23264*/
23265
23266/*
23267** The file suffix added to the data base filename in order to create the
23268** lock file.
23269*/
23270#define DOTLOCK_SUFFIX ".lock"
23271
23272/*
23273** This routine checks if there is a RESERVED lock held on the specified
23274** file by this or any other process. If such a lock is held, set *pResOut
23275** to a non-zero value otherwise *pResOut is set to zero.  The return value
23276** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23277**
23278** In dotfile locking, either a lock exists or it does not.  So in this
23279** variation of CheckReservedLock(), *pResOut is set to true if any lock
23280** is held on the file and false if the file is unlocked.
23281*/
23282static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23283  int rc = SQLITE_OK;
23284  int reserved = 0;
23285  unixFile *pFile = (unixFile*)id;
23286
23287  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23288
23289  assert( pFile );
23290
23291  /* Check if a thread in this process holds such a lock */
23292  if( pFile->locktype>SHARED_LOCK ){
23293    /* Either this connection or some other connection in the same process
23294    ** holds a lock on the file.  No need to check further. */
23295    reserved = 1;
23296  }else{
23297    /* The lock is held if and only if the lockfile exists */
23298    const char *zLockFile = (const char*)pFile->lockingContext;
23299    reserved = access(zLockFile, 0)==0;
23300  }
23301  OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
23302  *pResOut = reserved;
23303  return rc;
23304}
23305
23306/*
23307** Lock the file with the lock specified by parameter locktype - one
23308** of the following:
23309**
23310**     (1) SHARED_LOCK
23311**     (2) RESERVED_LOCK
23312**     (3) PENDING_LOCK
23313**     (4) EXCLUSIVE_LOCK
23314**
23315** Sometimes when requesting one lock state, additional lock states
23316** are inserted in between.  The locking might fail on one of the later
23317** transitions leaving the lock state different from what it started but
23318** still short of its goal.  The following chart shows the allowed
23319** transitions and the inserted intermediate states:
23320**
23321**    UNLOCKED -> SHARED
23322**    SHARED -> RESERVED
23323**    SHARED -> (PENDING) -> EXCLUSIVE
23324**    RESERVED -> (PENDING) -> EXCLUSIVE
23325**    PENDING -> EXCLUSIVE
23326**
23327** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23328** routine to lower a locking level.
23329**
23330** With dotfile locking, we really only support state (4): EXCLUSIVE.
23331** But we track the other locking levels internally.
23332*/
23333static int dotlockLock(sqlite3_file *id, int locktype) {
23334  unixFile *pFile = (unixFile*)id;
23335  int fd;
23336  char *zLockFile = (char *)pFile->lockingContext;
23337  int rc = SQLITE_OK;
23338
23339
23340  /* If we have any lock, then the lock file already exists.  All we have
23341  ** to do is adjust our internal record of the lock level.
23342  */
23343  if( pFile->locktype > NO_LOCK ){
23344    pFile->locktype = locktype;
23345#if !OS_VXWORKS
23346    /* Always update the timestamp on the old file */
23347    utimes(zLockFile, NULL);
23348#endif
23349    return SQLITE_OK;
23350  }
23351
23352  /* grab an exclusive lock */
23353  fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
23354  if( fd<0 ){
23355    /* failed to open/create the file, someone else may have stolen the lock */
23356    int tErrno = errno;
23357    if( EEXIST == tErrno ){
23358      rc = SQLITE_BUSY;
23359    } else {
23360      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23361      if( IS_LOCK_ERROR(rc) ){
23362        pFile->lastErrno = tErrno;
23363      }
23364    }
23365    return rc;
23366  }
23367  if( close(fd) ){
23368    pFile->lastErrno = errno;
23369    rc = SQLITE_IOERR_CLOSE;
23370  }
23371
23372  /* got it, set the type and return ok */
23373  pFile->locktype = locktype;
23374  return rc;
23375}
23376
23377/*
23378** Lower the locking level on file descriptor pFile to locktype.  locktype
23379** must be either NO_LOCK or SHARED_LOCK.
23380**
23381** If the locking level of the file descriptor is already at or below
23382** the requested locking level, this routine is a no-op.
23383**
23384** When the locking level reaches NO_LOCK, delete the lock file.
23385*/
23386static int dotlockUnlock(sqlite3_file *id, int locktype) {
23387  unixFile *pFile = (unixFile*)id;
23388  char *zLockFile = (char *)pFile->lockingContext;
23389
23390  assert( pFile );
23391  OSTRACE5("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
23392	   pFile->locktype, getpid());
23393  assert( locktype<=SHARED_LOCK );
23394
23395  /* no-op if possible */
23396  if( pFile->locktype==locktype ){
23397    return SQLITE_OK;
23398  }
23399
23400  /* To downgrade to shared, simply update our internal notion of the
23401  ** lock state.  No need to mess with the file on disk.
23402  */
23403  if( locktype==SHARED_LOCK ){
23404    pFile->locktype = SHARED_LOCK;
23405    return SQLITE_OK;
23406  }
23407
23408  /* To fully unlock the database, delete the lock file */
23409  assert( locktype==NO_LOCK );
23410  if( unlink(zLockFile) ){
23411    int rc = 0;
23412    int tErrno = errno;
23413    if( ENOENT != tErrno ){
23414      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23415    }
23416    if( IS_LOCK_ERROR(rc) ){
23417      pFile->lastErrno = tErrno;
23418    }
23419    return rc;
23420  }
23421  pFile->locktype = NO_LOCK;
23422  return SQLITE_OK;
23423}
23424
23425/*
23426** Close a file.  Make sure the lock has been released before closing.
23427*/
23428static int dotlockClose(sqlite3_file *id) {
23429  int rc;
23430  if( id ){
23431    unixFile *pFile = (unixFile*)id;
23432    dotlockUnlock(id, NO_LOCK);
23433    sqlite3_free(pFile->lockingContext);
23434  }
23435  rc = closeUnixFile(id);
23436  return rc;
23437}
23438/****************** End of the dot-file lock implementation *******************
23439******************************************************************************/
23440
23441/******************************************************************************
23442************************** Begin flock Locking ********************************
23443**
23444** Use the flock() system call to do file locking.
23445**
23446** flock() locking is like dot-file locking in that the various
23447** fine-grain locking levels supported by SQLite are collapsed into
23448** a single exclusive lock.  In other words, SHARED, RESERVED, and
23449** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
23450** still works when you do this, but concurrency is reduced since
23451** only a single process can be reading the database at a time.
23452**
23453** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
23454** compiling for VXWORKS.
23455*/
23456#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
23457
23458/*
23459** This routine checks if there is a RESERVED lock held on the specified
23460** file by this or any other process. If such a lock is held, set *pResOut
23461** to a non-zero value otherwise *pResOut is set to zero.  The return value
23462** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23463*/
23464static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
23465  int rc = SQLITE_OK;
23466  int reserved = 0;
23467  unixFile *pFile = (unixFile*)id;
23468
23469  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23470
23471  assert( pFile );
23472
23473  /* Check if a thread in this process holds such a lock */
23474  if( pFile->locktype>SHARED_LOCK ){
23475    reserved = 1;
23476  }
23477
23478  /* Otherwise see if some other process holds it. */
23479  if( !reserved ){
23480    /* attempt to get the lock */
23481    int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
23482    if( !lrc ){
23483      /* got the lock, unlock it */
23484      lrc = flock(pFile->h, LOCK_UN);
23485      if ( lrc ) {
23486        int tErrno = errno;
23487        /* unlock failed with an error */
23488        lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23489        if( IS_LOCK_ERROR(lrc) ){
23490          pFile->lastErrno = tErrno;
23491          rc = lrc;
23492        }
23493      }
23494    } else {
23495      int tErrno = errno;
23496      reserved = 1;
23497      /* someone else might have it reserved */
23498      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23499      if( IS_LOCK_ERROR(lrc) ){
23500        pFile->lastErrno = tErrno;
23501        rc = lrc;
23502      }
23503    }
23504  }
23505  OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
23506
23507#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23508  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
23509    rc = SQLITE_OK;
23510    reserved=1;
23511  }
23512#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23513  *pResOut = reserved;
23514  return rc;
23515}
23516
23517/*
23518** Lock the file with the lock specified by parameter locktype - one
23519** of the following:
23520**
23521**     (1) SHARED_LOCK
23522**     (2) RESERVED_LOCK
23523**     (3) PENDING_LOCK
23524**     (4) EXCLUSIVE_LOCK
23525**
23526** Sometimes when requesting one lock state, additional lock states
23527** are inserted in between.  The locking might fail on one of the later
23528** transitions leaving the lock state different from what it started but
23529** still short of its goal.  The following chart shows the allowed
23530** transitions and the inserted intermediate states:
23531**
23532**    UNLOCKED -> SHARED
23533**    SHARED -> RESERVED
23534**    SHARED -> (PENDING) -> EXCLUSIVE
23535**    RESERVED -> (PENDING) -> EXCLUSIVE
23536**    PENDING -> EXCLUSIVE
23537**
23538** flock() only really support EXCLUSIVE locks.  We track intermediate
23539** lock states in the sqlite3_file structure, but all locks SHARED or
23540** above are really EXCLUSIVE locks and exclude all other processes from
23541** access the file.
23542**
23543** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23544** routine to lower a locking level.
23545*/
23546static int flockLock(sqlite3_file *id, int locktype) {
23547  int rc = SQLITE_OK;
23548  unixFile *pFile = (unixFile*)id;
23549
23550  assert( pFile );
23551
23552  /* if we already have a lock, it is exclusive.
23553  ** Just adjust level and punt on outta here. */
23554  if (pFile->locktype > NO_LOCK) {
23555    pFile->locktype = locktype;
23556    return SQLITE_OK;
23557  }
23558
23559  /* grab an exclusive lock */
23560
23561  if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
23562    int tErrno = errno;
23563    /* didn't get, must be busy */
23564    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23565    if( IS_LOCK_ERROR(rc) ){
23566      pFile->lastErrno = tErrno;
23567    }
23568  } else {
23569    /* got it, set the type and return ok */
23570    pFile->locktype = locktype;
23571  }
23572  OSTRACE4("LOCK    %d %s %s (flock)\n", pFile->h, locktypeName(locktype),
23573           rc==SQLITE_OK ? "ok" : "failed");
23574#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23575  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
23576    rc = SQLITE_BUSY;
23577  }
23578#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23579  return rc;
23580}
23581
23582
23583/*
23584** Lower the locking level on file descriptor pFile to locktype.  locktype
23585** must be either NO_LOCK or SHARED_LOCK.
23586**
23587** If the locking level of the file descriptor is already at or below
23588** the requested locking level, this routine is a no-op.
23589*/
23590static int flockUnlock(sqlite3_file *id, int locktype) {
23591  unixFile *pFile = (unixFile*)id;
23592
23593  assert( pFile );
23594  OSTRACE5("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
23595           pFile->locktype, getpid());
23596  assert( locktype<=SHARED_LOCK );
23597
23598  /* no-op if possible */
23599  if( pFile->locktype==locktype ){
23600    return SQLITE_OK;
23601  }
23602
23603  /* shared can just be set because we always have an exclusive */
23604  if (locktype==SHARED_LOCK) {
23605    pFile->locktype = locktype;
23606    return SQLITE_OK;
23607  }
23608
23609  /* no, really, unlock. */
23610  int rc = flock(pFile->h, LOCK_UN);
23611  if (rc) {
23612    int r, tErrno = errno;
23613    r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23614    if( IS_LOCK_ERROR(r) ){
23615      pFile->lastErrno = tErrno;
23616    }
23617#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
23618    if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
23619      r = SQLITE_BUSY;
23620    }
23621#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
23622
23623    return r;
23624  } else {
23625    pFile->locktype = NO_LOCK;
23626    return SQLITE_OK;
23627  }
23628}
23629
23630/*
23631** Close a file.
23632*/
23633static int flockClose(sqlite3_file *id) {
23634  if( id ){
23635    flockUnlock(id, NO_LOCK);
23636  }
23637  return closeUnixFile(id);
23638}
23639
23640#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
23641
23642/******************* End of the flock lock implementation *********************
23643******************************************************************************/
23644
23645/******************************************************************************
23646************************ Begin Named Semaphore Locking ************************
23647**
23648** Named semaphore locking is only supported on VxWorks.
23649**
23650** Semaphore locking is like dot-lock and flock in that it really only
23651** supports EXCLUSIVE locking.  Only a single process can read or write
23652** the database file at a time.  This reduces potential concurrency, but
23653** makes the lock implementation much easier.
23654*/
23655#if OS_VXWORKS
23656
23657/*
23658** This routine checks if there is a RESERVED lock held on the specified
23659** file by this or any other process. If such a lock is held, set *pResOut
23660** to a non-zero value otherwise *pResOut is set to zero.  The return value
23661** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23662*/
23663static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
23664  int rc = SQLITE_OK;
23665  int reserved = 0;
23666  unixFile *pFile = (unixFile*)id;
23667
23668  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23669
23670  assert( pFile );
23671
23672  /* Check if a thread in this process holds such a lock */
23673  if( pFile->locktype>SHARED_LOCK ){
23674    reserved = 1;
23675  }
23676
23677  /* Otherwise see if some other process holds it. */
23678  if( !reserved ){
23679    sem_t *pSem = pFile->pOpen->pSem;
23680    struct stat statBuf;
23681
23682    if( sem_trywait(pSem)==-1 ){
23683      int tErrno = errno;
23684      if( EAGAIN != tErrno ){
23685        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23686        pFile->lastErrno = tErrno;
23687      } else {
23688        /* someone else has the lock when we are in NO_LOCK */
23689        reserved = (pFile->locktype < SHARED_LOCK);
23690      }
23691    }else{
23692      /* we could have it if we want it */
23693      sem_post(pSem);
23694    }
23695  }
23696  OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
23697
23698  *pResOut = reserved;
23699  return rc;
23700}
23701
23702/*
23703** Lock the file with the lock specified by parameter locktype - one
23704** of the following:
23705**
23706**     (1) SHARED_LOCK
23707**     (2) RESERVED_LOCK
23708**     (3) PENDING_LOCK
23709**     (4) EXCLUSIVE_LOCK
23710**
23711** Sometimes when requesting one lock state, additional lock states
23712** are inserted in between.  The locking might fail on one of the later
23713** transitions leaving the lock state different from what it started but
23714** still short of its goal.  The following chart shows the allowed
23715** transitions and the inserted intermediate states:
23716**
23717**    UNLOCKED -> SHARED
23718**    SHARED -> RESERVED
23719**    SHARED -> (PENDING) -> EXCLUSIVE
23720**    RESERVED -> (PENDING) -> EXCLUSIVE
23721**    PENDING -> EXCLUSIVE
23722**
23723** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
23724** lock states in the sqlite3_file structure, but all locks SHARED or
23725** above are really EXCLUSIVE locks and exclude all other processes from
23726** access the file.
23727**
23728** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23729** routine to lower a locking level.
23730*/
23731static int semLock(sqlite3_file *id, int locktype) {
23732  unixFile *pFile = (unixFile*)id;
23733  int fd;
23734  sem_t *pSem = pFile->pOpen->pSem;
23735  int rc = SQLITE_OK;
23736
23737  /* if we already have a lock, it is exclusive.
23738  ** Just adjust level and punt on outta here. */
23739  if (pFile->locktype > NO_LOCK) {
23740    pFile->locktype = locktype;
23741    rc = SQLITE_OK;
23742    goto sem_end_lock;
23743  }
23744
23745  /* lock semaphore now but bail out when already locked. */
23746  if( sem_trywait(pSem)==-1 ){
23747    rc = SQLITE_BUSY;
23748    goto sem_end_lock;
23749  }
23750
23751  /* got it, set the type and return ok */
23752  pFile->locktype = locktype;
23753
23754 sem_end_lock:
23755  return rc;
23756}
23757
23758/*
23759** Lower the locking level on file descriptor pFile to locktype.  locktype
23760** must be either NO_LOCK or SHARED_LOCK.
23761**
23762** If the locking level of the file descriptor is already at or below
23763** the requested locking level, this routine is a no-op.
23764*/
23765static int semUnlock(sqlite3_file *id, int locktype) {
23766  unixFile *pFile = (unixFile*)id;
23767  sem_t *pSem = pFile->pOpen->pSem;
23768
23769  assert( pFile );
23770  assert( pSem );
23771  OSTRACE5("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
23772	   pFile->locktype, getpid());
23773  assert( locktype<=SHARED_LOCK );
23774
23775  /* no-op if possible */
23776  if( pFile->locktype==locktype ){
23777    return SQLITE_OK;
23778  }
23779
23780  /* shared can just be set because we always have an exclusive */
23781  if (locktype==SHARED_LOCK) {
23782    pFile->locktype = locktype;
23783    return SQLITE_OK;
23784  }
23785
23786  /* no, really unlock. */
23787  if ( sem_post(pSem)==-1 ) {
23788    int rc, tErrno = errno;
23789    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23790    if( IS_LOCK_ERROR(rc) ){
23791      pFile->lastErrno = tErrno;
23792    }
23793    return rc;
23794  }
23795  pFile->locktype = NO_LOCK;
23796  return SQLITE_OK;
23797}
23798
23799/*
23800 ** Close a file.
23801 */
23802static int semClose(sqlite3_file *id) {
23803  if( id ){
23804    unixFile *pFile = (unixFile*)id;
23805    semUnlock(id, NO_LOCK);
23806    assert( pFile );
23807    unixEnterMutex();
23808    releaseLockInfo(pFile->pLock);
23809    releaseOpenCnt(pFile->pOpen);
23810    unixLeaveMutex();
23811    closeUnixFile(id);
23812  }
23813  return SQLITE_OK;
23814}
23815
23816#endif /* OS_VXWORKS */
23817/*
23818** Named semaphore locking is only available on VxWorks.
23819**
23820*************** End of the named semaphore lock implementation ****************
23821******************************************************************************/
23822
23823
23824/******************************************************************************
23825*************************** Begin AFP Locking *********************************
23826**
23827** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
23828** on Apple Macintosh computers - both OS9 and OSX.
23829**
23830** Third-party implementations of AFP are available.  But this code here
23831** only works on OSX.
23832*/
23833
23834#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
23835/*
23836** The afpLockingContext structure contains all afp lock specific state
23837*/
23838typedef struct afpLockingContext afpLockingContext;
23839struct afpLockingContext {
23840  unsigned long long sharedByte;
23841  const char *dbPath;             /* Name of the open file */
23842};
23843
23844struct ByteRangeLockPB2
23845{
23846  unsigned long long offset;        /* offset to first byte to lock */
23847  unsigned long long length;        /* nbr of bytes to lock */
23848  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
23849  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
23850  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
23851  int fd;                           /* file desc to assoc this lock with */
23852};
23853
23854#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
23855
23856/*
23857** This is a utility for setting or clearing a bit-range lock on an
23858** AFP filesystem.
23859**
23860** Return SQLITE_OK on success, SQLITE_BUSY on failure.
23861*/
23862static int afpSetLock(
23863  const char *path,              /* Name of the file to be locked or unlocked */
23864  unixFile *pFile,               /* Open file descriptor on path */
23865  unsigned long long offset,     /* First byte to be locked */
23866  unsigned long long length,     /* Number of bytes to lock */
23867  int setLockFlag                /* True to set lock.  False to clear lock */
23868){
23869  struct ByteRangeLockPB2 pb;
23870  int err;
23871
23872  pb.unLockFlag = setLockFlag ? 0 : 1;
23873  pb.startEndFlag = 0;
23874  pb.offset = offset;
23875  pb.length = length;
23876  pb.fd = pFile->h;
23877
23878  OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
23879    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
23880    offset, length);
23881  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
23882  if ( err==-1 ) {
23883    int rc;
23884    int tErrno = errno;
23885    OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
23886             path, tErrno, strerror(tErrno));
23887#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
23888    rc = SQLITE_BUSY;
23889#else
23890    rc = sqliteErrorFromPosixError(tErrno,
23891                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
23892#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
23893    if( IS_LOCK_ERROR(rc) ){
23894      pFile->lastErrno = tErrno;
23895    }
23896    return rc;
23897  } else {
23898    return SQLITE_OK;
23899  }
23900}
23901
23902/*
23903** This routine checks if there is a RESERVED lock held on the specified
23904** file by this or any other process. If such a lock is held, set *pResOut
23905** to a non-zero value otherwise *pResOut is set to zero.  The return value
23906** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23907*/
23908static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
23909  int rc = SQLITE_OK;
23910  int reserved = 0;
23911  unixFile *pFile = (unixFile*)id;
23912
23913  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23914
23915  assert( pFile );
23916  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23917
23918  /* Check if a thread in this process holds such a lock */
23919  if( pFile->locktype>SHARED_LOCK ){
23920    reserved = 1;
23921  }
23922
23923  /* Otherwise see if some other process holds it.
23924   */
23925  if( !reserved ){
23926    /* lock the RESERVED byte */
23927    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
23928    if( SQLITE_OK==lrc ){
23929      /* if we succeeded in taking the reserved lock, unlock it to restore
23930      ** the original state */
23931      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
23932    } else {
23933      /* if we failed to get the lock then someone else must have it */
23934      reserved = 1;
23935    }
23936    if( IS_LOCK_ERROR(lrc) ){
23937      rc=lrc;
23938    }
23939  }
23940
23941  OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
23942
23943  *pResOut = reserved;
23944  return rc;
23945}
23946
23947/*
23948** Lock the file with the lock specified by parameter locktype - one
23949** of the following:
23950**
23951**     (1) SHARED_LOCK
23952**     (2) RESERVED_LOCK
23953**     (3) PENDING_LOCK
23954**     (4) EXCLUSIVE_LOCK
23955**
23956** Sometimes when requesting one lock state, additional lock states
23957** are inserted in between.  The locking might fail on one of the later
23958** transitions leaving the lock state different from what it started but
23959** still short of its goal.  The following chart shows the allowed
23960** transitions and the inserted intermediate states:
23961**
23962**    UNLOCKED -> SHARED
23963**    SHARED -> RESERVED
23964**    SHARED -> (PENDING) -> EXCLUSIVE
23965**    RESERVED -> (PENDING) -> EXCLUSIVE
23966**    PENDING -> EXCLUSIVE
23967**
23968** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23969** routine to lower a locking level.
23970*/
23971static int afpLock(sqlite3_file *id, int locktype){
23972  int rc = SQLITE_OK;
23973  unixFile *pFile = (unixFile*)id;
23974  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
23975
23976  assert( pFile );
23977  OSTRACE5("LOCK    %d %s was %s pid=%d (afp)\n", pFile->h,
23978         locktypeName(locktype), locktypeName(pFile->locktype), getpid());
23979
23980  /* If there is already a lock of this type or more restrictive on the
23981  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
23982  ** unixEnterMutex() hasn't been called yet.
23983  */
23984  if( pFile->locktype>=locktype ){
23985    OSTRACE3("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
23986           locktypeName(locktype));
23987    return SQLITE_OK;
23988  }
23989
23990  /* Make sure the locking sequence is correct
23991  */
23992  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23993  assert( locktype!=PENDING_LOCK );
23994  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23995
23996  /* This mutex is needed because pFile->pLock is shared across threads
23997  */
23998  unixEnterMutex();
23999
24000  /* Make sure the current thread owns the pFile.
24001  */
24002  rc = transferOwnership(pFile);
24003  if( rc!=SQLITE_OK ){
24004    unixLeaveMutex();
24005    return rc;
24006  }
24007
24008  /* A PENDING lock is needed before acquiring a SHARED lock and before
24009  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24010  ** be released.
24011  */
24012  if( locktype==SHARED_LOCK
24013      || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
24014  ){
24015    int failed;
24016    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
24017    if (failed) {
24018      rc = failed;
24019      goto afp_end_lock;
24020    }
24021  }
24022
24023  /* If control gets to this point, then actually go ahead and make
24024  ** operating system calls for the specified lock.
24025  */
24026  if( locktype==SHARED_LOCK ){
24027    int lk, lrc1, lrc2;
24028    int lrc1Errno = 0;
24029
24030    /* Now get the read-lock SHARED_LOCK */
24031    /* note that the quality of the randomness doesn't matter that much */
24032    lk = random();
24033    context->sharedByte = (lk & 0x7fffffff)%(SHARED_SIZE - 1);
24034    lrc1 = afpSetLock(context->dbPath, pFile,
24035          SHARED_FIRST+context->sharedByte, 1, 1);
24036    if( IS_LOCK_ERROR(lrc1) ){
24037      lrc1Errno = pFile->lastErrno;
24038    }
24039    /* Drop the temporary PENDING lock */
24040    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24041
24042    if( IS_LOCK_ERROR(lrc1) ) {
24043      pFile->lastErrno = lrc1Errno;
24044      rc = lrc1;
24045      goto afp_end_lock;
24046    } else if( IS_LOCK_ERROR(lrc2) ){
24047      rc = lrc2;
24048      goto afp_end_lock;
24049    } else if( lrc1 != SQLITE_OK ) {
24050      rc = lrc1;
24051    } else {
24052      pFile->locktype = SHARED_LOCK;
24053      pFile->pOpen->nLock++;
24054    }
24055  }else{
24056    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24057    ** assumed that there is a SHARED or greater lock on the file
24058    ** already.
24059    */
24060    int failed = 0;
24061    assert( 0!=pFile->locktype );
24062    if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
24063        /* Acquire a RESERVED lock */
24064        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24065    }
24066    if (!failed && locktype == EXCLUSIVE_LOCK) {
24067      /* Acquire an EXCLUSIVE lock */
24068
24069      /* Remove the shared lock before trying the range.  we'll need to
24070      ** reestablish the shared lock if we can't get the  afpUnlock
24071      */
24072      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
24073                         context->sharedByte, 1, 0)) ){
24074        int failed2 = SQLITE_OK;
24075        /* now attemmpt to get the exclusive lock range */
24076        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
24077                               SHARED_SIZE, 1);
24078        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
24079                       SHARED_FIRST + context->sharedByte, 1, 1)) ){
24080          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
24081          ** a critical I/O error
24082          */
24083          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
24084               SQLITE_IOERR_LOCK;
24085          goto afp_end_lock;
24086        }
24087      }else{
24088        rc = failed;
24089      }
24090    }
24091    if( failed ){
24092      rc = failed;
24093    }
24094  }
24095
24096  if( rc==SQLITE_OK ){
24097    pFile->locktype = locktype;
24098  }else if( locktype==EXCLUSIVE_LOCK ){
24099    pFile->locktype = PENDING_LOCK;
24100  }
24101
24102afp_end_lock:
24103  unixLeaveMutex();
24104  OSTRACE4("LOCK    %d %s %s (afp)\n", pFile->h, locktypeName(locktype),
24105         rc==SQLITE_OK ? "ok" : "failed");
24106  return rc;
24107}
24108
24109/*
24110** Lower the locking level on file descriptor pFile to locktype.  locktype
24111** must be either NO_LOCK or SHARED_LOCK.
24112**
24113** If the locking level of the file descriptor is already at or below
24114** the requested locking level, this routine is a no-op.
24115*/
24116static int afpUnlock(sqlite3_file *id, int locktype) {
24117  int rc = SQLITE_OK;
24118  unixFile *pFile = (unixFile*)id;
24119  afpLockingContext *pCtx = (afpLockingContext *) pFile->lockingContext;
24120
24121  assert( pFile );
24122  OSTRACE5("UNLOCK  %d %d was %d pid=%d (afp)\n", pFile->h, locktype,
24123         pFile->locktype, getpid());
24124
24125  assert( locktype<=SHARED_LOCK );
24126  if( pFile->locktype<=locktype ){
24127    return SQLITE_OK;
24128  }
24129  if( CHECK_THREADID(pFile) ){
24130    return SQLITE_MISUSE;
24131  }
24132  unixEnterMutex();
24133  if( pFile->locktype>SHARED_LOCK ){
24134
24135    if( pFile->locktype==EXCLUSIVE_LOCK ){
24136      rc = afpSetLock(pCtx->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
24137      if( rc==SQLITE_OK && locktype==SHARED_LOCK ){
24138        /* only re-establish the shared lock if necessary */
24139        int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
24140        rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 1);
24141      }
24142    }
24143    if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
24144      rc = afpSetLock(pCtx->dbPath, pFile, PENDING_BYTE, 1, 0);
24145    }
24146    if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK ){
24147      rc = afpSetLock(pCtx->dbPath, pFile, RESERVED_BYTE, 1, 0);
24148    }
24149  }else if( locktype==NO_LOCK ){
24150    /* clear the shared lock */
24151    int sharedLockByte = SHARED_FIRST+pCtx->sharedByte;
24152    rc = afpSetLock(pCtx->dbPath, pFile, sharedLockByte, 1, 0);
24153  }
24154
24155  if( rc==SQLITE_OK ){
24156    if( locktype==NO_LOCK ){
24157      struct unixOpenCnt *pOpen = pFile->pOpen;
24158      pOpen->nLock--;
24159      assert( pOpen->nLock>=0 );
24160      if( pOpen->nLock==0 ){
24161        rc = closePendingFds(pFile);
24162      }
24163    }
24164  }
24165  unixLeaveMutex();
24166  if( rc==SQLITE_OK ){
24167    pFile->locktype = locktype;
24168  }
24169  return rc;
24170}
24171
24172/*
24173** Close a file & cleanup AFP specific locking context
24174*/
24175static int afpClose(sqlite3_file *id) {
24176  if( id ){
24177    unixFile *pFile = (unixFile*)id;
24178    afpUnlock(id, NO_LOCK);
24179    unixEnterMutex();
24180    if( pFile->pOpen && pFile->pOpen->nLock ){
24181      /* If there are outstanding locks, do not actually close the file just
24182      ** yet because that would clear those locks.  Instead, add the file
24183      ** descriptor to pOpen->aPending.  It will be automatically closed when
24184      ** the last lock is cleared.
24185      */
24186      setPendingFd(pFile);
24187    }
24188    releaseOpenCnt(pFile->pOpen);
24189    sqlite3_free(pFile->lockingContext);
24190    closeUnixFile(id);
24191    unixLeaveMutex();
24192  }
24193  return SQLITE_OK;
24194}
24195
24196#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24197/*
24198** The code above is the AFP lock implementation.  The code is specific
24199** to MacOSX and does not work on other unix platforms.  No alternative
24200** is available.  If you don't compile for a mac, then the "unix-afp"
24201** VFS is not available.
24202**
24203********************* End of the AFP lock implementation **********************
24204******************************************************************************/
24205
24206
24207/******************************************************************************
24208**************** Non-locking sqlite3_file methods *****************************
24209**
24210** The next division contains implementations for all methods of the
24211** sqlite3_file object other than the locking methods.  The locking
24212** methods were defined in divisions above (one locking method per
24213** division).  Those methods that are common to all locking modes
24214** are gather together into this division.
24215*/
24216
24217/*
24218** Seek to the offset passed as the second argument, then read cnt
24219** bytes into pBuf. Return the number of bytes actually read.
24220**
24221** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
24222** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
24223** one system to another.  Since SQLite does not define USE_PREAD
24224** any any form by default, we will not attempt to define _XOPEN_SOURCE.
24225** See tickets #2741 and #2681.
24226**
24227** To avoid stomping the errno value on a failed read the lastErrno value
24228** is set before returning.
24229*/
24230static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
24231  int got;
24232  i64 newOffset;
24233  TIMER_START;
24234#if defined(USE_PREAD)
24235  got = pread(id->h, pBuf, cnt, offset);
24236  SimulateIOError( got = -1 );
24237#elif defined(USE_PREAD64)
24238  got = pread64(id->h, pBuf, cnt, offset);
24239  SimulateIOError( got = -1 );
24240#else
24241  newOffset = lseek(id->h, offset, SEEK_SET);
24242  SimulateIOError( newOffset-- );
24243  if( newOffset!=offset ){
24244    if( newOffset == -1 ){
24245      ((unixFile*)id)->lastErrno = errno;
24246    }else{
24247      ((unixFile*)id)->lastErrno = 0;
24248    }
24249    return -1;
24250  }
24251  got = read(id->h, pBuf, cnt);
24252#endif
24253  TIMER_END;
24254  if( got<0 ){
24255    ((unixFile*)id)->lastErrno = errno;
24256  }
24257  OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
24258  return got;
24259}
24260
24261/*
24262** Read data from a file into a buffer.  Return SQLITE_OK if all
24263** bytes were read successfully and SQLITE_IOERR if anything goes
24264** wrong.
24265*/
24266static int unixRead(
24267  sqlite3_file *id,
24268  void *pBuf,
24269  int amt,
24270  sqlite3_int64 offset
24271){
24272  unixFile *pFile = (unixFile *)id;
24273  int got;
24274  assert( id );
24275
24276  /* If this is a database file (not a journal, master-journal or temp
24277  ** file), the bytes in the locking range should never be read or written. */
24278  assert( pFile->pUnused==0
24279       || offset>=PENDING_BYTE+512
24280       || offset+amt<=PENDING_BYTE
24281  );
24282
24283  got = seekAndRead(pFile, offset, pBuf, amt);
24284  if( got==amt ){
24285    return SQLITE_OK;
24286  }else if( got<0 ){
24287    /* lastErrno set by seekAndRead */
24288    return SQLITE_IOERR_READ;
24289  }else{
24290    pFile->lastErrno = 0; /* not a system error */
24291    /* Unread parts of the buffer must be zero-filled */
24292    memset(&((char*)pBuf)[got], 0, amt-got);
24293    return SQLITE_IOERR_SHORT_READ;
24294  }
24295}
24296
24297/*
24298** Seek to the offset in id->offset then read cnt bytes into pBuf.
24299** Return the number of bytes actually read.  Update the offset.
24300**
24301** To avoid stomping the errno value on a failed write the lastErrno value
24302** is set before returning.
24303*/
24304static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
24305  int got;
24306  i64 newOffset;
24307  TIMER_START;
24308#if defined(USE_PREAD)
24309  got = pwrite(id->h, pBuf, cnt, offset);
24310#elif defined(USE_PREAD64)
24311  got = pwrite64(id->h, pBuf, cnt, offset);
24312#else
24313  newOffset = lseek(id->h, offset, SEEK_SET);
24314  if( newOffset!=offset ){
24315    if( newOffset == -1 ){
24316      ((unixFile*)id)->lastErrno = errno;
24317    }else{
24318      ((unixFile*)id)->lastErrno = 0;
24319    }
24320    return -1;
24321  }
24322  got = write(id->h, pBuf, cnt);
24323#endif
24324  TIMER_END;
24325  if( got<0 ){
24326    ((unixFile*)id)->lastErrno = errno;
24327  }
24328
24329  OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
24330  return got;
24331}
24332
24333
24334/*
24335** Write data from a buffer into a file.  Return SQLITE_OK on success
24336** or some other error code on failure.
24337*/
24338static int unixWrite(
24339  sqlite3_file *id,
24340  const void *pBuf,
24341  int amt,
24342  sqlite3_int64 offset
24343){
24344  unixFile *pFile = (unixFile*)id;
24345  int wrote = 0;
24346  assert( id );
24347  assert( amt>0 );
24348
24349  /* If this is a database file (not a journal, master-journal or temp
24350  ** file), the bytes in the locking range should never be read or written. */
24351  assert( pFile->pUnused==0
24352       || offset>=PENDING_BYTE+512
24353       || offset+amt<=PENDING_BYTE
24354  );
24355
24356#ifndef NDEBUG
24357  /* If we are doing a normal write to a database file (as opposed to
24358  ** doing a hot-journal rollback or a write to some file other than a
24359  ** normal database file) then record the fact that the database
24360  ** has changed.  If the transaction counter is modified, record that
24361  ** fact too.
24362  */
24363  if( pFile->inNormalWrite ){
24364    pFile->dbUpdate = 1;  /* The database has been modified */
24365    if( offset<=24 && offset+amt>=27 ){
24366      int rc;
24367      char oldCntr[4];
24368      SimulateIOErrorBenign(1);
24369      rc = seekAndRead(pFile, 24, oldCntr, 4);
24370      SimulateIOErrorBenign(0);
24371      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
24372        pFile->transCntrChng = 1;  /* The transaction counter has changed */
24373      }
24374    }
24375  }
24376#endif
24377
24378  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
24379    amt -= wrote;
24380    offset += wrote;
24381    pBuf = &((char*)pBuf)[wrote];
24382  }
24383  SimulateIOError(( wrote=(-1), amt=1 ));
24384  SimulateDiskfullError(( wrote=0, amt=1 ));
24385  if( amt>0 ){
24386    if( wrote<0 ){
24387      /* lastErrno set by seekAndWrite */
24388      return SQLITE_IOERR_WRITE;
24389    }else{
24390      pFile->lastErrno = 0; /* not a system error */
24391      return SQLITE_FULL;
24392    }
24393  }
24394  return SQLITE_OK;
24395}
24396
24397#ifdef SQLITE_TEST
24398/*
24399** Count the number of fullsyncs and normal syncs.  This is used to test
24400** that syncs and fullsyncs are occurring at the right times.
24401*/
24402SQLITE_API int sqlite3_sync_count = 0;
24403SQLITE_API int sqlite3_fullsync_count = 0;
24404#endif
24405
24406/*
24407** We do not trust systems to provide a working fdatasync().  Some do.
24408** Others do no.  To be safe, we will stick with the (slower) fsync().
24409** If you know that your system does support fdatasync() correctly,
24410** then simply compile with -Dfdatasync=fdatasync
24411*/
24412#if !defined(fdatasync) && !defined(__linux__)
24413# define fdatasync fsync
24414#endif
24415
24416/*
24417** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
24418** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
24419** only available on Mac OS X.  But that could change.
24420*/
24421#ifdef F_FULLFSYNC
24422# define HAVE_FULLFSYNC 1
24423#else
24424# define HAVE_FULLFSYNC 0
24425#endif
24426
24427
24428/*
24429** The fsync() system call does not work as advertised on many
24430** unix systems.  The following procedure is an attempt to make
24431** it work better.
24432**
24433** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
24434** for testing when we want to run through the test suite quickly.
24435** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
24436** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
24437** or power failure will likely corrupt the database file.
24438**
24439** SQLite sets the dataOnly flag if the size of the file is unchanged.
24440** The idea behind dataOnly is that it should only write the file content
24441** to disk, not the inode.  We only set dataOnly if the file size is
24442** unchanged since the file size is part of the inode.  However,
24443** Ted Ts'o tells us that fdatasync() will also write the inode if the
24444** file size has changed.  The only real difference between fdatasync()
24445** and fsync(), Ted tells us, is that fdatasync() will not flush the
24446** inode if the mtime or owner or other inode attributes have changed.
24447** We only care about the file size, not the other file attributes, so
24448** as far as SQLite is concerned, an fdatasync() is always adequate.
24449** So, we always use fdatasync() if it is available, regardless of
24450** the value of the dataOnly flag.
24451*/
24452static int full_fsync(int fd, int fullSync, int dataOnly){
24453  int rc;
24454
24455  /* The following "ifdef/elif/else/" block has the same structure as
24456  ** the one below. It is replicated here solely to avoid cluttering
24457  ** up the real code with the UNUSED_PARAMETER() macros.
24458  */
24459#ifdef SQLITE_NO_SYNC
24460  UNUSED_PARAMETER(fd);
24461  UNUSED_PARAMETER(fullSync);
24462  UNUSED_PARAMETER(dataOnly);
24463#elif HAVE_FULLFSYNC
24464  UNUSED_PARAMETER(dataOnly);
24465#else
24466  UNUSED_PARAMETER(fullSync);
24467  UNUSED_PARAMETER(dataOnly);
24468#endif
24469
24470  /* Record the number of times that we do a normal fsync() and
24471  ** FULLSYNC.  This is used during testing to verify that this procedure
24472  ** gets called with the correct arguments.
24473  */
24474#ifdef SQLITE_TEST
24475  if( fullSync ) sqlite3_fullsync_count++;
24476  sqlite3_sync_count++;
24477#endif
24478
24479  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
24480  ** no-op
24481  */
24482#ifdef SQLITE_NO_SYNC
24483  rc = SQLITE_OK;
24484#elif HAVE_FULLFSYNC
24485  if( fullSync ){
24486    rc = fcntl(fd, F_FULLFSYNC, 0);
24487  }else{
24488    rc = 1;
24489  }
24490  /* If the FULLFSYNC failed, fall back to attempting an fsync().
24491  ** It shouldn't be possible for fullfsync to fail on the local
24492  ** file system (on OSX), so failure indicates that FULLFSYNC
24493  ** isn't supported for this file system. So, attempt an fsync
24494  ** and (for now) ignore the overhead of a superfluous fcntl call.
24495  ** It'd be better to detect fullfsync support once and avoid
24496  ** the fcntl call every time sync is called.
24497  */
24498  if( rc ) rc = fsync(fd);
24499
24500#else
24501  rc = fdatasync(fd);
24502#if OS_VXWORKS
24503  if( rc==-1 && errno==ENOTSUP ){
24504    rc = fsync(fd);
24505  }
24506#endif /* OS_VXWORKS */
24507#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
24508
24509  if( OS_VXWORKS && rc!= -1 ){
24510    rc = 0;
24511  }
24512  return rc;
24513}
24514
24515/*
24516** Make sure all writes to a particular file are committed to disk.
24517**
24518** If dataOnly==0 then both the file itself and its metadata (file
24519** size, access time, etc) are synced.  If dataOnly!=0 then only the
24520** file data is synced.
24521**
24522** Under Unix, also make sure that the directory entry for the file
24523** has been created by fsync-ing the directory that contains the file.
24524** If we do not do this and we encounter a power failure, the directory
24525** entry for the journal might not exist after we reboot.  The next
24526** SQLite to access the file will not know that the journal exists (because
24527** the directory entry for the journal was never created) and the transaction
24528** will not roll back - possibly leading to database corruption.
24529*/
24530static int unixSync(sqlite3_file *id, int flags){
24531  int rc;
24532  unixFile *pFile = (unixFile*)id;
24533
24534  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
24535  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
24536
24537  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
24538  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
24539      || (flags&0x0F)==SQLITE_SYNC_FULL
24540  );
24541
24542  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
24543  ** line is to test that doing so does not cause any problems.
24544  */
24545  SimulateDiskfullError( return SQLITE_FULL );
24546
24547  assert( pFile );
24548  OSTRACE2("SYNC    %-3d\n", pFile->h);
24549  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
24550  SimulateIOError( rc=1 );
24551  if( rc ){
24552    pFile->lastErrno = errno;
24553    return SQLITE_IOERR_FSYNC;
24554  }
24555  if( pFile->dirfd>=0 ){
24556    int err;
24557    OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
24558            HAVE_FULLFSYNC, isFullsync);
24559#ifndef SQLITE_DISABLE_DIRSYNC
24560    /* The directory sync is only attempted if full_fsync is
24561    ** turned off or unavailable.  If a full_fsync occurred above,
24562    ** then the directory sync is superfluous.
24563    */
24564    if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
24565       /*
24566       ** We have received multiple reports of fsync() returning
24567       ** errors when applied to directories on certain file systems.
24568       ** A failed directory sync is not a big deal.  So it seems
24569       ** better to ignore the error.  Ticket #1657
24570       */
24571       /* pFile->lastErrno = errno; */
24572       /* return SQLITE_IOERR; */
24573    }
24574#endif
24575    err = close(pFile->dirfd); /* Only need to sync once, so close the */
24576    if( err==0 ){              /* directory when we are done */
24577      pFile->dirfd = -1;
24578    }else{
24579      pFile->lastErrno = errno;
24580      rc = SQLITE_IOERR_DIR_CLOSE;
24581    }
24582  }
24583  return rc;
24584}
24585
24586/*
24587** Truncate an open file to a specified size
24588*/
24589static int unixTruncate(sqlite3_file *id, i64 nByte){
24590  int rc;
24591  assert( id );
24592  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
24593  rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
24594  if( rc ){
24595    ((unixFile*)id)->lastErrno = errno;
24596    return SQLITE_IOERR_TRUNCATE;
24597  }else{
24598#ifndef NDEBUG
24599    /* If we are doing a normal write to a database file (as opposed to
24600    ** doing a hot-journal rollback or a write to some file other than a
24601    ** normal database file) and we truncate the file to zero length,
24602    ** that effectively updates the change counter.  This might happen
24603    ** when restoring a database using the backup API from a zero-length
24604    ** source.
24605    */
24606    if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
24607      ((unixFile*)id)->transCntrChng = 1;
24608    }
24609#endif
24610
24611    return SQLITE_OK;
24612  }
24613}
24614
24615/*
24616** Determine the current size of a file in bytes
24617*/
24618static int unixFileSize(sqlite3_file *id, i64 *pSize){
24619  int rc;
24620  struct stat buf;
24621  assert( id );
24622  rc = fstat(((unixFile*)id)->h, &buf);
24623  SimulateIOError( rc=1 );
24624  if( rc!=0 ){
24625    ((unixFile*)id)->lastErrno = errno;
24626    return SQLITE_IOERR_FSTAT;
24627  }
24628  *pSize = buf.st_size;
24629
24630  /* When opening a zero-size database, the findLockInfo() procedure
24631  ** writes a single byte into that file in order to work around a bug
24632  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
24633  ** layers, we need to report this file size as zero even though it is
24634  ** really 1.   Ticket #3260.
24635  */
24636  if( *pSize==1 ) *pSize = 0;
24637
24638
24639  return SQLITE_OK;
24640}
24641
24642#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
24643/*
24644** Handler for proxy-locking file-control verbs.  Defined below in the
24645** proxying locking division.
24646*/
24647static int proxyFileControl(sqlite3_file*,int,void*);
24648#endif
24649
24650
24651/*
24652** Information and control of an open file handle.
24653*/
24654static int unixFileControl(sqlite3_file *id, int op, void *pArg){
24655  switch( op ){
24656    case SQLITE_FCNTL_LOCKSTATE: {
24657      *(int*)pArg = ((unixFile*)id)->locktype;
24658      return SQLITE_OK;
24659    }
24660    case SQLITE_LAST_ERRNO: {
24661      *(int*)pArg = ((unixFile*)id)->lastErrno;
24662      return SQLITE_OK;
24663    }
24664#ifndef NDEBUG
24665    /* The pager calls this method to signal that it has done
24666    ** a rollback and that the database is therefore unchanged and
24667    ** it hence it is OK for the transaction change counter to be
24668    ** unchanged.
24669    */
24670    case SQLITE_FCNTL_DB_UNCHANGED: {
24671      ((unixFile*)id)->dbUpdate = 0;
24672      return SQLITE_OK;
24673    }
24674#endif
24675#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
24676    case SQLITE_SET_LOCKPROXYFILE:
24677    case SQLITE_GET_LOCKPROXYFILE: {
24678      return proxyFileControl(id,op,pArg);
24679    }
24680#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
24681  }
24682  return SQLITE_ERROR;
24683}
24684
24685/*
24686** Return the sector size in bytes of the underlying block device for
24687** the specified file. This is almost always 512 bytes, but may be
24688** larger for some devices.
24689**
24690** SQLite code assumes this function cannot fail. It also assumes that
24691** if two files are created in the same file-system directory (i.e.
24692** a database and its journal file) that the sector size will be the
24693** same for both.
24694*/
24695static int unixSectorSize(sqlite3_file *NotUsed){
24696  UNUSED_PARAMETER(NotUsed);
24697  return SQLITE_DEFAULT_SECTOR_SIZE;
24698}
24699
24700/*
24701** Return the device characteristics for the file. This is always 0 for unix.
24702*/
24703static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
24704  UNUSED_PARAMETER(NotUsed);
24705  return 0;
24706}
24707
24708/*
24709** Here ends the implementation of all sqlite3_file methods.
24710**
24711********************** End sqlite3_file Methods *******************************
24712******************************************************************************/
24713
24714/*
24715** This division contains definitions of sqlite3_io_methods objects that
24716** implement various file locking strategies.  It also contains definitions
24717** of "finder" functions.  A finder-function is used to locate the appropriate
24718** sqlite3_io_methods object for a particular database file.  The pAppData
24719** field of the sqlite3_vfs VFS objects are initialized to be pointers to
24720** the correct finder-function for that VFS.
24721**
24722** Most finder functions return a pointer to a fixed sqlite3_io_methods
24723** object.  The only interesting finder-function is autolockIoFinder, which
24724** looks at the filesystem type and tries to guess the best locking
24725** strategy from that.
24726**
24727** For finder-funtion F, two objects are created:
24728**
24729**    (1) The real finder-function named "FImpt()".
24730**
24731**    (2) A constant pointer to this function named just "F".
24732**
24733**
24734** A pointer to the F pointer is used as the pAppData value for VFS
24735** objects.  We have to do this instead of letting pAppData point
24736** directly at the finder-function since C90 rules prevent a void*
24737** from be cast into a function pointer.
24738**
24739**
24740** Each instance of this macro generates two objects:
24741**
24742**   *  A constant sqlite3_io_methods object call METHOD that has locking
24743**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
24744**
24745**   *  An I/O method finder function called FINDER that returns a pointer
24746**      to the METHOD object in the previous bullet.
24747*/
24748#define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK)               \
24749static const sqlite3_io_methods METHOD = {                                   \
24750   1,                          /* iVersion */                                \
24751   CLOSE,                      /* xClose */                                  \
24752   unixRead,                   /* xRead */                                   \
24753   unixWrite,                  /* xWrite */                                  \
24754   unixTruncate,               /* xTruncate */                               \
24755   unixSync,                   /* xSync */                                   \
24756   unixFileSize,               /* xFileSize */                               \
24757   LOCK,                       /* xLock */                                   \
24758   UNLOCK,                     /* xUnlock */                                 \
24759   CKLOCK,                     /* xCheckReservedLock */                      \
24760   unixFileControl,            /* xFileControl */                            \
24761   unixSectorSize,             /* xSectorSize */                             \
24762   unixDeviceCharacteristics   /* xDeviceCapabilities */                     \
24763};                                                                           \
24764static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
24765  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
24766  return &METHOD;                                                            \
24767}                                                                            \
24768static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
24769    = FINDER##Impl;
24770
24771/*
24772** Here are all of the sqlite3_io_methods objects for each of the
24773** locking strategies.  Functions that return pointers to these methods
24774** are also created.
24775*/
24776IOMETHODS(
24777  posixIoFinder,            /* Finder function name */
24778  posixIoMethods,           /* sqlite3_io_methods object name */
24779  unixClose,                /* xClose method */
24780  unixLock,                 /* xLock method */
24781  unixUnlock,               /* xUnlock method */
24782  unixCheckReservedLock     /* xCheckReservedLock method */
24783)
24784IOMETHODS(
24785  nolockIoFinder,           /* Finder function name */
24786  nolockIoMethods,          /* sqlite3_io_methods object name */
24787  nolockClose,              /* xClose method */
24788  nolockLock,               /* xLock method */
24789  nolockUnlock,             /* xUnlock method */
24790  nolockCheckReservedLock   /* xCheckReservedLock method */
24791)
24792IOMETHODS(
24793  dotlockIoFinder,          /* Finder function name */
24794  dotlockIoMethods,         /* sqlite3_io_methods object name */
24795  dotlockClose,             /* xClose method */
24796  dotlockLock,              /* xLock method */
24797  dotlockUnlock,            /* xUnlock method */
24798  dotlockCheckReservedLock  /* xCheckReservedLock method */
24799)
24800
24801#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24802IOMETHODS(
24803  flockIoFinder,            /* Finder function name */
24804  flockIoMethods,           /* sqlite3_io_methods object name */
24805  flockClose,               /* xClose method */
24806  flockLock,                /* xLock method */
24807  flockUnlock,              /* xUnlock method */
24808  flockCheckReservedLock    /* xCheckReservedLock method */
24809)
24810#endif
24811
24812#if OS_VXWORKS
24813IOMETHODS(
24814  semIoFinder,              /* Finder function name */
24815  semIoMethods,             /* sqlite3_io_methods object name */
24816  semClose,                 /* xClose method */
24817  semLock,                  /* xLock method */
24818  semUnlock,                /* xUnlock method */
24819  semCheckReservedLock      /* xCheckReservedLock method */
24820)
24821#endif
24822
24823#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24824IOMETHODS(
24825  afpIoFinder,              /* Finder function name */
24826  afpIoMethods,             /* sqlite3_io_methods object name */
24827  afpClose,                 /* xClose method */
24828  afpLock,                  /* xLock method */
24829  afpUnlock,                /* xUnlock method */
24830  afpCheckReservedLock      /* xCheckReservedLock method */
24831)
24832#endif
24833
24834/*
24835** The "Whole File Locking" finder returns the same set of methods as
24836** the posix locking finder.  But it also sets the SQLITE_WHOLE_FILE_LOCKING
24837** flag to force the posix advisory locks to cover the whole file instead
24838** of just a small span of bytes near the 1GiB boundary.  Whole File Locking
24839** is useful on NFS-mounted files since it helps NFS to maintain cache
24840** coherency.  But it is a detriment to other filesystems since it runs
24841** slower.
24842*/
24843static const sqlite3_io_methods *posixWflIoFinderImpl(const char*z, unixFile*p){
24844  UNUSED_PARAMETER(z);
24845  p->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
24846  return &posixIoMethods;
24847}
24848static const sqlite3_io_methods
24849  *(*const posixWflIoFinder)(const char*,unixFile *p) = posixWflIoFinderImpl;
24850
24851/*
24852** The proxy locking method is a "super-method" in the sense that it
24853** opens secondary file descriptors for the conch and lock files and
24854** it uses proxy, dot-file, AFP, and flock() locking methods on those
24855** secondary files.  For this reason, the division that implements
24856** proxy locking is located much further down in the file.  But we need
24857** to go ahead and define the sqlite3_io_methods and finder function
24858** for proxy locking here.  So we forward declare the I/O methods.
24859*/
24860#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24861static int proxyClose(sqlite3_file*);
24862static int proxyLock(sqlite3_file*, int);
24863static int proxyUnlock(sqlite3_file*, int);
24864static int proxyCheckReservedLock(sqlite3_file*, int*);
24865IOMETHODS(
24866  proxyIoFinder,            /* Finder function name */
24867  proxyIoMethods,           /* sqlite3_io_methods object name */
24868  proxyClose,               /* xClose method */
24869  proxyLock,                /* xLock method */
24870  proxyUnlock,              /* xUnlock method */
24871  proxyCheckReservedLock    /* xCheckReservedLock method */
24872)
24873#endif
24874
24875
24876#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24877/*
24878** This "finder" function attempts to determine the best locking strategy
24879** for the database file "filePath".  It then returns the sqlite3_io_methods
24880** object that implements that strategy.
24881**
24882** This is for MacOSX only.
24883*/
24884static const sqlite3_io_methods *autolockIoFinderImpl(
24885  const char *filePath,    /* name of the database file */
24886  unixFile *pNew           /* open file object for the database file */
24887){
24888  static const struct Mapping {
24889    const char *zFilesystem;              /* Filesystem type name */
24890    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
24891  } aMap[] = {
24892    { "hfs",    &posixIoMethods },
24893    { "ufs",    &posixIoMethods },
24894    { "afpfs",  &afpIoMethods },
24895#ifdef SQLITE_ENABLE_AFP_LOCKING_SMB
24896    { "smbfs",  &afpIoMethods },
24897#else
24898    { "smbfs",  &flockIoMethods },
24899#endif
24900    { "webdav", &nolockIoMethods },
24901    { 0, 0 }
24902  };
24903  int i;
24904  struct statfs fsInfo;
24905  struct flock lockInfo;
24906
24907  if( !filePath ){
24908    /* If filePath==NULL that means we are dealing with a transient file
24909    ** that does not need to be locked. */
24910    return &nolockIoMethods;
24911  }
24912  if( statfs(filePath, &fsInfo) != -1 ){
24913    if( fsInfo.f_flags & MNT_RDONLY ){
24914      return &nolockIoMethods;
24915    }
24916    for(i=0; aMap[i].zFilesystem; i++){
24917      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
24918        return aMap[i].pMethods;
24919      }
24920    }
24921  }
24922
24923  /* Default case. Handles, amongst others, "nfs".
24924  ** Test byte-range lock using fcntl(). If the call succeeds,
24925  ** assume that the file-system supports POSIX style locks.
24926  */
24927  lockInfo.l_len = 1;
24928  lockInfo.l_start = 0;
24929  lockInfo.l_whence = SEEK_SET;
24930  lockInfo.l_type = F_RDLCK;
24931  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
24932    pNew->fileFlags = SQLITE_WHOLE_FILE_LOCKING;
24933    return &posixIoMethods;
24934  }else{
24935    return &dotlockIoMethods;
24936  }
24937}
24938static const sqlite3_io_methods
24939  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
24940
24941#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24942
24943#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
24944/*
24945** This "finder" function attempts to determine the best locking strategy
24946** for the database file "filePath".  It then returns the sqlite3_io_methods
24947** object that implements that strategy.
24948**
24949** This is for VXWorks only.
24950*/
24951static const sqlite3_io_methods *autolockIoFinderImpl(
24952  const char *filePath,    /* name of the database file */
24953  unixFile *pNew           /* the open file object */
24954){
24955  struct flock lockInfo;
24956
24957  if( !filePath ){
24958    /* If filePath==NULL that means we are dealing with a transient file
24959    ** that does not need to be locked. */
24960    return &nolockIoMethods;
24961  }
24962
24963  /* Test if fcntl() is supported and use POSIX style locks.
24964  ** Otherwise fall back to the named semaphore method.
24965  */
24966  lockInfo.l_len = 1;
24967  lockInfo.l_start = 0;
24968  lockInfo.l_whence = SEEK_SET;
24969  lockInfo.l_type = F_RDLCK;
24970  if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
24971    return &posixIoMethods;
24972  }else{
24973    return &semIoMethods;
24974  }
24975}
24976static const sqlite3_io_methods
24977  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
24978
24979#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
24980
24981/*
24982** An abstract type for a pointer to a IO method finder function:
24983*/
24984typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
24985
24986
24987/****************************************************************************
24988**************************** sqlite3_vfs methods ****************************
24989**
24990** This division contains the implementation of methods on the
24991** sqlite3_vfs object.
24992*/
24993
24994/*
24995** Initialize the contents of the unixFile structure pointed to by pId.
24996*/
24997static int fillInUnixFile(
24998  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
24999  int h,                  /* Open file descriptor of file being opened */
25000  int dirfd,              /* Directory file descriptor */
25001  sqlite3_file *pId,      /* Write to the unixFile structure here */
25002  const char *zFilename,  /* Name of the file being opened */
25003  int noLock,             /* Omit locking if true */
25004  int isDelete            /* Delete on close if true */
25005){
25006  const sqlite3_io_methods *pLockingStyle;
25007  unixFile *pNew = (unixFile *)pId;
25008  int rc = SQLITE_OK;
25009
25010  assert( pNew->pLock==NULL );
25011  assert( pNew->pOpen==NULL );
25012
25013  /* Parameter isDelete is only used on vxworks. Express this explicitly
25014  ** here to prevent compiler warnings about unused parameters.
25015  */
25016  UNUSED_PARAMETER(isDelete);
25017
25018  OSTRACE3("OPEN    %-3d %s\n", h, zFilename);
25019  pNew->h = h;
25020  pNew->dirfd = dirfd;
25021  SET_THREADID(pNew);
25022  pNew->fileFlags = 0;
25023
25024#if OS_VXWORKS
25025  pNew->pId = vxworksFindFileId(zFilename);
25026  if( pNew->pId==0 ){
25027    noLock = 1;
25028    rc = SQLITE_NOMEM;
25029  }
25030#endif
25031
25032  if( noLock ){
25033    pLockingStyle = &nolockIoMethods;
25034  }else{
25035    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
25036#if SQLITE_ENABLE_LOCKING_STYLE
25037    /* Cache zFilename in the locking context (AFP and dotlock override) for
25038    ** proxyLock activation is possible (remote proxy is based on db name)
25039    ** zFilename remains valid until file is closed, to support */
25040    pNew->lockingContext = (void*)zFilename;
25041#endif
25042  }
25043
25044  if( pLockingStyle == &posixIoMethods ){
25045    unixEnterMutex();
25046    rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25047    if( rc!=SQLITE_OK ){
25048      /* If an error occured in findLockInfo(), close the file descriptor
25049      ** immediately, before releasing the mutex. findLockInfo() may fail
25050      ** in two scenarios:
25051      **
25052      **   (a) A call to fstat() failed.
25053      **   (b) A malloc failed.
25054      **
25055      ** Scenario (b) may only occur if the process is holding no other
25056      ** file descriptors open on the same file. If there were other file
25057      ** descriptors on this file, then no malloc would be required by
25058      ** findLockInfo(). If this is the case, it is quite safe to close
25059      ** handle h - as it is guaranteed that no posix locks will be released
25060      ** by doing so.
25061      **
25062      ** If scenario (a) caused the error then things are not so safe. The
25063      ** implicit assumption here is that if fstat() fails, things are in
25064      ** such bad shape that dropping a lock or two doesn't matter much.
25065      */
25066      close(h);
25067      h = -1;
25068    }
25069    unixLeaveMutex();
25070  }
25071
25072#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25073  else if( pLockingStyle == &afpIoMethods ){
25074    /* AFP locking uses the file path so it needs to be included in
25075    ** the afpLockingContext.
25076    */
25077    afpLockingContext *pCtx;
25078    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
25079    if( pCtx==0 ){
25080      rc = SQLITE_NOMEM;
25081    }else{
25082      /* NB: zFilename exists and remains valid until the file is closed
25083      ** according to requirement F11141.  So we do not need to make a
25084      ** copy of the filename. */
25085      pCtx->dbPath = zFilename;
25086      srandomdev();
25087      unixEnterMutex();
25088      rc = findLockInfo(pNew, NULL, &pNew->pOpen);
25089      unixLeaveMutex();
25090    }
25091  }
25092#endif
25093
25094  else if( pLockingStyle == &dotlockIoMethods ){
25095    /* Dotfile locking uses the file path so it needs to be included in
25096    ** the dotlockLockingContext
25097    */
25098    char *zLockFile;
25099    int nFilename;
25100    nFilename = (int)strlen(zFilename) + 6;
25101    zLockFile = (char *)sqlite3_malloc(nFilename);
25102    if( zLockFile==0 ){
25103      rc = SQLITE_NOMEM;
25104    }else{
25105      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
25106    }
25107    pNew->lockingContext = zLockFile;
25108  }
25109
25110#if OS_VXWORKS
25111  else if( pLockingStyle == &semIoMethods ){
25112    /* Named semaphore locking uses the file path so it needs to be
25113    ** included in the semLockingContext
25114    */
25115    unixEnterMutex();
25116    rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25117    if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
25118      char *zSemName = pNew->pOpen->aSemName;
25119      int n;
25120      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
25121                       pNew->pId->zCanonicalName);
25122      for( n=1; zSemName[n]; n++ )
25123        if( zSemName[n]=='/' ) zSemName[n] = '_';
25124      pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
25125      if( pNew->pOpen->pSem == SEM_FAILED ){
25126        rc = SQLITE_NOMEM;
25127        pNew->pOpen->aSemName[0] = '\0';
25128      }
25129    }
25130    unixLeaveMutex();
25131  }
25132#endif
25133
25134  pNew->lastErrno = 0;
25135#if OS_VXWORKS
25136  if( rc!=SQLITE_OK ){
25137    unlink(zFilename);
25138    isDelete = 0;
25139  }
25140  pNew->isDelete = isDelete;
25141#endif
25142  if( rc!=SQLITE_OK ){
25143    if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
25144    if( h>=0 ) close(h);
25145  }else{
25146    pNew->pMethod = pLockingStyle;
25147    OpenCounter(+1);
25148  }
25149  return rc;
25150}
25151
25152/*
25153** Open a file descriptor to the directory containing file zFilename.
25154** If successful, *pFd is set to the opened file descriptor and
25155** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
25156** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
25157** value.
25158**
25159** If SQLITE_OK is returned, the caller is responsible for closing
25160** the file descriptor *pFd using close().
25161*/
25162static int openDirectory(const char *zFilename, int *pFd){
25163  int ii;
25164  int fd = -1;
25165  char zDirname[MAX_PATHNAME+1];
25166
25167  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
25168  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
25169  if( ii>0 ){
25170    zDirname[ii] = '\0';
25171    fd = open(zDirname, O_RDONLY|O_BINARY, 0);
25172    if( fd>=0 ){
25173#ifdef FD_CLOEXEC
25174      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25175#endif
25176      OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
25177    }
25178  }
25179  *pFd = fd;
25180  return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN);
25181}
25182
25183/*
25184** Create a temporary file name in zBuf.  zBuf must be allocated
25185** by the calling process and must be big enough to hold at least
25186** pVfs->mxPathname bytes.
25187*/
25188static int getTempname(int nBuf, char *zBuf){
25189  static const char *azDirs[] = {
25190     0,
25191     0,
25192     "/var/tmp",
25193     "/usr/tmp",
25194     "/tmp",
25195     ".",
25196  };
25197  static const unsigned char zChars[] =
25198    "abcdefghijklmnopqrstuvwxyz"
25199    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
25200    "0123456789";
25201  unsigned int i, j;
25202  struct stat buf;
25203  const char *zDir = ".";
25204
25205  /* It's odd to simulate an io-error here, but really this is just
25206  ** using the io-error infrastructure to test that SQLite handles this
25207  ** function failing.
25208  */
25209  SimulateIOError( return SQLITE_IOERR );
25210
25211  azDirs[0] = sqlite3_temp_directory;
25212  if (NULL == azDirs[1]) {
25213    azDirs[1] = getenv("TMPDIR");
25214  }
25215
25216  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
25217    if( azDirs[i]==0 ) continue;
25218    if( stat(azDirs[i], &buf) ) continue;
25219    if( !S_ISDIR(buf.st_mode) ) continue;
25220    if( access(azDirs[i], 07) ) continue;
25221    zDir = azDirs[i];
25222    break;
25223  }
25224
25225  /* Check that the output buffer is large enough for the temporary file
25226  ** name. If it is not, return SQLITE_ERROR.
25227  */
25228  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
25229    return SQLITE_ERROR;
25230  }
25231
25232  do{
25233    sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
25234    j = (int)strlen(zBuf);
25235    sqlite3_randomness(15, &zBuf[j]);
25236    for(i=0; i<15; i++, j++){
25237      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
25238    }
25239    zBuf[j] = 0;
25240  }while( access(zBuf,0)==0 );
25241  return SQLITE_OK;
25242}
25243
25244#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25245/*
25246** Routine to transform a unixFile into a proxy-locking unixFile.
25247** Implementation in the proxy-lock division, but used by unixOpen()
25248** if SQLITE_PREFER_PROXY_LOCKING is defined.
25249*/
25250static int proxyTransformUnixFile(unixFile*, const char*);
25251#endif
25252
25253/*
25254** Search for an unused file descriptor that was opened on the database
25255** file (not a journal or master-journal file) identified by pathname
25256** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
25257** argument to this function.
25258**
25259** Such a file descriptor may exist if a database connection was closed
25260** but the associated file descriptor could not be closed because some
25261** other file descriptor open on the same file is holding a file-lock.
25262** Refer to comments in the unixClose() function and the lengthy comment
25263** describing "Posix Advisory Locking" at the start of this file for
25264** further details. Also, ticket #4018.
25265**
25266** If a suitable file descriptor is found, then it is returned. If no
25267** such file descriptor is located, -1 is returned.
25268*/
25269static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
25270  UnixUnusedFd *pUnused = 0;
25271
25272  /* Do not search for an unused file descriptor on vxworks. Not because
25273  ** vxworks would not benefit from the change (it might, we're not sure),
25274  ** but because no way to test it is currently available. It is better
25275  ** not to risk breaking vxworks support for the sake of such an obscure
25276  ** feature.  */
25277#if !OS_VXWORKS
25278  struct stat sStat;                   /* Results of stat() call */
25279
25280  /* A stat() call may fail for various reasons. If this happens, it is
25281  ** almost certain that an open() call on the same path will also fail.
25282  ** For this reason, if an error occurs in the stat() call here, it is
25283  ** ignored and -1 is returned. The caller will try to open a new file
25284  ** descriptor on the same path, fail, and return an error to SQLite.
25285  **
25286  ** Even if a subsequent open() call does succeed, the consequences of
25287  ** not searching for a resusable file descriptor are not dire.  */
25288  if( 0==stat(zPath, &sStat) ){
25289    struct unixOpenCnt *pOpen;
25290
25291    unixEnterMutex();
25292    pOpen = openList;
25293    while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
25294                     || pOpen->fileId.ino!=sStat.st_ino) ){
25295       pOpen = pOpen->pNext;
25296    }
25297    if( pOpen ){
25298      UnixUnusedFd **pp;
25299      for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
25300      pUnused = *pp;
25301      if( pUnused ){
25302        *pp = pUnused->pNext;
25303      }
25304    }
25305    unixLeaveMutex();
25306  }
25307#endif    /* if !OS_VXWORKS */
25308  return pUnused;
25309}
25310
25311/*
25312** Open the file zPath.
25313**
25314** Previously, the SQLite OS layer used three functions in place of this
25315** one:
25316**
25317**     sqlite3OsOpenReadWrite();
25318**     sqlite3OsOpenReadOnly();
25319**     sqlite3OsOpenExclusive();
25320**
25321** These calls correspond to the following combinations of flags:
25322**
25323**     ReadWrite() ->     (READWRITE | CREATE)
25324**     ReadOnly()  ->     (READONLY)
25325**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
25326**
25327** The old OpenExclusive() accepted a boolean argument - "delFlag". If
25328** true, the file was configured to be automatically deleted when the
25329** file handle closed. To achieve the same effect using this new
25330** interface, add the DELETEONCLOSE flag to those specified above for
25331** OpenExclusive().
25332*/
25333static int unixOpen(
25334  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
25335  const char *zPath,           /* Pathname of file to be opened */
25336  sqlite3_file *pFile,         /* The file descriptor to be filled in */
25337  int flags,                   /* Input flags to control the opening */
25338  int *pOutFlags               /* Output flags returned to SQLite core */
25339){
25340  unixFile *p = (unixFile *)pFile;
25341  int fd = -1;                   /* File descriptor returned by open() */
25342  int dirfd = -1;                /* Directory file descriptor */
25343  int openFlags = 0;             /* Flags to pass to open() */
25344  int eType = flags&0xFFFFFF00;  /* Type of file to open */
25345  int noLock;                    /* True to omit locking primitives */
25346  int rc = SQLITE_OK;            /* Function Return Code */
25347
25348  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
25349  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
25350  int isCreate     = (flags & SQLITE_OPEN_CREATE);
25351  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
25352  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
25353
25354  /* If creating a master or main-file journal, this function will open
25355  ** a file-descriptor on the directory too. The first time unixSync()
25356  ** is called the directory file descriptor will be fsync()ed and close()d.
25357  */
25358  int isOpenDirectory = (isCreate &&
25359      (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
25360  );
25361
25362  /* If argument zPath is a NULL pointer, this function is required to open
25363  ** a temporary file. Use this buffer to store the file name in.
25364  */
25365  char zTmpname[MAX_PATHNAME+1];
25366  const char *zName = zPath;
25367
25368  /* Check the following statements are true:
25369  **
25370  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
25371  **   (b) if CREATE is set, then READWRITE must also be set, and
25372  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
25373  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
25374  */
25375  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
25376  assert(isCreate==0 || isReadWrite);
25377  assert(isExclusive==0 || isCreate);
25378  assert(isDelete==0 || isCreate);
25379
25380  /* The main DB, main journal, and master journal are never automatically
25381  ** deleted. Nor are they ever temporary files.  */
25382  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
25383  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
25384  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
25385
25386  /* Assert that the upper layer has set one of the "file-type" flags. */
25387  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
25388       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
25389       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
25390       || eType==SQLITE_OPEN_TRANSIENT_DB
25391  );
25392
25393  memset(p, 0, sizeof(unixFile));
25394
25395  if( eType==SQLITE_OPEN_MAIN_DB ){
25396    UnixUnusedFd *pUnused;
25397    pUnused = findReusableFd(zName, flags);
25398    if( pUnused ){
25399      fd = pUnused->fd;
25400    }else{
25401      pUnused = sqlite3_malloc(sizeof(*pUnused));
25402      if( !pUnused ){
25403        return SQLITE_NOMEM;
25404      }
25405    }
25406    p->pUnused = pUnused;
25407  }else if( !zName ){
25408    /* If zName is NULL, the upper layer is requesting a temp file. */
25409    assert(isDelete && !isOpenDirectory);
25410    rc = getTempname(MAX_PATHNAME+1, zTmpname);
25411    if( rc!=SQLITE_OK ){
25412      return rc;
25413    }
25414    zName = zTmpname;
25415  }
25416
25417  /* Determine the value of the flags parameter passed to POSIX function
25418  ** open(). These must be calculated even if open() is not called, as
25419  ** they may be stored as part of the file handle and used by the
25420  ** 'conch file' locking functions later on.  */
25421  if( isReadonly )  openFlags |= O_RDONLY;
25422  if( isReadWrite ) openFlags |= O_RDWR;
25423  if( isCreate )    openFlags |= O_CREAT;
25424  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
25425  openFlags |= (O_LARGEFILE|O_BINARY);
25426
25427  if( fd<0 ){
25428    mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
25429    fd = open(zName, openFlags, openMode);
25430    OSTRACE4("OPENX   %-3d %s 0%o\n", fd, zName, openFlags);
25431    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
25432      /* Failed to open the file for read/write access. Try read-only. */
25433      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
25434      openFlags &= ~(O_RDWR|O_CREAT);
25435      flags |= SQLITE_OPEN_READONLY;
25436      openFlags |= O_RDONLY;
25437      fd = open(zName, openFlags, openMode);
25438    }
25439    if( fd<0 ){
25440      rc = SQLITE_CANTOPEN;
25441      goto open_finished;
25442    }
25443  }
25444  assert( fd>=0 );
25445  if( pOutFlags ){
25446    *pOutFlags = flags;
25447  }
25448
25449  if( p->pUnused ){
25450    p->pUnused->fd = fd;
25451    p->pUnused->flags = flags;
25452  }
25453
25454  if( isDelete ){
25455#if OS_VXWORKS
25456    zPath = zName;
25457#else
25458    unlink(zName);
25459#endif
25460  }
25461#if SQLITE_ENABLE_LOCKING_STYLE
25462  else{
25463    p->openFlags = openFlags;
25464  }
25465#endif
25466
25467  if( isOpenDirectory ){
25468    rc = openDirectory(zPath, &dirfd);
25469    if( rc!=SQLITE_OK ){
25470      /* It is safe to close fd at this point, because it is guaranteed not
25471      ** to be open on a database file. If it were open on a database file,
25472      ** it would not be safe to close as this would release any locks held
25473      ** on the file by this process.  */
25474      assert( eType!=SQLITE_OPEN_MAIN_DB );
25475      close(fd);             /* silently leak if fail, already in error */
25476      goto open_finished;
25477    }
25478  }
25479
25480#ifdef FD_CLOEXEC
25481  fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25482#endif
25483
25484  noLock = eType!=SQLITE_OPEN_MAIN_DB;
25485
25486#if SQLITE_PREFER_PROXY_LOCKING
25487  if( zPath!=NULL && !noLock && pVfs->xOpen ){
25488    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
25489    int useProxy = 0;
25490
25491    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
25492    ** never use proxy, NULL means use proxy for non-local files only.  */
25493    if( envforce!=NULL ){
25494      useProxy = atoi(envforce)>0;
25495    }else{
25496      struct statfs fsInfo;
25497      if( statfs(zPath, &fsInfo) == -1 ){
25498        /* In theory, the close(fd) call is sub-optimal. If the file opened
25499        ** with fd is a database file, and there are other connections open
25500        ** on that file that are currently holding advisory locks on it,
25501        ** then the call to close() will cancel those locks. In practice,
25502        ** we're assuming that statfs() doesn't fail very often. At least
25503        ** not while other file descriptors opened by the same process on
25504        ** the same file are working.  */
25505        p->lastErrno = errno;
25506        if( dirfd>=0 ){
25507          close(dirfd); /* silently leak if fail, in error */
25508        }
25509        close(fd); /* silently leak if fail, in error */
25510        rc = SQLITE_IOERR_ACCESS;
25511        goto open_finished;
25512      }
25513      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
25514    }
25515    if( useProxy ){
25516      rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
25517      if( rc==SQLITE_OK ){
25518        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
25519      }
25520      goto open_finished;
25521    }
25522  }
25523#endif
25524
25525  rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
25526open_finished:
25527  if( rc!=SQLITE_OK ){
25528    sqlite3_free(p->pUnused);
25529  }
25530  return rc;
25531}
25532
25533
25534/*
25535** Delete the file at zPath. If the dirSync argument is true, fsync()
25536** the directory after deleting the file.
25537*/
25538static int unixDelete(
25539  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
25540  const char *zPath,        /* Name of file to be deleted */
25541  int dirSync               /* If true, fsync() directory after deleting file */
25542){
25543  int rc = SQLITE_OK;
25544  UNUSED_PARAMETER(NotUsed);
25545  SimulateIOError(return SQLITE_IOERR_DELETE);
25546  unlink(zPath);
25547#ifndef SQLITE_DISABLE_DIRSYNC
25548  if( dirSync ){
25549    int fd;
25550    rc = openDirectory(zPath, &fd);
25551    if( rc==SQLITE_OK ){
25552#if OS_VXWORKS
25553      if( fsync(fd)==-1 )
25554#else
25555      if( fsync(fd) )
25556#endif
25557      {
25558        rc = SQLITE_IOERR_DIR_FSYNC;
25559      }
25560      if( close(fd)&&!rc ){
25561        rc = SQLITE_IOERR_DIR_CLOSE;
25562      }
25563    }
25564  }
25565#endif
25566  return rc;
25567}
25568
25569/*
25570** Test the existance of or access permissions of file zPath. The
25571** test performed depends on the value of flags:
25572**
25573**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
25574**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
25575**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
25576**
25577** Otherwise return 0.
25578*/
25579static int unixAccess(
25580  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
25581  const char *zPath,      /* Path of the file to examine */
25582  int flags,              /* What do we want to learn about the zPath file? */
25583  int *pResOut            /* Write result boolean here */
25584){
25585  int amode = 0;
25586  UNUSED_PARAMETER(NotUsed);
25587  SimulateIOError( return SQLITE_IOERR_ACCESS; );
25588  switch( flags ){
25589    case SQLITE_ACCESS_EXISTS:
25590      amode = F_OK;
25591      break;
25592    case SQLITE_ACCESS_READWRITE:
25593      amode = W_OK|R_OK;
25594      break;
25595    case SQLITE_ACCESS_READ:
25596      amode = R_OK;
25597      break;
25598
25599    default:
25600      assert(!"Invalid flags argument");
25601  }
25602  *pResOut = (access(zPath, amode)==0);
25603  return SQLITE_OK;
25604}
25605
25606
25607/*
25608** Turn a relative pathname into a full pathname. The relative path
25609** is stored as a nul-terminated string in the buffer pointed to by
25610** zPath.
25611**
25612** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
25613** (in this case, MAX_PATHNAME bytes). The full-path is written to
25614** this buffer before returning.
25615*/
25616static int unixFullPathname(
25617  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
25618  const char *zPath,            /* Possibly relative input path */
25619  int nOut,                     /* Size of output buffer in bytes */
25620  char *zOut                    /* Output buffer */
25621){
25622
25623  /* It's odd to simulate an io-error here, but really this is just
25624  ** using the io-error infrastructure to test that SQLite handles this
25625  ** function failing. This function could fail if, for example, the
25626  ** current working directory has been unlinked.
25627  */
25628  SimulateIOError( return SQLITE_ERROR );
25629
25630  assert( pVfs->mxPathname==MAX_PATHNAME );
25631  UNUSED_PARAMETER(pVfs);
25632
25633  zOut[nOut-1] = '\0';
25634  if( zPath[0]=='/' ){
25635    sqlite3_snprintf(nOut, zOut, "%s", zPath);
25636  }else{
25637    int nCwd;
25638    if( getcwd(zOut, nOut-1)==0 ){
25639      return SQLITE_CANTOPEN;
25640    }
25641    nCwd = (int)strlen(zOut);
25642    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
25643  }
25644  return SQLITE_OK;
25645}
25646
25647
25648#ifndef SQLITE_OMIT_LOAD_EXTENSION
25649/*
25650** Interfaces for opening a shared library, finding entry points
25651** within the shared library, and closing the shared library.
25652*/
25653#include <dlfcn.h>
25654static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
25655  UNUSED_PARAMETER(NotUsed);
25656  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
25657}
25658
25659/*
25660** SQLite calls this function immediately after a call to unixDlSym() or
25661** unixDlOpen() fails (returns a null pointer). If a more detailed error
25662** message is available, it is written to zBufOut. If no error message
25663** is available, zBufOut is left unmodified and SQLite uses a default
25664** error message.
25665*/
25666static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
25667  char *zErr;
25668  UNUSED_PARAMETER(NotUsed);
25669  unixEnterMutex();
25670  zErr = dlerror();
25671  if( zErr ){
25672    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
25673  }
25674  unixLeaveMutex();
25675}
25676static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
25677  /*
25678  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
25679  ** cast into a pointer to a function.  And yet the library dlsym() routine
25680  ** returns a void* which is really a pointer to a function.  So how do we
25681  ** use dlsym() with -pedantic-errors?
25682  **
25683  ** Variable x below is defined to be a pointer to a function taking
25684  ** parameters void* and const char* and returning a pointer to a function.
25685  ** We initialize x by assigning it a pointer to the dlsym() function.
25686  ** (That assignment requires a cast.)  Then we call the function that
25687  ** x points to.
25688  **
25689  ** This work-around is unlikely to work correctly on any system where
25690  ** you really cannot cast a function pointer into void*.  But then, on the
25691  ** other hand, dlsym() will not work on such a system either, so we have
25692  ** not really lost anything.
25693  */
25694  void (*(*x)(void*,const char*))(void);
25695  UNUSED_PARAMETER(NotUsed);
25696  x = (void(*(*)(void*,const char*))(void))dlsym;
25697  return (*x)(p, zSym);
25698}
25699static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
25700  UNUSED_PARAMETER(NotUsed);
25701  dlclose(pHandle);
25702}
25703#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
25704  #define unixDlOpen  0
25705  #define unixDlError 0
25706  #define unixDlSym   0
25707  #define unixDlClose 0
25708#endif
25709
25710/*
25711** Write nBuf bytes of random data to the supplied buffer zBuf.
25712*/
25713static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
25714  UNUSED_PARAMETER(NotUsed);
25715  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
25716
25717  /* We have to initialize zBuf to prevent valgrind from reporting
25718  ** errors.  The reports issued by valgrind are incorrect - we would
25719  ** prefer that the randomness be increased by making use of the
25720  ** uninitialized space in zBuf - but valgrind errors tend to worry
25721  ** some users.  Rather than argue, it seems easier just to initialize
25722  ** the whole array and silence valgrind, even if that means less randomness
25723  ** in the random seed.
25724  **
25725  ** When testing, initializing zBuf[] to zero is all we do.  That means
25726  ** that we always use the same random number sequence.  This makes the
25727  ** tests repeatable.
25728  */
25729  memset(zBuf, 0, nBuf);
25730#if !defined(SQLITE_TEST)
25731  {
25732    int pid, fd;
25733    fd = open("/dev/urandom", O_RDONLY);
25734    if( fd<0 ){
25735      time_t t;
25736      time(&t);
25737      memcpy(zBuf, &t, sizeof(t));
25738      pid = getpid();
25739      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
25740      assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
25741      nBuf = sizeof(t) + sizeof(pid);
25742    }else{
25743      nBuf = read(fd, zBuf, nBuf);
25744      close(fd);
25745    }
25746  }
25747#endif
25748  return nBuf;
25749}
25750
25751
25752/*
25753** Sleep for a little while.  Return the amount of time slept.
25754** The argument is the number of microseconds we want to sleep.
25755** The return value is the number of microseconds of sleep actually
25756** requested from the underlying operating system, a number which
25757** might be greater than or equal to the argument, but not less
25758** than the argument.
25759*/
25760static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
25761#if OS_VXWORKS
25762  struct timespec sp;
25763
25764  sp.tv_sec = microseconds / 1000000;
25765  sp.tv_nsec = (microseconds % 1000000) * 1000;
25766  nanosleep(&sp, NULL);
25767  UNUSED_PARAMETER(NotUsed);
25768  return microseconds;
25769#elif defined(HAVE_USLEEP) && HAVE_USLEEP
25770  usleep(microseconds);
25771  UNUSED_PARAMETER(NotUsed);
25772  return microseconds;
25773#else
25774  int seconds = (microseconds+999999)/1000000;
25775  sleep(seconds);
25776  UNUSED_PARAMETER(NotUsed);
25777  return seconds*1000000;
25778#endif
25779}
25780
25781/*
25782** The following variable, if set to a non-zero value, is interpreted as
25783** the number of seconds since 1970 and is used to set the result of
25784** sqlite3OsCurrentTime() during testing.
25785*/
25786#ifdef SQLITE_TEST
25787SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
25788#endif
25789
25790/*
25791** Find the current time (in Universal Coordinated Time).  Write the
25792** current time and date as a Julian Day number into *prNow and
25793** return 0.  Return 1 if the time and date cannot be found.
25794*/
25795static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
25796#if defined(SQLITE_OMIT_FLOATING_POINT)
25797  time_t t;
25798  time(&t);
25799  *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
25800#elif defined(NO_GETTOD)
25801  time_t t;
25802  time(&t);
25803  *prNow = t/86400.0 + 2440587.5;
25804#elif OS_VXWORKS
25805  struct timespec sNow;
25806  clock_gettime(CLOCK_REALTIME, &sNow);
25807  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
25808#else
25809  struct timeval sNow;
25810  gettimeofday(&sNow, 0);
25811  *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
25812#endif
25813
25814#ifdef SQLITE_TEST
25815  if( sqlite3_current_time ){
25816    *prNow = sqlite3_current_time/86400.0 + 2440587.5;
25817  }
25818#endif
25819  UNUSED_PARAMETER(NotUsed);
25820  return 0;
25821}
25822
25823/*
25824** We added the xGetLastError() method with the intention of providing
25825** better low-level error messages when operating-system problems come up
25826** during SQLite operation.  But so far, none of that has been implemented
25827** in the core.  So this routine is never called.  For now, it is merely
25828** a place-holder.
25829*/
25830static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
25831  UNUSED_PARAMETER(NotUsed);
25832  UNUSED_PARAMETER(NotUsed2);
25833  UNUSED_PARAMETER(NotUsed3);
25834  return 0;
25835}
25836
25837/*
25838************************ End of sqlite3_vfs methods ***************************
25839******************************************************************************/
25840
25841/******************************************************************************
25842************************** Begin Proxy Locking ********************************
25843**
25844** Proxy locking is a "uber-locking-method" in this sense:  It uses the
25845** other locking methods on secondary lock files.  Proxy locking is a
25846** meta-layer over top of the primitive locking implemented above.  For
25847** this reason, the division that implements of proxy locking is deferred
25848** until late in the file (here) after all of the other I/O methods have
25849** been defined - so that the primitive locking methods are available
25850** as services to help with the implementation of proxy locking.
25851**
25852****
25853**
25854** The default locking schemes in SQLite use byte-range locks on the
25855** database file to coordinate safe, concurrent access by multiple readers
25856** and writers [http://sqlite.org/lockingv3.html].  The five file locking
25857** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
25858** as POSIX read & write locks over fixed set of locations (via fsctl),
25859** on AFP and SMB only exclusive byte-range locks are available via fsctl
25860** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
25861** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
25862** address in the shared range is taken for a SHARED lock, the entire
25863** shared range is taken for an EXCLUSIVE lock):
25864**
25865**      PENDING_BYTE        0x40000000
25866**      RESERVED_BYTE       0x40000001
25867**      SHARED_RANGE        0x40000002 -> 0x40000200
25868**
25869** This works well on the local file system, but shows a nearly 100x
25870** slowdown in read performance on AFP because the AFP client disables
25871** the read cache when byte-range locks are present.  Enabling the read
25872** cache exposes a cache coherency problem that is present on all OS X
25873** supported network file systems.  NFS and AFP both observe the
25874** close-to-open semantics for ensuring cache coherency
25875** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
25876** address the requirements for concurrent database access by multiple
25877** readers and writers
25878** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
25879**
25880** To address the performance and cache coherency issues, proxy file locking
25881** changes the way database access is controlled by limiting access to a
25882** single host at a time and moving file locks off of the database file
25883** and onto a proxy file on the local file system.
25884**
25885**
25886** Using proxy locks
25887** -----------------
25888**
25889** C APIs
25890**
25891**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
25892**                       <proxy_path> | ":auto:");
25893**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
25894**
25895**
25896** SQL pragmas
25897**
25898**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
25899**  PRAGMA [database.]lock_proxy_file
25900**
25901** Specifying ":auto:" means that if there is a conch file with a matching
25902** host ID in it, the proxy path in the conch file will be used, otherwise
25903** a proxy path based on the user's temp dir
25904** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
25905** actual proxy file name is generated from the name and path of the
25906** database file.  For example:
25907**
25908**       For database path "/Users/me/foo.db"
25909**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
25910**
25911** Once a lock proxy is configured for a database connection, it can not
25912** be removed, however it may be switched to a different proxy path via
25913** the above APIs (assuming the conch file is not being held by another
25914** connection or process).
25915**
25916**
25917** How proxy locking works
25918** -----------------------
25919**
25920** Proxy file locking relies primarily on two new supporting files:
25921**
25922**   *  conch file to limit access to the database file to a single host
25923**      at a time
25924**
25925**   *  proxy file to act as a proxy for the advisory locks normally
25926**      taken on the database
25927**
25928** The conch file - to use a proxy file, sqlite must first "hold the conch"
25929** by taking an sqlite-style shared lock on the conch file, reading the
25930** contents and comparing the host's unique host ID (see below) and lock
25931** proxy path against the values stored in the conch.  The conch file is
25932** stored in the same directory as the database file and the file name
25933** is patterned after the database file name as ".<databasename>-conch".
25934** If the conch file does not exist, or it's contents do not match the
25935** host ID and/or proxy path, then the lock is escalated to an exclusive
25936** lock and the conch file contents is updated with the host ID and proxy
25937** path and the lock is downgraded to a shared lock again.  If the conch
25938** is held by another process (with a shared lock), the exclusive lock
25939** will fail and SQLITE_BUSY is returned.
25940**
25941** The proxy file - a single-byte file used for all advisory file locks
25942** normally taken on the database file.   This allows for safe sharing
25943** of the database file for multiple readers and writers on the same
25944** host (the conch ensures that they all use the same local lock file).
25945**
25946** There is a third file - the host ID file - used as a persistent record
25947** of a unique identifier for the host, a 128-byte unique host id file
25948** in the path defined by the HOSTIDPATH macro (default value is
25949** /Library/Caches/.com.apple.sqliteConchHostId).
25950**
25951** Requesting the lock proxy does not immediately take the conch, it is
25952** only taken when the first request to lock database file is made.
25953** This matches the semantics of the traditional locking behavior, where
25954** opening a connection to a database file does not take a lock on it.
25955** The shared lock and an open file descriptor are maintained until
25956** the connection to the database is closed.
25957**
25958** The proxy file and the lock file are never deleted so they only need
25959** to be created the first time they are used.
25960**
25961** Configuration options
25962** ---------------------
25963**
25964**  SQLITE_PREFER_PROXY_LOCKING
25965**
25966**       Database files accessed on non-local file systems are
25967**       automatically configured for proxy locking, lock files are
25968**       named automatically using the same logic as
25969**       PRAGMA lock_proxy_file=":auto:"
25970**
25971**  SQLITE_PROXY_DEBUG
25972**
25973**       Enables the logging of error messages during host id file
25974**       retrieval and creation
25975**
25976**  HOSTIDPATH
25977**
25978**       Overrides the default host ID file path location
25979**
25980**  LOCKPROXYDIR
25981**
25982**       Overrides the default directory used for lock proxy files that
25983**       are named automatically via the ":auto:" setting
25984**
25985**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
25986**
25987**       Permissions to use when creating a directory for storing the
25988**       lock proxy files, only used when LOCKPROXYDIR is not set.
25989**
25990**
25991** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
25992** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
25993** force proxy locking to be used for every database file opened, and 0
25994** will force automatic proxy locking to be disabled for all database
25995** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
25996** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
25997*/
25998
25999/*
26000** Proxy locking is only available on MacOSX
26001*/
26002#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26003
26004#ifdef SQLITE_TEST
26005/* simulate multiple hosts by creating unique hostid file paths */
26006SQLITE_API int sqlite3_hostid_num = 0;
26007#endif
26008
26009/*
26010** The proxyLockingContext has the path and file structures for the remote
26011** and local proxy files in it
26012*/
26013typedef struct proxyLockingContext proxyLockingContext;
26014struct proxyLockingContext {
26015  unixFile *conchFile;         /* Open conch file */
26016  char *conchFilePath;         /* Name of the conch file */
26017  unixFile *lockProxy;         /* Open proxy lock file */
26018  char *lockProxyPath;         /* Name of the proxy lock file */
26019  char *dbPath;                /* Name of the open file */
26020  int conchHeld;               /* True if the conch is currently held */
26021  void *oldLockingContext;     /* Original lockingcontext to restore on close */
26022  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
26023};
26024
26025/* HOSTIDLEN and CONCHLEN both include space for the string
26026** terminating nul
26027*/
26028#define HOSTIDLEN         128
26029#define CONCHLEN          (MAXPATHLEN+HOSTIDLEN+1)
26030#ifndef HOSTIDPATH
26031# define HOSTIDPATH       "/Library/Caches/.com.apple.sqliteConchHostId"
26032#endif
26033
26034/* basically a copy of unixRandomness with different
26035** test behavior built in */
26036static int proxyGenerateHostID(char *pHostID){
26037  int pid, fd, len;
26038  unsigned char *key = (unsigned char *)pHostID;
26039
26040  memset(key, 0, HOSTIDLEN);
26041  len = 0;
26042  fd = open("/dev/urandom", O_RDONLY);
26043  if( fd>=0 ){
26044    len = read(fd, key, HOSTIDLEN);
26045    close(fd); /* silently leak the fd if it fails */
26046  }
26047  if( len < HOSTIDLEN ){
26048    time_t t;
26049    time(&t);
26050    memcpy(key, &t, sizeof(t));
26051    pid = getpid();
26052    memcpy(&key[sizeof(t)], &pid, sizeof(pid));
26053  }
26054
26055#ifdef MAKE_PRETTY_HOSTID
26056  {
26057    int i;
26058    /* filter the bytes into printable ascii characters and NUL terminate */
26059    key[(HOSTIDLEN-1)] = 0x00;
26060    for( i=0; i<(HOSTIDLEN-1); i++ ){
26061      unsigned char pa = key[i]&0x7F;
26062      if( pa<0x20 ){
26063        key[i] = (key[i]&0x80 == 0x80) ? pa+0x40 : pa+0x20;
26064      }else if( pa==0x7F ){
26065        key[i] = (key[i]&0x80 == 0x80) ? pa=0x20 : pa+0x7E;
26066      }
26067    }
26068  }
26069#endif
26070  return SQLITE_OK;
26071}
26072
26073/* writes the host id path to path, path should be an pre-allocated buffer
26074** with enough space for a path
26075*/
26076static void proxyGetHostIDPath(char *path, size_t len){
26077  strlcpy(path, HOSTIDPATH, len);
26078#ifdef SQLITE_TEST
26079  if( sqlite3_hostid_num>0 ){
26080    char suffix[2] = "1";
26081    suffix[0] = suffix[0] + sqlite3_hostid_num;
26082    strlcat(path, suffix, len);
26083  }
26084#endif
26085  OSTRACE3("GETHOSTIDPATH  %s pid=%d\n", path, getpid());
26086}
26087
26088/* get the host ID from a sqlite hostid file stored in the
26089** user-specific tmp directory, create the ID if it's not there already
26090*/
26091static int proxyGetHostID(char *pHostID, int *pError){
26092  int fd;
26093  char path[MAXPATHLEN];
26094  size_t len;
26095  int rc=SQLITE_OK;
26096
26097  proxyGetHostIDPath(path, MAXPATHLEN);
26098  /* try to create the host ID file, if it already exists read the contents */
26099  fd = open(path, O_CREAT|O_WRONLY|O_EXCL, 0644);
26100  if( fd<0 ){
26101    int err=errno;
26102
26103    if( err!=EEXIST ){
26104#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
26105      fprintf(stderr, "sqlite error creating host ID file %s: %s\n",
26106              path, strerror(err));
26107#endif
26108      return SQLITE_PERM;
26109    }
26110    /* couldn't create the file, read it instead */
26111    fd = open(path, O_RDONLY|O_EXCL);
26112    if( fd<0 ){
26113#ifdef SQLITE_PROXY_DEBUG /* set the sqlite error message instead */
26114      int err = errno;
26115      fprintf(stderr, "sqlite error opening host ID file %s: %s\n",
26116              path, strerror(err));
26117#endif
26118      return SQLITE_PERM;
26119    }
26120    len = pread(fd, pHostID, HOSTIDLEN, 0);
26121    if( len<0 ){
26122      *pError = errno;
26123      rc = SQLITE_IOERR_READ;
26124    }else if( len<HOSTIDLEN ){
26125      *pError = 0;
26126      rc = SQLITE_IOERR_SHORT_READ;
26127    }
26128    close(fd); /* silently leak the fd if it fails */
26129    OSTRACE3("GETHOSTID  read %s pid=%d\n", pHostID, getpid());
26130    return rc;
26131  }else{
26132    /* we're creating the host ID file (use a random string of bytes) */
26133    proxyGenerateHostID(pHostID);
26134    len = pwrite(fd, pHostID, HOSTIDLEN, 0);
26135    if( len<0 ){
26136      *pError = errno;
26137      rc = SQLITE_IOERR_WRITE;
26138    }else if( len<HOSTIDLEN ){
26139      *pError = 0;
26140      rc = SQLITE_IOERR_WRITE;
26141    }
26142    close(fd); /* silently leak the fd if it fails */
26143    OSTRACE3("GETHOSTID  wrote %s pid=%d\n", pHostID, getpid());
26144    return rc;
26145  }
26146}
26147
26148static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
26149  int len;
26150  int dbLen;
26151  int i;
26152
26153#ifdef LOCKPROXYDIR
26154  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
26155#else
26156# ifdef _CS_DARWIN_USER_TEMP_DIR
26157  {
26158    confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen);
26159    len = strlcat(lPath, "sqliteplocks", maxLen);
26160    if( mkdir(lPath, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
26161      /* if mkdir fails, handle as lock file creation failure */
26162#  ifdef SQLITE_DEBUG
26163      int err = errno;
26164      if( err!=EEXIST ){
26165        fprintf(stderr, "proxyGetLockPath: mkdir(%s,0%o) error %d %s\n", lPath,
26166                SQLITE_DEFAULT_PROXYDIR_PERMISSIONS, err, strerror(err));
26167      }
26168#  endif
26169    }else{
26170      OSTRACE3("GETLOCKPATH  mkdir %s pid=%d\n", lPath, getpid());
26171    }
26172
26173  }
26174# else
26175  len = strlcpy(lPath, "/tmp/", maxLen);
26176# endif
26177#endif
26178
26179  if( lPath[len-1]!='/' ){
26180    len = strlcat(lPath, "/", maxLen);
26181  }
26182
26183  /* transform the db path to a unique cache name */
26184  dbLen = (int)strlen(dbPath);
26185  for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
26186    char c = dbPath[i];
26187    lPath[i+len] = (c=='/')?'_':c;
26188  }
26189  lPath[i+len]='\0';
26190  strlcat(lPath, ":auto:", maxLen);
26191  return SQLITE_OK;
26192}
26193
26194/*
26195** Create a new VFS file descriptor (stored in memory obtained from
26196** sqlite3_malloc) and open the file named "path" in the file descriptor.
26197**
26198** The caller is responsible not only for closing the file descriptor
26199** but also for freeing the memory associated with the file descriptor.
26200*/
26201static int proxyCreateUnixFile(const char *path, unixFile **ppFile) {
26202  unixFile *pNew;
26203  int flags = SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
26204  int rc = SQLITE_OK;
26205  sqlite3_vfs dummyVfs;
26206
26207  pNew = (unixFile *)sqlite3_malloc(sizeof(unixFile));
26208  if( !pNew ){
26209    return SQLITE_NOMEM;
26210  }
26211  memset(pNew, 0, sizeof(unixFile));
26212
26213  /* Call unixOpen() to open the proxy file. The flags passed to unixOpen()
26214  ** suggest that the file being opened is a "main database". This is
26215  ** necessary as other file types do not necessarily support locking. It
26216  ** is better to use unixOpen() instead of opening the file directly with
26217  ** open(), as unixOpen() sets up the various mechanisms required to
26218  ** make sure a call to close() does not cause the system to discard
26219  ** POSIX locks prematurely.
26220  **
26221  ** It is important that the xOpen member of the VFS object passed to
26222  ** unixOpen() is NULL. This tells unixOpen() may try to open a proxy-file
26223  ** for the proxy-file (creating a potential infinite loop).
26224  */
26225  dummyVfs.pAppData = (void*)&autolockIoFinder;
26226  dummyVfs.xOpen = 0;
26227  rc = unixOpen(&dummyVfs, path, (sqlite3_file *)pNew, flags, &flags);
26228  if( rc==SQLITE_OK && (flags&SQLITE_OPEN_READONLY) ){
26229    pNew->pMethod->xClose((sqlite3_file *)pNew);
26230    rc = SQLITE_CANTOPEN;
26231  }
26232
26233  if( rc!=SQLITE_OK ){
26234    sqlite3_free(pNew);
26235    pNew = 0;
26236  }
26237
26238  *ppFile = pNew;
26239  return rc;
26240}
26241
26242/* takes the conch by taking a shared lock and read the contents conch, if
26243** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
26244** lockPath means that the lockPath in the conch file will be used if the
26245** host IDs match, or a new lock path will be generated automatically
26246** and written to the conch file.
26247*/
26248static int proxyTakeConch(unixFile *pFile){
26249  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26250
26251  if( pCtx->conchHeld>0 ){
26252    return SQLITE_OK;
26253  }else{
26254    unixFile *conchFile = pCtx->conchFile;
26255    char testValue[CONCHLEN];
26256    char conchValue[CONCHLEN];
26257    char lockPath[MAXPATHLEN];
26258    char *tLockPath = NULL;
26259    int rc = SQLITE_OK;
26260    int readRc = SQLITE_OK;
26261    int syncPerms = 0;
26262
26263    OSTRACE4("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
26264             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
26265
26266    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
26267    if( rc==SQLITE_OK ){
26268      int pError = 0;
26269      memset(testValue, 0, CONCHLEN); /* conch is fixed size */
26270      rc = proxyGetHostID(testValue, &pError);
26271      if( (rc&0xff)==SQLITE_IOERR ){
26272        pFile->lastErrno = pError;
26273      }
26274      if( pCtx->lockProxyPath ){
26275        strlcpy(&testValue[HOSTIDLEN], pCtx->lockProxyPath, MAXPATHLEN);
26276      }
26277    }
26278    if( rc!=SQLITE_OK ){
26279      goto end_takeconch;
26280    }
26281
26282    readRc = unixRead((sqlite3_file *)conchFile, conchValue, CONCHLEN, 0);
26283    if( readRc!=SQLITE_IOERR_SHORT_READ ){
26284      if( readRc!=SQLITE_OK ){
26285        if( (rc&0xff)==SQLITE_IOERR ){
26286          pFile->lastErrno = conchFile->lastErrno;
26287        }
26288        rc = readRc;
26289        goto end_takeconch;
26290      }
26291      /* if the conch has data compare the contents */
26292      if( !pCtx->lockProxyPath ){
26293        /* for auto-named local lock file, just check the host ID and we'll
26294         ** use the local lock file path that's already in there */
26295        if( !memcmp(testValue, conchValue, HOSTIDLEN) ){
26296          tLockPath = (char *)&conchValue[HOSTIDLEN];
26297          goto end_takeconch;
26298        }
26299      }else{
26300        /* we've got the conch if conchValue matches our path and host ID */
26301        if( !memcmp(testValue, conchValue, CONCHLEN) ){
26302          goto end_takeconch;
26303        }
26304      }
26305    }else{
26306      /* a short read means we're "creating" the conch (even though it could
26307      ** have been user-intervention), if we acquire the exclusive lock,
26308      ** we'll try to match the current on-disk permissions of the database
26309      */
26310      syncPerms = 1;
26311    }
26312
26313    /* either conch was emtpy or didn't match */
26314    if( !pCtx->lockProxyPath ){
26315      proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
26316      tLockPath = lockPath;
26317      strlcpy(&testValue[HOSTIDLEN], lockPath, MAXPATHLEN);
26318    }
26319
26320    /* update conch with host and path (this will fail if other process
26321     ** has a shared lock already) */
26322    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
26323    if( rc==SQLITE_OK ){
26324      rc = unixWrite((sqlite3_file *)conchFile, testValue, CONCHLEN, 0);
26325      if( rc==SQLITE_OK && syncPerms ){
26326        struct stat buf;
26327        int err = fstat(pFile->h, &buf);
26328        if( err==0 ){
26329          /* try to match the database file permissions, ignore failure */
26330#ifndef SQLITE_PROXY_DEBUG
26331          fchmod(conchFile->h, buf.st_mode);
26332#else
26333          if( fchmod(conchFile->h, buf.st_mode)!=0 ){
26334            int code = errno;
26335            fprintf(stderr, "fchmod %o FAILED with %d %s\n",
26336                             buf.st_mode, code, strerror(code));
26337          } else {
26338            fprintf(stderr, "fchmod %o SUCCEDED\n",buf.st_mode);
26339          }
26340        }else{
26341          int code = errno;
26342          fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
26343                          err, code, strerror(code));
26344#endif
26345        }
26346      }
26347    }
26348    conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
26349
26350end_takeconch:
26351    OSTRACE2("TRANSPROXY: CLOSE  %d\n", pFile->h);
26352    if( rc==SQLITE_OK && pFile->openFlags ){
26353      if( pFile->h>=0 ){
26354#ifdef STRICT_CLOSE_ERROR
26355        if( close(pFile->h) ){
26356          pFile->lastErrno = errno;
26357          return SQLITE_IOERR_CLOSE;
26358        }
26359#else
26360        close(pFile->h); /* silently leak fd if fail */
26361#endif
26362      }
26363      pFile->h = -1;
26364      int fd = open(pCtx->dbPath, pFile->openFlags,
26365                    SQLITE_DEFAULT_FILE_PERMISSIONS);
26366      OSTRACE2("TRANSPROXY: OPEN  %d\n", fd);
26367      if( fd>=0 ){
26368        pFile->h = fd;
26369      }else{
26370        rc=SQLITE_CANTOPEN; /* SQLITE_BUSY? proxyTakeConch called
26371                               during locking */
26372      }
26373    }
26374    if( rc==SQLITE_OK && !pCtx->lockProxy ){
26375      char *path = tLockPath ? tLockPath : pCtx->lockProxyPath;
26376      /* ACS: Need to make a copy of path sometimes */
26377      rc = proxyCreateUnixFile(path, &pCtx->lockProxy);
26378    }
26379    if( rc==SQLITE_OK ){
26380      pCtx->conchHeld = 1;
26381
26382      if( tLockPath ){
26383        pCtx->lockProxyPath = sqlite3DbStrDup(0, tLockPath);
26384        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
26385          ((afpLockingContext *)pCtx->lockProxy->lockingContext)->dbPath =
26386                     pCtx->lockProxyPath;
26387        }
26388      }
26389    } else {
26390      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26391    }
26392    OSTRACE3("TAKECONCH  %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
26393    return rc;
26394  }
26395}
26396
26397/*
26398** If pFile holds a lock on a conch file, then release that lock.
26399*/
26400static int proxyReleaseConch(unixFile *pFile){
26401  int rc;                     /* Subroutine return code */
26402  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
26403  unixFile *conchFile;        /* Name of the conch file */
26404
26405  pCtx = (proxyLockingContext *)pFile->lockingContext;
26406  conchFile = pCtx->conchFile;
26407  OSTRACE4("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
26408           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
26409           getpid());
26410  pCtx->conchHeld = 0;
26411  rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
26412  OSTRACE3("RELEASECONCH  %d %s\n", conchFile->h,
26413           (rc==SQLITE_OK ? "ok" : "failed"));
26414  return rc;
26415}
26416
26417/*
26418** Given the name of a database file, compute the name of its conch file.
26419** Store the conch filename in memory obtained from sqlite3_malloc().
26420** Make *pConchPath point to the new name.  Return SQLITE_OK on success
26421** or SQLITE_NOMEM if unable to obtain memory.
26422**
26423** The caller is responsible for ensuring that the allocated memory
26424** space is eventually freed.
26425**
26426** *pConchPath is set to NULL if a memory allocation error occurs.
26427*/
26428static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
26429  int i;                        /* Loop counter */
26430  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
26431  char *conchPath;              /* buffer in which to construct conch name */
26432
26433  /* Allocate space for the conch filename and initialize the name to
26434  ** the name of the original database file. */
26435  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
26436  if( conchPath==0 ){
26437    return SQLITE_NOMEM;
26438  }
26439  memcpy(conchPath, dbPath, len+1);
26440
26441  /* now insert a "." before the last / character */
26442  for( i=(len-1); i>=0; i-- ){
26443    if( conchPath[i]=='/' ){
26444      i++;
26445      break;
26446    }
26447  }
26448  conchPath[i]='.';
26449  while ( i<len ){
26450    conchPath[i+1]=dbPath[i];
26451    i++;
26452  }
26453
26454  /* append the "-conch" suffix to the file */
26455  memcpy(&conchPath[i+1], "-conch", 7);
26456  assert( (int)strlen(conchPath) == len+7 );
26457
26458  return SQLITE_OK;
26459}
26460
26461
26462/* Takes a fully configured proxy locking-style unix file and switches
26463** the local lock file path
26464*/
26465static int switchLockProxyPath(unixFile *pFile, const char *path) {
26466  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
26467  char *oldPath = pCtx->lockProxyPath;
26468  int rc = SQLITE_OK;
26469
26470  if( pFile->locktype!=NO_LOCK ){
26471    return SQLITE_BUSY;
26472  }
26473
26474  /* nothing to do if the path is NULL, :auto: or matches the existing path */
26475  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
26476    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
26477    return SQLITE_OK;
26478  }else{
26479    unixFile *lockProxy = pCtx->lockProxy;
26480    pCtx->lockProxy=NULL;
26481    pCtx->conchHeld = 0;
26482    if( lockProxy!=NULL ){
26483      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
26484      if( rc ) return rc;
26485      sqlite3_free(lockProxy);
26486    }
26487    sqlite3_free(oldPath);
26488    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
26489  }
26490
26491  return rc;
26492}
26493
26494/*
26495** pFile is a file that has been opened by a prior xOpen call.  dbPath
26496** is a string buffer at least MAXPATHLEN+1 characters in size.
26497**
26498** This routine find the filename associated with pFile and writes it
26499** int dbPath.
26500*/
26501static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
26502#if defined(__APPLE__)
26503  if( pFile->pMethod == &afpIoMethods ){
26504    /* afp style keeps a reference to the db path in the filePath field
26505    ** of the struct */
26506    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
26507    strcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath);
26508  }else
26509#endif
26510  if( pFile->pMethod == &dotlockIoMethods ){
26511    /* dot lock style uses the locking context to store the dot lock
26512    ** file path */
26513    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
26514    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
26515  }else{
26516    /* all other styles use the locking context to store the db file path */
26517    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
26518    strcpy(dbPath, (char *)pFile->lockingContext);
26519  }
26520  return SQLITE_OK;
26521}
26522
26523/*
26524** Takes an already filled in unix file and alters it so all file locking
26525** will be performed on the local proxy lock file.  The following fields
26526** are preserved in the locking context so that they can be restored and
26527** the unix structure properly cleaned up at close time:
26528**  ->lockingContext
26529**  ->pMethod
26530*/
26531static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
26532  proxyLockingContext *pCtx;
26533  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
26534  char *lockPath=NULL;
26535  int rc = SQLITE_OK;
26536
26537  if( pFile->locktype!=NO_LOCK ){
26538    return SQLITE_BUSY;
26539  }
26540  proxyGetDbPathForUnixFile(pFile, dbPath);
26541  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
26542    lockPath=NULL;
26543  }else{
26544    lockPath=(char *)path;
26545  }
26546
26547  OSTRACE4("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
26548           (lockPath ? lockPath : ":auto:"), getpid());
26549
26550  pCtx = sqlite3_malloc( sizeof(*pCtx) );
26551  if( pCtx==0 ){
26552    return SQLITE_NOMEM;
26553  }
26554  memset(pCtx, 0, sizeof(*pCtx));
26555
26556  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
26557  if( rc==SQLITE_OK ){
26558    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile);
26559  }
26560  if( rc==SQLITE_OK && lockPath ){
26561    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
26562  }
26563
26564  if( rc==SQLITE_OK ){
26565    /* all memory is allocated, proxys are created and assigned,
26566    ** switch the locking context and pMethod then return.
26567    */
26568    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
26569    pCtx->oldLockingContext = pFile->lockingContext;
26570    pFile->lockingContext = pCtx;
26571    pCtx->pOldMethod = pFile->pMethod;
26572    pFile->pMethod = &proxyIoMethods;
26573  }else{
26574    if( pCtx->conchFile ){
26575      rc = pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
26576      if( rc ) return rc;
26577      sqlite3_free(pCtx->conchFile);
26578    }
26579    sqlite3_free(pCtx->conchFilePath);
26580    sqlite3_free(pCtx);
26581  }
26582  OSTRACE3("TRANSPROXY  %d %s\n", pFile->h,
26583           (rc==SQLITE_OK ? "ok" : "failed"));
26584  return rc;
26585}
26586
26587
26588/*
26589** This routine handles sqlite3_file_control() calls that are specific
26590** to proxy locking.
26591*/
26592static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
26593  switch( op ){
26594    case SQLITE_GET_LOCKPROXYFILE: {
26595      unixFile *pFile = (unixFile*)id;
26596      if( pFile->pMethod == &proxyIoMethods ){
26597        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
26598        proxyTakeConch(pFile);
26599        if( pCtx->lockProxyPath ){
26600          *(const char **)pArg = pCtx->lockProxyPath;
26601        }else{
26602          *(const char **)pArg = ":auto: (not held)";
26603        }
26604      } else {
26605        *(const char **)pArg = NULL;
26606      }
26607      return SQLITE_OK;
26608    }
26609    case SQLITE_SET_LOCKPROXYFILE: {
26610      unixFile *pFile = (unixFile*)id;
26611      int rc = SQLITE_OK;
26612      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
26613      if( pArg==NULL || (const char *)pArg==0 ){
26614        if( isProxyStyle ){
26615          /* turn off proxy locking - not supported */
26616          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
26617        }else{
26618          /* turn off proxy locking - already off - NOOP */
26619          rc = SQLITE_OK;
26620        }
26621      }else{
26622        const char *proxyPath = (const char *)pArg;
26623        if( isProxyStyle ){
26624          proxyLockingContext *pCtx =
26625            (proxyLockingContext*)pFile->lockingContext;
26626          if( !strcmp(pArg, ":auto:")
26627           || (pCtx->lockProxyPath &&
26628               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
26629          ){
26630            rc = SQLITE_OK;
26631          }else{
26632            rc = switchLockProxyPath(pFile, proxyPath);
26633          }
26634        }else{
26635          /* turn on proxy file locking */
26636          rc = proxyTransformUnixFile(pFile, proxyPath);
26637        }
26638      }
26639      return rc;
26640    }
26641    default: {
26642      assert( 0 );  /* The call assures that only valid opcodes are sent */
26643    }
26644  }
26645  /*NOTREACHED*/
26646  return SQLITE_ERROR;
26647}
26648
26649/*
26650** Within this division (the proxying locking implementation) the procedures
26651** above this point are all utilities.  The lock-related methods of the
26652** proxy-locking sqlite3_io_method object follow.
26653*/
26654
26655
26656/*
26657** This routine checks if there is a RESERVED lock held on the specified
26658** file by this or any other process. If such a lock is held, set *pResOut
26659** to a non-zero value otherwise *pResOut is set to zero.  The return value
26660** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26661*/
26662static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
26663  unixFile *pFile = (unixFile*)id;
26664  int rc = proxyTakeConch(pFile);
26665  if( rc==SQLITE_OK ){
26666    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26667    unixFile *proxy = pCtx->lockProxy;
26668    return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
26669  }
26670  return rc;
26671}
26672
26673/*
26674** Lock the file with the lock specified by parameter locktype - one
26675** of the following:
26676**
26677**     (1) SHARED_LOCK
26678**     (2) RESERVED_LOCK
26679**     (3) PENDING_LOCK
26680**     (4) EXCLUSIVE_LOCK
26681**
26682** Sometimes when requesting one lock state, additional lock states
26683** are inserted in between.  The locking might fail on one of the later
26684** transitions leaving the lock state different from what it started but
26685** still short of its goal.  The following chart shows the allowed
26686** transitions and the inserted intermediate states:
26687**
26688**    UNLOCKED -> SHARED
26689**    SHARED -> RESERVED
26690**    SHARED -> (PENDING) -> EXCLUSIVE
26691**    RESERVED -> (PENDING) -> EXCLUSIVE
26692**    PENDING -> EXCLUSIVE
26693**
26694** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26695** routine to lower a locking level.
26696*/
26697static int proxyLock(sqlite3_file *id, int locktype) {
26698  unixFile *pFile = (unixFile*)id;
26699  int rc = proxyTakeConch(pFile);
26700  if( rc==SQLITE_OK ){
26701    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26702    unixFile *proxy = pCtx->lockProxy;
26703    rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
26704    pFile->locktype = proxy->locktype;
26705  }
26706  return rc;
26707}
26708
26709
26710/*
26711** Lower the locking level on file descriptor pFile to locktype.  locktype
26712** must be either NO_LOCK or SHARED_LOCK.
26713**
26714** If the locking level of the file descriptor is already at or below
26715** the requested locking level, this routine is a no-op.
26716*/
26717static int proxyUnlock(sqlite3_file *id, int locktype) {
26718  unixFile *pFile = (unixFile*)id;
26719  int rc = proxyTakeConch(pFile);
26720  if( rc==SQLITE_OK ){
26721    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26722    unixFile *proxy = pCtx->lockProxy;
26723    rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
26724    pFile->locktype = proxy->locktype;
26725  }
26726  return rc;
26727}
26728
26729/*
26730** Close a file that uses proxy locks.
26731*/
26732static int proxyClose(sqlite3_file *id) {
26733  if( id ){
26734    unixFile *pFile = (unixFile*)id;
26735    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
26736    unixFile *lockProxy = pCtx->lockProxy;
26737    unixFile *conchFile = pCtx->conchFile;
26738    int rc = SQLITE_OK;
26739
26740    if( lockProxy ){
26741      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
26742      if( rc ) return rc;
26743      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
26744      if( rc ) return rc;
26745      sqlite3_free(lockProxy);
26746      pCtx->lockProxy = 0;
26747    }
26748    if( conchFile ){
26749      if( pCtx->conchHeld ){
26750        rc = proxyReleaseConch(pFile);
26751        if( rc ) return rc;
26752      }
26753      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
26754      if( rc ) return rc;
26755      sqlite3_free(conchFile);
26756    }
26757    sqlite3_free(pCtx->lockProxyPath);
26758    sqlite3_free(pCtx->conchFilePath);
26759    sqlite3_free(pCtx->dbPath);
26760    /* restore the original locking context and pMethod then close it */
26761    pFile->lockingContext = pCtx->oldLockingContext;
26762    pFile->pMethod = pCtx->pOldMethod;
26763    sqlite3_free(pCtx);
26764    return pFile->pMethod->xClose(id);
26765  }
26766  return SQLITE_OK;
26767}
26768
26769
26770
26771#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26772/*
26773** The proxy locking style is intended for use with AFP filesystems.
26774** And since AFP is only supported on MacOSX, the proxy locking is also
26775** restricted to MacOSX.
26776**
26777**
26778******************* End of the proxy lock implementation **********************
26779******************************************************************************/
26780
26781/*
26782** Initialize the operating system interface.
26783**
26784** This routine registers all VFS implementations for unix-like operating
26785** systems.  This routine, and the sqlite3_os_end() routine that follows,
26786** should be the only routines in this file that are visible from other
26787** files.
26788**
26789** This routine is called once during SQLite initialization and by a
26790** single thread.  The memory allocation and mutex subsystems have not
26791** necessarily been initialized when this routine is called, and so they
26792** should not be used.
26793*/
26794SQLITE_API int sqlite3_os_init(void){
26795  /*
26796  ** The following macro defines an initializer for an sqlite3_vfs object.
26797  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
26798  ** to the "finder" function.  (pAppData is a pointer to a pointer because
26799  ** silly C90 rules prohibit a void* from being cast to a function pointer
26800  ** and so we have to go through the intermediate pointer to avoid problems
26801  ** when compiling with -pedantic-errors on GCC.)
26802  **
26803  ** The FINDER parameter to this macro is the name of the pointer to the
26804  ** finder-function.  The finder-function returns a pointer to the
26805  ** sqlite_io_methods object that implements the desired locking
26806  ** behaviors.  See the division above that contains the IOMETHODS
26807  ** macro for addition information on finder-functions.
26808  **
26809  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
26810  ** object.  But the "autolockIoFinder" available on MacOSX does a little
26811  ** more than that; it looks at the filesystem type that hosts the
26812  ** database file and tries to choose an locking method appropriate for
26813  ** that filesystem time.
26814  */
26815  #define UNIXVFS(VFSNAME, FINDER) {                        \
26816    1,                    /* iVersion */                    \
26817    sizeof(unixFile),     /* szOsFile */                    \
26818    MAX_PATHNAME,         /* mxPathname */                  \
26819    0,                    /* pNext */                       \
26820    VFSNAME,              /* zName */                       \
26821    (void*)&FINDER,       /* pAppData */                    \
26822    unixOpen,             /* xOpen */                       \
26823    unixDelete,           /* xDelete */                     \
26824    unixAccess,           /* xAccess */                     \
26825    unixFullPathname,     /* xFullPathname */               \
26826    unixDlOpen,           /* xDlOpen */                     \
26827    unixDlError,          /* xDlError */                    \
26828    unixDlSym,            /* xDlSym */                      \
26829    unixDlClose,          /* xDlClose */                    \
26830    unixRandomness,       /* xRandomness */                 \
26831    unixSleep,            /* xSleep */                      \
26832    unixCurrentTime,      /* xCurrentTime */                \
26833    unixGetLastError      /* xGetLastError */               \
26834  }
26835
26836  /*
26837  ** All default VFSes for unix are contained in the following array.
26838  **
26839  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
26840  ** by the SQLite core when the VFS is registered.  So the following
26841  ** array cannot be const.
26842  */
26843  static sqlite3_vfs aVfs[] = {
26844#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
26845    UNIXVFS("unix",          autolockIoFinder ),
26846#else
26847    UNIXVFS("unix",          posixIoFinder ),
26848#endif
26849    UNIXVFS("unix-none",     nolockIoFinder ),
26850    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
26851    UNIXVFS("unix-wfl",      posixWflIoFinder ),
26852#if OS_VXWORKS
26853    UNIXVFS("unix-namedsem", semIoFinder ),
26854#endif
26855#if SQLITE_ENABLE_LOCKING_STYLE
26856    UNIXVFS("unix-posix",    posixIoFinder ),
26857#if !OS_VXWORKS
26858    UNIXVFS("unix-flock",    flockIoFinder ),
26859#endif
26860#endif
26861#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26862    UNIXVFS("unix-afp",      afpIoFinder ),
26863    UNIXVFS("unix-proxy",    proxyIoFinder ),
26864#endif
26865  };
26866  unsigned int i;          /* Loop counter */
26867
26868  /* Register all VFSes defined in the aVfs[] array */
26869  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
26870    sqlite3_vfs_register(&aVfs[i], i==0);
26871  }
26872  return SQLITE_OK;
26873}
26874
26875/*
26876** Shutdown the operating system interface.
26877**
26878** Some operating systems might need to do some cleanup in this routine,
26879** to release dynamically allocated objects.  But not on unix.
26880** This routine is a no-op for unix.
26881*/
26882SQLITE_API int sqlite3_os_end(void){
26883  return SQLITE_OK;
26884}
26885
26886#endif /* SQLITE_OS_UNIX */
26887
26888/************** End of os_unix.c *********************************************/
26889/************** Begin file os_win.c ******************************************/
26890/*
26891** 2004 May 22
26892**
26893** The author disclaims copyright to this source code.  In place of
26894** a legal notice, here is a blessing:
26895**
26896**    May you do good and not evil.
26897**    May you find forgiveness for yourself and forgive others.
26898**    May you share freely, never taking more than you give.
26899**
26900******************************************************************************
26901**
26902** This file contains code that is specific to windows.
26903*/
26904#if SQLITE_OS_WIN               /* This file is used for windows only */
26905
26906
26907/*
26908** A Note About Memory Allocation:
26909**
26910** This driver uses malloc()/free() directly rather than going through
26911** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
26912** are designed for use on embedded systems where memory is scarce and
26913** malloc failures happen frequently.  Win32 does not typically run on
26914** embedded systems, and when it does the developers normally have bigger
26915** problems to worry about than running out of memory.  So there is not
26916** a compelling need to use the wrappers.
26917**
26918** But there is a good reason to not use the wrappers.  If we use the
26919** wrappers then we will get simulated malloc() failures within this
26920** driver.  And that causes all kinds of problems for our tests.  We
26921** could enhance SQLite to deal with simulated malloc failures within
26922** the OS driver, but the code to deal with those failure would not
26923** be exercised on Linux (which does not need to malloc() in the driver)
26924** and so we would have difficulty writing coverage tests for that
26925** code.  Better to leave the code out, we think.
26926**
26927** The point of this discussion is as follows:  When creating a new
26928** OS layer for an embedded system, if you use this file as an example,
26929** avoid the use of malloc()/free().  Those routines work ok on windows
26930** desktops but not so well in embedded systems.
26931*/
26932
26933#include <winbase.h>
26934
26935#ifdef __CYGWIN__
26936# include <sys/cygwin.h>
26937#endif
26938
26939/*
26940** Macros used to determine whether or not to use threads.
26941*/
26942#if defined(THREADSAFE) && THREADSAFE
26943# define SQLITE_W32_THREADS 1
26944#endif
26945
26946/*
26947** Include code that is common to all os_*.c files
26948*/
26949/************** Include os_common.h in the middle of os_win.c ****************/
26950/************** Begin file os_common.h ***************************************/
26951/*
26952** 2004 May 22
26953**
26954** The author disclaims copyright to this source code.  In place of
26955** a legal notice, here is a blessing:
26956**
26957**    May you do good and not evil.
26958**    May you find forgiveness for yourself and forgive others.
26959**    May you share freely, never taking more than you give.
26960**
26961******************************************************************************
26962**
26963** This file contains macros and a little bit of code that is common to
26964** all of the platform-specific files (os_*.c) and is #included into those
26965** files.
26966**
26967** This file should be #included by the os_*.c files only.  It is not a
26968** general purpose header file.
26969*/
26970#ifndef _OS_COMMON_H_
26971#define _OS_COMMON_H_
26972
26973/*
26974** At least two bugs have slipped in because we changed the MEMORY_DEBUG
26975** macro to SQLITE_DEBUG and some older makefiles have not yet made the
26976** switch.  The following code should catch this problem at compile-time.
26977*/
26978#ifdef MEMORY_DEBUG
26979# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
26980#endif
26981
26982#ifdef SQLITE_DEBUG
26983SQLITE_PRIVATE int sqlite3OSTrace = 0;
26984#define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
26985#define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
26986#define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
26987#define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
26988#define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
26989#define OSTRACE6(X,Y,Z,A,B,C) \
26990    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
26991#define OSTRACE7(X,Y,Z,A,B,C,D) \
26992    if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
26993#else
26994#define OSTRACE1(X)
26995#define OSTRACE2(X,Y)
26996#define OSTRACE3(X,Y,Z)
26997#define OSTRACE4(X,Y,Z,A)
26998#define OSTRACE5(X,Y,Z,A,B)
26999#define OSTRACE6(X,Y,Z,A,B,C)
27000#define OSTRACE7(X,Y,Z,A,B,C,D)
27001#endif
27002
27003/*
27004** Macros for performance tracing.  Normally turned off.  Only works
27005** on i486 hardware.
27006*/
27007#ifdef SQLITE_PERFORMANCE_TRACE
27008
27009/*
27010** hwtime.h contains inline assembler code for implementing
27011** high-performance timing routines.
27012*/
27013/************** Include hwtime.h in the middle of os_common.h ****************/
27014/************** Begin file hwtime.h ******************************************/
27015/*
27016** 2008 May 27
27017**
27018** The author disclaims copyright to this source code.  In place of
27019** a legal notice, here is a blessing:
27020**
27021**    May you do good and not evil.
27022**    May you find forgiveness for yourself and forgive others.
27023**    May you share freely, never taking more than you give.
27024**
27025******************************************************************************
27026**
27027** This file contains inline asm code for retrieving "high-performance"
27028** counters for x86 class CPUs.
27029*/
27030#ifndef _HWTIME_H_
27031#define _HWTIME_H_
27032
27033/*
27034** The following routine only works on pentium-class (or newer) processors.
27035** It uses the RDTSC opcode to read the cycle count value out of the
27036** processor and returns that value.  This can be used for high-res
27037** profiling.
27038*/
27039#if (defined(__GNUC__) || defined(_MSC_VER)) && \
27040      (defined(i386) || defined(__i386__) || defined(_M_IX86))
27041
27042  #if defined(__GNUC__)
27043
27044  __inline__ sqlite_uint64 sqlite3Hwtime(void){
27045     unsigned int lo, hi;
27046     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
27047     return (sqlite_uint64)hi << 32 | lo;
27048  }
27049
27050  #elif defined(_MSC_VER)
27051
27052  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
27053     __asm {
27054        rdtsc
27055        ret       ; return value at EDX:EAX
27056     }
27057  }
27058
27059  #endif
27060
27061#elif (defined(__GNUC__) && defined(__x86_64__))
27062
27063  __inline__ sqlite_uint64 sqlite3Hwtime(void){
27064      unsigned long val;
27065      __asm__ __volatile__ ("rdtsc" : "=A" (val));
27066      return val;
27067  }
27068
27069#elif (defined(__GNUC__) && defined(__ppc__))
27070
27071  __inline__ sqlite_uint64 sqlite3Hwtime(void){
27072      unsigned long long retval;
27073      unsigned long junk;
27074      __asm__ __volatile__ ("\n\
27075          1:      mftbu   %1\n\
27076                  mftb    %L0\n\
27077                  mftbu   %0\n\
27078                  cmpw    %0,%1\n\
27079                  bne     1b"
27080                  : "=r" (retval), "=r" (junk));
27081      return retval;
27082  }
27083
27084#else
27085
27086  #error Need implementation of sqlite3Hwtime() for your platform.
27087
27088  /*
27089  ** To compile without implementing sqlite3Hwtime() for your platform,
27090  ** you can remove the above #error and use the following
27091  ** stub function.  You will lose timing support for many
27092  ** of the debugging and testing utilities, but it should at
27093  ** least compile and run.
27094  */
27095SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
27096
27097#endif
27098
27099#endif /* !defined(_HWTIME_H_) */
27100
27101/************** End of hwtime.h **********************************************/
27102/************** Continuing where we left off in os_common.h ******************/
27103
27104static sqlite_uint64 g_start;
27105static sqlite_uint64 g_elapsed;
27106#define TIMER_START       g_start=sqlite3Hwtime()
27107#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
27108#define TIMER_ELAPSED     g_elapsed
27109#else
27110#define TIMER_START
27111#define TIMER_END
27112#define TIMER_ELAPSED     ((sqlite_uint64)0)
27113#endif
27114
27115/*
27116** If we compile with the SQLITE_TEST macro set, then the following block
27117** of code will give us the ability to simulate a disk I/O error.  This
27118** is used for testing the I/O recovery logic.
27119*/
27120#ifdef SQLITE_TEST
27121SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
27122SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
27123SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
27124SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
27125SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
27126SQLITE_API int sqlite3_diskfull_pending = 0;
27127SQLITE_API int sqlite3_diskfull = 0;
27128#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
27129#define SimulateIOError(CODE)  \
27130  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
27131       || sqlite3_io_error_pending-- == 1 )  \
27132              { local_ioerr(); CODE; }
27133static void local_ioerr(){
27134  IOTRACE(("IOERR\n"));
27135  sqlite3_io_error_hit++;
27136  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
27137}
27138#define SimulateDiskfullError(CODE) \
27139   if( sqlite3_diskfull_pending ){ \
27140     if( sqlite3_diskfull_pending == 1 ){ \
27141       local_ioerr(); \
27142       sqlite3_diskfull = 1; \
27143       sqlite3_io_error_hit = 1; \
27144       CODE; \
27145     }else{ \
27146       sqlite3_diskfull_pending--; \
27147     } \
27148   }
27149#else
27150#define SimulateIOErrorBenign(X)
27151#define SimulateIOError(A)
27152#define SimulateDiskfullError(A)
27153#endif
27154
27155/*
27156** When testing, keep a count of the number of open files.
27157*/
27158#ifdef SQLITE_TEST
27159SQLITE_API int sqlite3_open_file_count = 0;
27160#define OpenCounter(X)  sqlite3_open_file_count+=(X)
27161#else
27162#define OpenCounter(X)
27163#endif
27164
27165#endif /* !defined(_OS_COMMON_H_) */
27166
27167/************** End of os_common.h *******************************************/
27168/************** Continuing where we left off in os_win.c *********************/
27169
27170/*
27171** Some microsoft compilers lack this definition.
27172*/
27173#ifndef INVALID_FILE_ATTRIBUTES
27174# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
27175#endif
27176
27177/*
27178** Determine if we are dealing with WindowsCE - which has a much
27179** reduced API.
27180*/
27181#if SQLITE_OS_WINCE
27182# define AreFileApisANSI() 1
27183# define FormatMessageW(a,b,c,d,e,f,g) 0
27184#endif
27185
27186/*
27187** WinCE lacks native support for file locking so we have to fake it
27188** with some code of our own.
27189*/
27190#if SQLITE_OS_WINCE
27191typedef struct winceLock {
27192  int nReaders;       /* Number of reader locks obtained */
27193  BOOL bPending;      /* Indicates a pending lock has been obtained */
27194  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
27195  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
27196} winceLock;
27197#endif
27198
27199/*
27200** The winFile structure is a subclass of sqlite3_file* specific to the win32
27201** portability layer.
27202*/
27203typedef struct winFile winFile;
27204struct winFile {
27205  const sqlite3_io_methods *pMethod;/* Must be first */
27206  HANDLE h;               /* Handle for accessing the file */
27207  unsigned char locktype; /* Type of lock currently held on this file */
27208  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
27209  DWORD lastErrno;        /* The Windows errno from the last I/O error */
27210  DWORD sectorSize;       /* Sector size of the device file is on */
27211#if SQLITE_OS_WINCE
27212  WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
27213  HANDLE hMutex;          /* Mutex used to control access to shared lock */
27214  HANDLE hShared;         /* Shared memory segment used for locking */
27215  winceLock local;        /* Locks obtained by this instance of winFile */
27216  winceLock *shared;      /* Global shared lock memory for the file  */
27217#endif
27218};
27219
27220/*
27221** Forward prototypes.
27222*/
27223static int getSectorSize(
27224    sqlite3_vfs *pVfs,
27225    const char *zRelative     /* UTF-8 file name */
27226);
27227
27228/*
27229** The following variable is (normally) set once and never changes
27230** thereafter.  It records whether the operating system is Win95
27231** or WinNT.
27232**
27233** 0:   Operating system unknown.
27234** 1:   Operating system is Win95.
27235** 2:   Operating system is WinNT.
27236**
27237** In order to facilitate testing on a WinNT system, the test fixture
27238** can manually set this value to 1 to emulate Win98 behavior.
27239*/
27240#ifdef SQLITE_TEST
27241SQLITE_API int sqlite3_os_type = 0;
27242#else
27243static int sqlite3_os_type = 0;
27244#endif
27245
27246/*
27247** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
27248** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
27249**
27250** Here is an interesting observation:  Win95, Win98, and WinME lack
27251** the LockFileEx() API.  But we can still statically link against that
27252** API as long as we don't call it when running Win95/98/ME.  A call to
27253** this routine is used to determine if the host is Win95/98/ME or
27254** WinNT/2K/XP so that we will know whether or not we can safely call
27255** the LockFileEx() API.
27256*/
27257#if SQLITE_OS_WINCE
27258# define isNT()  (1)
27259#else
27260  static int isNT(void){
27261    if( sqlite3_os_type==0 ){
27262      OSVERSIONINFO sInfo;
27263      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
27264      GetVersionEx(&sInfo);
27265      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
27266    }
27267    return sqlite3_os_type==2;
27268  }
27269#endif /* SQLITE_OS_WINCE */
27270
27271/*
27272** Convert a UTF-8 string to microsoft unicode (UTF-16?).
27273**
27274** Space to hold the returned string is obtained from malloc.
27275*/
27276static WCHAR *utf8ToUnicode(const char *zFilename){
27277  int nChar;
27278  WCHAR *zWideFilename;
27279
27280  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
27281  zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
27282  if( zWideFilename==0 ){
27283    return 0;
27284  }
27285  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
27286  if( nChar==0 ){
27287    free(zWideFilename);
27288    zWideFilename = 0;
27289  }
27290  return zWideFilename;
27291}
27292
27293/*
27294** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
27295** obtained from malloc().
27296*/
27297static char *unicodeToUtf8(const WCHAR *zWideFilename){
27298  int nByte;
27299  char *zFilename;
27300
27301  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
27302  zFilename = malloc( nByte );
27303  if( zFilename==0 ){
27304    return 0;
27305  }
27306  nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
27307                              0, 0);
27308  if( nByte == 0 ){
27309    free(zFilename);
27310    zFilename = 0;
27311  }
27312  return zFilename;
27313}
27314
27315/*
27316** Convert an ansi string to microsoft unicode, based on the
27317** current codepage settings for file apis.
27318**
27319** Space to hold the returned string is obtained
27320** from malloc.
27321*/
27322static WCHAR *mbcsToUnicode(const char *zFilename){
27323  int nByte;
27324  WCHAR *zMbcsFilename;
27325  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
27326
27327  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
27328  zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
27329  if( zMbcsFilename==0 ){
27330    return 0;
27331  }
27332  nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
27333  if( nByte==0 ){
27334    free(zMbcsFilename);
27335    zMbcsFilename = 0;
27336  }
27337  return zMbcsFilename;
27338}
27339
27340/*
27341** Convert microsoft unicode to multibyte character string, based on the
27342** user's Ansi codepage.
27343**
27344** Space to hold the returned string is obtained from
27345** malloc().
27346*/
27347static char *unicodeToMbcs(const WCHAR *zWideFilename){
27348  int nByte;
27349  char *zFilename;
27350  int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
27351
27352  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
27353  zFilename = malloc( nByte );
27354  if( zFilename==0 ){
27355    return 0;
27356  }
27357  nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
27358                              0, 0);
27359  if( nByte == 0 ){
27360    free(zFilename);
27361    zFilename = 0;
27362  }
27363  return zFilename;
27364}
27365
27366/*
27367** Convert multibyte character string to UTF-8.  Space to hold the
27368** returned string is obtained from malloc().
27369*/
27370SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
27371  char *zFilenameUtf8;
27372  WCHAR *zTmpWide;
27373
27374  zTmpWide = mbcsToUnicode(zFilename);
27375  if( zTmpWide==0 ){
27376    return 0;
27377  }
27378  zFilenameUtf8 = unicodeToUtf8(zTmpWide);
27379  free(zTmpWide);
27380  return zFilenameUtf8;
27381}
27382
27383/*
27384** Convert UTF-8 to multibyte character string.  Space to hold the
27385** returned string is obtained from malloc().
27386*/
27387static char *utf8ToMbcs(const char *zFilename){
27388  char *zFilenameMbcs;
27389  WCHAR *zTmpWide;
27390
27391  zTmpWide = utf8ToUnicode(zFilename);
27392  if( zTmpWide==0 ){
27393    return 0;
27394  }
27395  zFilenameMbcs = unicodeToMbcs(zTmpWide);
27396  free(zTmpWide);
27397  return zFilenameMbcs;
27398}
27399
27400#if SQLITE_OS_WINCE
27401/*************************************************************************
27402** This section contains code for WinCE only.
27403*/
27404/*
27405** WindowsCE does not have a localtime() function.  So create a
27406** substitute.
27407*/
27408struct tm *__cdecl localtime(const time_t *t)
27409{
27410  static struct tm y;
27411  FILETIME uTm, lTm;
27412  SYSTEMTIME pTm;
27413  sqlite3_int64 t64;
27414  t64 = *t;
27415  t64 = (t64 + 11644473600)*10000000;
27416  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
27417  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
27418  FileTimeToLocalFileTime(&uTm,&lTm);
27419  FileTimeToSystemTime(&lTm,&pTm);
27420  y.tm_year = pTm.wYear - 1900;
27421  y.tm_mon = pTm.wMonth - 1;
27422  y.tm_wday = pTm.wDayOfWeek;
27423  y.tm_mday = pTm.wDay;
27424  y.tm_hour = pTm.wHour;
27425  y.tm_min = pTm.wMinute;
27426  y.tm_sec = pTm.wSecond;
27427  return &y;
27428}
27429
27430/* This will never be called, but defined to make the code compile */
27431#define GetTempPathA(a,b)
27432
27433#define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
27434#define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
27435#define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
27436
27437#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
27438
27439/*
27440** Acquire a lock on the handle h
27441*/
27442static void winceMutexAcquire(HANDLE h){
27443   DWORD dwErr;
27444   do {
27445     dwErr = WaitForSingleObject(h, INFINITE);
27446   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
27447}
27448/*
27449** Release a lock acquired by winceMutexAcquire()
27450*/
27451#define winceMutexRelease(h) ReleaseMutex(h)
27452
27453/*
27454** Create the mutex and shared memory used for locking in the file
27455** descriptor pFile
27456*/
27457static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
27458  WCHAR *zTok;
27459  WCHAR *zName = utf8ToUnicode(zFilename);
27460  BOOL bInit = TRUE;
27461
27462  /* Initialize the local lockdata */
27463  ZeroMemory(&pFile->local, sizeof(pFile->local));
27464
27465  /* Replace the backslashes from the filename and lowercase it
27466  ** to derive a mutex name. */
27467  zTok = CharLowerW(zName);
27468  for (;*zTok;zTok++){
27469    if (*zTok == '\\') *zTok = '_';
27470  }
27471
27472  /* Create/open the named mutex */
27473  pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
27474  if (!pFile->hMutex){
27475    pFile->lastErrno = GetLastError();
27476    free(zName);
27477    return FALSE;
27478  }
27479
27480  /* Acquire the mutex before continuing */
27481  winceMutexAcquire(pFile->hMutex);
27482
27483  /* Since the names of named mutexes, semaphores, file mappings etc are
27484  ** case-sensitive, take advantage of that by uppercasing the mutex name
27485  ** and using that as the shared filemapping name.
27486  */
27487  CharUpperW(zName);
27488  pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
27489                                       PAGE_READWRITE, 0, sizeof(winceLock),
27490                                       zName);
27491
27492  /* Set a flag that indicates we're the first to create the memory so it
27493  ** must be zero-initialized */
27494  if (GetLastError() == ERROR_ALREADY_EXISTS){
27495    bInit = FALSE;
27496  }
27497
27498  free(zName);
27499
27500  /* If we succeeded in making the shared memory handle, map it. */
27501  if (pFile->hShared){
27502    pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared,
27503             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
27504    /* If mapping failed, close the shared memory handle and erase it */
27505    if (!pFile->shared){
27506      pFile->lastErrno = GetLastError();
27507      CloseHandle(pFile->hShared);
27508      pFile->hShared = NULL;
27509    }
27510  }
27511
27512  /* If shared memory could not be created, then close the mutex and fail */
27513  if (pFile->hShared == NULL){
27514    winceMutexRelease(pFile->hMutex);
27515    CloseHandle(pFile->hMutex);
27516    pFile->hMutex = NULL;
27517    return FALSE;
27518  }
27519
27520  /* Initialize the shared memory if we're supposed to */
27521  if (bInit) {
27522    ZeroMemory(pFile->shared, sizeof(winceLock));
27523  }
27524
27525  winceMutexRelease(pFile->hMutex);
27526  return TRUE;
27527}
27528
27529/*
27530** Destroy the part of winFile that deals with wince locks
27531*/
27532static void winceDestroyLock(winFile *pFile){
27533  if (pFile->hMutex){
27534    /* Acquire the mutex */
27535    winceMutexAcquire(pFile->hMutex);
27536
27537    /* The following blocks should probably assert in debug mode, but they
27538       are to cleanup in case any locks remained open */
27539    if (pFile->local.nReaders){
27540      pFile->shared->nReaders --;
27541    }
27542    if (pFile->local.bReserved){
27543      pFile->shared->bReserved = FALSE;
27544    }
27545    if (pFile->local.bPending){
27546      pFile->shared->bPending = FALSE;
27547    }
27548    if (pFile->local.bExclusive){
27549      pFile->shared->bExclusive = FALSE;
27550    }
27551
27552    /* De-reference and close our copy of the shared memory handle */
27553    UnmapViewOfFile(pFile->shared);
27554    CloseHandle(pFile->hShared);
27555
27556    /* Done with the mutex */
27557    winceMutexRelease(pFile->hMutex);
27558    CloseHandle(pFile->hMutex);
27559    pFile->hMutex = NULL;
27560  }
27561}
27562
27563/*
27564** An implementation of the LockFile() API of windows for wince
27565*/
27566static BOOL winceLockFile(
27567  HANDLE *phFile,
27568  DWORD dwFileOffsetLow,
27569  DWORD dwFileOffsetHigh,
27570  DWORD nNumberOfBytesToLockLow,
27571  DWORD nNumberOfBytesToLockHigh
27572){
27573  winFile *pFile = HANDLE_TO_WINFILE(phFile);
27574  BOOL bReturn = FALSE;
27575
27576  UNUSED_PARAMETER(dwFileOffsetHigh);
27577  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
27578
27579  if (!pFile->hMutex) return TRUE;
27580  winceMutexAcquire(pFile->hMutex);
27581
27582  /* Wanting an exclusive lock? */
27583  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
27584       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
27585    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
27586       pFile->shared->bExclusive = TRUE;
27587       pFile->local.bExclusive = TRUE;
27588       bReturn = TRUE;
27589    }
27590  }
27591
27592  /* Want a read-only lock? */
27593  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
27594           nNumberOfBytesToLockLow == 1){
27595    if (pFile->shared->bExclusive == 0){
27596      pFile->local.nReaders ++;
27597      if (pFile->local.nReaders == 1){
27598        pFile->shared->nReaders ++;
27599      }
27600      bReturn = TRUE;
27601    }
27602  }
27603
27604  /* Want a pending lock? */
27605  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
27606    /* If no pending lock has been acquired, then acquire it */
27607    if (pFile->shared->bPending == 0) {
27608      pFile->shared->bPending = TRUE;
27609      pFile->local.bPending = TRUE;
27610      bReturn = TRUE;
27611    }
27612  }
27613
27614  /* Want a reserved lock? */
27615  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
27616    if (pFile->shared->bReserved == 0) {
27617      pFile->shared->bReserved = TRUE;
27618      pFile->local.bReserved = TRUE;
27619      bReturn = TRUE;
27620    }
27621  }
27622
27623  winceMutexRelease(pFile->hMutex);
27624  return bReturn;
27625}
27626
27627/*
27628** An implementation of the UnlockFile API of windows for wince
27629*/
27630static BOOL winceUnlockFile(
27631  HANDLE *phFile,
27632  DWORD dwFileOffsetLow,
27633  DWORD dwFileOffsetHigh,
27634  DWORD nNumberOfBytesToUnlockLow,
27635  DWORD nNumberOfBytesToUnlockHigh
27636){
27637  winFile *pFile = HANDLE_TO_WINFILE(phFile);
27638  BOOL bReturn = FALSE;
27639
27640  UNUSED_PARAMETER(dwFileOffsetHigh);
27641  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
27642
27643  if (!pFile->hMutex) return TRUE;
27644  winceMutexAcquire(pFile->hMutex);
27645
27646  /* Releasing a reader lock or an exclusive lock */
27647  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
27648    /* Did we have an exclusive lock? */
27649    if (pFile->local.bExclusive){
27650      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
27651      pFile->local.bExclusive = FALSE;
27652      pFile->shared->bExclusive = FALSE;
27653      bReturn = TRUE;
27654    }
27655
27656    /* Did we just have a reader lock? */
27657    else if (pFile->local.nReaders){
27658      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
27659      pFile->local.nReaders --;
27660      if (pFile->local.nReaders == 0)
27661      {
27662        pFile->shared->nReaders --;
27663      }
27664      bReturn = TRUE;
27665    }
27666  }
27667
27668  /* Releasing a pending lock */
27669  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
27670    if (pFile->local.bPending){
27671      pFile->local.bPending = FALSE;
27672      pFile->shared->bPending = FALSE;
27673      bReturn = TRUE;
27674    }
27675  }
27676  /* Releasing a reserved lock */
27677  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
27678    if (pFile->local.bReserved) {
27679      pFile->local.bReserved = FALSE;
27680      pFile->shared->bReserved = FALSE;
27681      bReturn = TRUE;
27682    }
27683  }
27684
27685  winceMutexRelease(pFile->hMutex);
27686  return bReturn;
27687}
27688
27689/*
27690** An implementation of the LockFileEx() API of windows for wince
27691*/
27692static BOOL winceLockFileEx(
27693  HANDLE *phFile,
27694  DWORD dwFlags,
27695  DWORD dwReserved,
27696  DWORD nNumberOfBytesToLockLow,
27697  DWORD nNumberOfBytesToLockHigh,
27698  LPOVERLAPPED lpOverlapped
27699){
27700  UNUSED_PARAMETER(dwReserved);
27701  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
27702
27703  /* If the caller wants a shared read lock, forward this call
27704  ** to winceLockFile */
27705  if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
27706      dwFlags == 1 &&
27707      nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
27708    return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
27709  }
27710  return FALSE;
27711}
27712/*
27713** End of the special code for wince
27714*****************************************************************************/
27715#endif /* SQLITE_OS_WINCE */
27716
27717/*****************************************************************************
27718** The next group of routines implement the I/O methods specified
27719** by the sqlite3_io_methods object.
27720******************************************************************************/
27721
27722/*
27723** Close a file.
27724**
27725** It is reported that an attempt to close a handle might sometimes
27726** fail.  This is a very unreasonable result, but windows is notorious
27727** for being unreasonable so I do not doubt that it might happen.  If
27728** the close fails, we pause for 100 milliseconds and try again.  As
27729** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
27730** giving up and returning an error.
27731*/
27732#define MX_CLOSE_ATTEMPT 3
27733static int winClose(sqlite3_file *id){
27734  int rc, cnt = 0;
27735  winFile *pFile = (winFile*)id;
27736
27737  assert( id!=0 );
27738  OSTRACE2("CLOSE %d\n", pFile->h);
27739  do{
27740    rc = CloseHandle(pFile->h);
27741  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
27742#if SQLITE_OS_WINCE
27743#define WINCE_DELETION_ATTEMPTS 3
27744  winceDestroyLock(pFile);
27745  if( pFile->zDeleteOnClose ){
27746    int cnt = 0;
27747    while(
27748           DeleteFileW(pFile->zDeleteOnClose)==0
27749        && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
27750        && cnt++ < WINCE_DELETION_ATTEMPTS
27751    ){
27752       Sleep(100);  /* Wait a little before trying again */
27753    }
27754    free(pFile->zDeleteOnClose);
27755  }
27756#endif
27757  OpenCounter(-1);
27758  return rc ? SQLITE_OK : SQLITE_IOERR;
27759}
27760
27761/*
27762** Some microsoft compilers lack this definition.
27763*/
27764#ifndef INVALID_SET_FILE_POINTER
27765# define INVALID_SET_FILE_POINTER ((DWORD)-1)
27766#endif
27767
27768/*
27769** Read data from a file into a buffer.  Return SQLITE_OK if all
27770** bytes were read successfully and SQLITE_IOERR if anything goes
27771** wrong.
27772*/
27773static int winRead(
27774  sqlite3_file *id,          /* File to read from */
27775  void *pBuf,                /* Write content into this buffer */
27776  int amt,                   /* Number of bytes to read */
27777  sqlite3_int64 offset       /* Begin reading at this offset */
27778){
27779  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
27780  LONG lowerBits = (LONG)(offset & 0xffffffff);
27781  DWORD rc;
27782  winFile *pFile = (winFile*)id;
27783  DWORD error;
27784  DWORD got;
27785
27786  assert( id!=0 );
27787  SimulateIOError(return SQLITE_IOERR_READ);
27788  OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
27789  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
27790  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
27791    pFile->lastErrno = error;
27792    return SQLITE_FULL;
27793  }
27794  if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
27795    pFile->lastErrno = GetLastError();
27796    return SQLITE_IOERR_READ;
27797  }
27798  if( got==(DWORD)amt ){
27799    return SQLITE_OK;
27800  }else{
27801    /* Unread parts of the buffer must be zero-filled */
27802    memset(&((char*)pBuf)[got], 0, amt-got);
27803    return SQLITE_IOERR_SHORT_READ;
27804  }
27805}
27806
27807/*
27808** Write data from a buffer into a file.  Return SQLITE_OK on success
27809** or some other error code on failure.
27810*/
27811static int winWrite(
27812  sqlite3_file *id,         /* File to write into */
27813  const void *pBuf,         /* The bytes to be written */
27814  int amt,                  /* Number of bytes to write */
27815  sqlite3_int64 offset      /* Offset into the file to begin writing at */
27816){
27817  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
27818  LONG lowerBits = (LONG)(offset & 0xffffffff);
27819  DWORD rc;
27820  winFile *pFile = (winFile*)id;
27821  DWORD error;
27822  DWORD wrote = 0;
27823
27824  assert( id!=0 );
27825  SimulateIOError(return SQLITE_IOERR_WRITE);
27826  SimulateDiskfullError(return SQLITE_FULL);
27827  OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
27828  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
27829  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
27830    pFile->lastErrno = error;
27831    return SQLITE_FULL;
27832  }
27833  assert( amt>0 );
27834  while(
27835     amt>0
27836     && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
27837     && wrote>0
27838  ){
27839    amt -= wrote;
27840    pBuf = &((char*)pBuf)[wrote];
27841  }
27842  if( !rc || amt>(int)wrote ){
27843    pFile->lastErrno = GetLastError();
27844    return SQLITE_FULL;
27845  }
27846  return SQLITE_OK;
27847}
27848
27849/*
27850** Truncate an open file to a specified size
27851*/
27852static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
27853  LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
27854  LONG lowerBits = (LONG)(nByte & 0xffffffff);
27855  DWORD rc;
27856  winFile *pFile = (winFile*)id;
27857  DWORD error;
27858
27859  assert( id!=0 );
27860  OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
27861  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
27862  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
27863  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
27864    pFile->lastErrno = error;
27865    return SQLITE_IOERR_TRUNCATE;
27866  }
27867  /* SetEndOfFile will fail if nByte is negative */
27868  if( !SetEndOfFile(pFile->h) ){
27869    pFile->lastErrno = GetLastError();
27870    return SQLITE_IOERR_TRUNCATE;
27871  }
27872  return SQLITE_OK;
27873}
27874
27875#ifdef SQLITE_TEST
27876/*
27877** Count the number of fullsyncs and normal syncs.  This is used to test
27878** that syncs and fullsyncs are occuring at the right times.
27879*/
27880SQLITE_API int sqlite3_sync_count = 0;
27881SQLITE_API int sqlite3_fullsync_count = 0;
27882#endif
27883
27884/*
27885** Make sure all writes to a particular file are committed to disk.
27886*/
27887static int winSync(sqlite3_file *id, int flags){
27888#ifndef SQLITE_NO_SYNC
27889  winFile *pFile = (winFile*)id;
27890
27891  assert( id!=0 );
27892  OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
27893#else
27894  UNUSED_PARAMETER(id);
27895#endif
27896#ifndef SQLITE_TEST
27897  UNUSED_PARAMETER(flags);
27898#else
27899  if( flags & SQLITE_SYNC_FULL ){
27900    sqlite3_fullsync_count++;
27901  }
27902  sqlite3_sync_count++;
27903#endif
27904  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
27905  ** no-op
27906  */
27907#ifdef SQLITE_NO_SYNC
27908    return SQLITE_OK;
27909#else
27910  if( FlushFileBuffers(pFile->h) ){
27911    return SQLITE_OK;
27912  }else{
27913    pFile->lastErrno = GetLastError();
27914    return SQLITE_IOERR;
27915  }
27916#endif
27917}
27918
27919/*
27920** Determine the current size of a file in bytes
27921*/
27922static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
27923  DWORD upperBits;
27924  DWORD lowerBits;
27925  winFile *pFile = (winFile*)id;
27926  DWORD error;
27927
27928  assert( id!=0 );
27929  SimulateIOError(return SQLITE_IOERR_FSTAT);
27930  lowerBits = GetFileSize(pFile->h, &upperBits);
27931  if(   (lowerBits == INVALID_FILE_SIZE)
27932     && ((error = GetLastError()) != NO_ERROR) )
27933  {
27934    pFile->lastErrno = error;
27935    return SQLITE_IOERR_FSTAT;
27936  }
27937  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
27938  return SQLITE_OK;
27939}
27940
27941/*
27942** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
27943*/
27944#ifndef LOCKFILE_FAIL_IMMEDIATELY
27945# define LOCKFILE_FAIL_IMMEDIATELY 1
27946#endif
27947
27948/*
27949** Acquire a reader lock.
27950** Different API routines are called depending on whether or not this
27951** is Win95 or WinNT.
27952*/
27953static int getReadLock(winFile *pFile){
27954  int res;
27955  if( isNT() ){
27956    OVERLAPPED ovlp;
27957    ovlp.Offset = SHARED_FIRST;
27958    ovlp.OffsetHigh = 0;
27959    ovlp.hEvent = 0;
27960    res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
27961                     0, SHARED_SIZE, 0, &ovlp);
27962/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
27963*/
27964#if SQLITE_OS_WINCE==0
27965  }else{
27966    int lk;
27967    sqlite3_randomness(sizeof(lk), &lk);
27968    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
27969    res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
27970#endif
27971  }
27972  if( res == 0 ){
27973    pFile->lastErrno = GetLastError();
27974  }
27975  return res;
27976}
27977
27978/*
27979** Undo a readlock
27980*/
27981static int unlockReadLock(winFile *pFile){
27982  int res;
27983  if( isNT() ){
27984    res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
27985/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
27986*/
27987#if SQLITE_OS_WINCE==0
27988  }else{
27989    res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
27990#endif
27991  }
27992  if( res == 0 ){
27993    pFile->lastErrno = GetLastError();
27994  }
27995  return res;
27996}
27997
27998/*
27999** Lock the file with the lock specified by parameter locktype - one
28000** of the following:
28001**
28002**     (1) SHARED_LOCK
28003**     (2) RESERVED_LOCK
28004**     (3) PENDING_LOCK
28005**     (4) EXCLUSIVE_LOCK
28006**
28007** Sometimes when requesting one lock state, additional lock states
28008** are inserted in between.  The locking might fail on one of the later
28009** transitions leaving the lock state different from what it started but
28010** still short of its goal.  The following chart shows the allowed
28011** transitions and the inserted intermediate states:
28012**
28013**    UNLOCKED -> SHARED
28014**    SHARED -> RESERVED
28015**    SHARED -> (PENDING) -> EXCLUSIVE
28016**    RESERVED -> (PENDING) -> EXCLUSIVE
28017**    PENDING -> EXCLUSIVE
28018**
28019** This routine will only increase a lock.  The winUnlock() routine
28020** erases all locks at once and returns us immediately to locking level 0.
28021** It is not possible to lower the locking level one step at a time.  You
28022** must go straight to locking level 0.
28023*/
28024static int winLock(sqlite3_file *id, int locktype){
28025  int rc = SQLITE_OK;    /* Return code from subroutines */
28026  int res = 1;           /* Result of a windows lock call */
28027  int newLocktype;       /* Set pFile->locktype to this value before exiting */
28028  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
28029  winFile *pFile = (winFile*)id;
28030  DWORD error = NO_ERROR;
28031
28032  assert( id!=0 );
28033  OSTRACE5("LOCK %d %d was %d(%d)\n",
28034          pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
28035
28036  /* If there is already a lock of this type or more restrictive on the
28037  ** OsFile, do nothing. Don't use the end_lock: exit path, as
28038  ** sqlite3OsEnterMutex() hasn't been called yet.
28039  */
28040  if( pFile->locktype>=locktype ){
28041    return SQLITE_OK;
28042  }
28043
28044  /* Make sure the locking sequence is correct
28045  */
28046  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
28047  assert( locktype!=PENDING_LOCK );
28048  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
28049
28050  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
28051  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
28052  ** the PENDING_LOCK byte is temporary.
28053  */
28054  newLocktype = pFile->locktype;
28055  if(   (pFile->locktype==NO_LOCK)
28056     || (   (locktype==EXCLUSIVE_LOCK)
28057         && (pFile->locktype==RESERVED_LOCK))
28058  ){
28059    int cnt = 3;
28060    while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
28061      /* Try 3 times to get the pending lock.  The pending lock might be
28062      ** held by another reader process who will release it momentarily.
28063      */
28064      OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
28065      Sleep(1);
28066    }
28067    gotPendingLock = res;
28068    if( !res ){
28069      error = GetLastError();
28070    }
28071  }
28072
28073  /* Acquire a shared lock
28074  */
28075  if( locktype==SHARED_LOCK && res ){
28076    assert( pFile->locktype==NO_LOCK );
28077    res = getReadLock(pFile);
28078    if( res ){
28079      newLocktype = SHARED_LOCK;
28080    }else{
28081      error = GetLastError();
28082    }
28083  }
28084
28085  /* Acquire a RESERVED lock
28086  */
28087  if( locktype==RESERVED_LOCK && res ){
28088    assert( pFile->locktype==SHARED_LOCK );
28089    res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28090    if( res ){
28091      newLocktype = RESERVED_LOCK;
28092    }else{
28093      error = GetLastError();
28094    }
28095  }
28096
28097  /* Acquire a PENDING lock
28098  */
28099  if( locktype==EXCLUSIVE_LOCK && res ){
28100    newLocktype = PENDING_LOCK;
28101    gotPendingLock = 0;
28102  }
28103
28104  /* Acquire an EXCLUSIVE lock
28105  */
28106  if( locktype==EXCLUSIVE_LOCK && res ){
28107    assert( pFile->locktype>=SHARED_LOCK );
28108    res = unlockReadLock(pFile);
28109    OSTRACE2("unreadlock = %d\n", res);
28110    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28111    if( res ){
28112      newLocktype = EXCLUSIVE_LOCK;
28113    }else{
28114      error = GetLastError();
28115      OSTRACE2("error-code = %d\n", error);
28116      getReadLock(pFile);
28117    }
28118  }
28119
28120  /* If we are holding a PENDING lock that ought to be released, then
28121  ** release it now.
28122  */
28123  if( gotPendingLock && locktype==SHARED_LOCK ){
28124    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
28125  }
28126
28127  /* Update the state of the lock has held in the file descriptor then
28128  ** return the appropriate result code.
28129  */
28130  if( res ){
28131    rc = SQLITE_OK;
28132  }else{
28133    OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
28134           locktype, newLocktype);
28135    pFile->lastErrno = error;
28136    rc = SQLITE_BUSY;
28137  }
28138  pFile->locktype = (u8)newLocktype;
28139  return rc;
28140}
28141
28142/*
28143** This routine checks if there is a RESERVED lock held on the specified
28144** file by this or any other process. If such a lock is held, return
28145** non-zero, otherwise zero.
28146*/
28147static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
28148  int rc;
28149  winFile *pFile = (winFile*)id;
28150
28151  assert( id!=0 );
28152  if( pFile->locktype>=RESERVED_LOCK ){
28153    rc = 1;
28154    OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
28155  }else{
28156    rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28157    if( rc ){
28158      UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28159    }
28160    rc = !rc;
28161    OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
28162  }
28163  *pResOut = rc;
28164  return SQLITE_OK;
28165}
28166
28167/*
28168** Lower the locking level on file descriptor id to locktype.  locktype
28169** must be either NO_LOCK or SHARED_LOCK.
28170**
28171** If the locking level of the file descriptor is already at or below
28172** the requested locking level, this routine is a no-op.
28173**
28174** It is not possible for this routine to fail if the second argument
28175** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
28176** might return SQLITE_IOERR;
28177*/
28178static int winUnlock(sqlite3_file *id, int locktype){
28179  int type;
28180  winFile *pFile = (winFile*)id;
28181  int rc = SQLITE_OK;
28182  assert( pFile!=0 );
28183  assert( locktype<=SHARED_LOCK );
28184  OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
28185          pFile->locktype, pFile->sharedLockByte);
28186  type = pFile->locktype;
28187  if( type>=EXCLUSIVE_LOCK ){
28188    UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28189    if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
28190      /* This should never happen.  We should always be able to
28191      ** reacquire the read lock */
28192      rc = SQLITE_IOERR_UNLOCK;
28193    }
28194  }
28195  if( type>=RESERVED_LOCK ){
28196    UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
28197  }
28198  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
28199    unlockReadLock(pFile);
28200  }
28201  if( type>=PENDING_LOCK ){
28202    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
28203  }
28204  pFile->locktype = (u8)locktype;
28205  return rc;
28206}
28207
28208/*
28209** Control and query of the open file handle.
28210*/
28211static int winFileControl(sqlite3_file *id, int op, void *pArg){
28212  switch( op ){
28213    case SQLITE_FCNTL_LOCKSTATE: {
28214      *(int*)pArg = ((winFile*)id)->locktype;
28215      return SQLITE_OK;
28216    }
28217    case SQLITE_LAST_ERRNO: {
28218      *(int*)pArg = (int)((winFile*)id)->lastErrno;
28219      return SQLITE_OK;
28220    }
28221  }
28222  return SQLITE_ERROR;
28223}
28224
28225/*
28226** Return the sector size in bytes of the underlying block device for
28227** the specified file. This is almost always 512 bytes, but may be
28228** larger for some devices.
28229**
28230** SQLite code assumes this function cannot fail. It also assumes that
28231** if two files are created in the same file-system directory (i.e.
28232** a database and its journal file) that the sector size will be the
28233** same for both.
28234*/
28235static int winSectorSize(sqlite3_file *id){
28236  assert( id!=0 );
28237  return (int)(((winFile*)id)->sectorSize);
28238}
28239
28240/*
28241** Return a vector of device characteristics.
28242*/
28243static int winDeviceCharacteristics(sqlite3_file *id){
28244  UNUSED_PARAMETER(id);
28245  return 0;
28246}
28247
28248/*
28249** This vector defines all the methods that can operate on an
28250** sqlite3_file for win32.
28251*/
28252static const sqlite3_io_methods winIoMethod = {
28253  1,                        /* iVersion */
28254  winClose,
28255  winRead,
28256  winWrite,
28257  winTruncate,
28258  winSync,
28259  winFileSize,
28260  winLock,
28261  winUnlock,
28262  winCheckReservedLock,
28263  winFileControl,
28264  winSectorSize,
28265  winDeviceCharacteristics
28266};
28267
28268/***************************************************************************
28269** Here ends the I/O methods that form the sqlite3_io_methods object.
28270**
28271** The next block of code implements the VFS methods.
28272****************************************************************************/
28273
28274/*
28275** Convert a UTF-8 filename into whatever form the underlying
28276** operating system wants filenames in.  Space to hold the result
28277** is obtained from malloc and must be freed by the calling
28278** function.
28279*/
28280static void *convertUtf8Filename(const char *zFilename){
28281  void *zConverted = 0;
28282  if( isNT() ){
28283    zConverted = utf8ToUnicode(zFilename);
28284/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28285*/
28286#if SQLITE_OS_WINCE==0
28287  }else{
28288    zConverted = utf8ToMbcs(zFilename);
28289#endif
28290  }
28291  /* caller will handle out of memory */
28292  return zConverted;
28293}
28294
28295/*
28296** Create a temporary file name in zBuf.  zBuf must be big enough to
28297** hold at pVfs->mxPathname characters.
28298*/
28299static int getTempname(int nBuf, char *zBuf){
28300  static char zChars[] =
28301    "abcdefghijklmnopqrstuvwxyz"
28302    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28303    "0123456789";
28304  size_t i, j;
28305  char zTempPath[MAX_PATH+1];
28306  if( sqlite3_temp_directory ){
28307    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
28308  }else if( isNT() ){
28309    char *zMulti;
28310    WCHAR zWidePath[MAX_PATH];
28311    GetTempPathW(MAX_PATH-30, zWidePath);
28312    zMulti = unicodeToUtf8(zWidePath);
28313    if( zMulti ){
28314      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
28315      free(zMulti);
28316    }else{
28317      return SQLITE_NOMEM;
28318    }
28319/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28320** Since the ASCII version of these Windows API do not exist for WINCE,
28321** it's important to not reference them for WINCE builds.
28322*/
28323#if SQLITE_OS_WINCE==0
28324  }else{
28325    char *zUtf8;
28326    char zMbcsPath[MAX_PATH];
28327    GetTempPathA(MAX_PATH-30, zMbcsPath);
28328    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
28329    if( zUtf8 ){
28330      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
28331      free(zUtf8);
28332    }else{
28333      return SQLITE_NOMEM;
28334    }
28335#endif
28336  }
28337  for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
28338  zTempPath[i] = 0;
28339  sqlite3_snprintf(nBuf-30, zBuf,
28340                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
28341  j = sqlite3Strlen30(zBuf);
28342  sqlite3_randomness(20, &zBuf[j]);
28343  for(i=0; i<20; i++, j++){
28344    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28345  }
28346  zBuf[j] = 0;
28347  OSTRACE2("TEMP FILENAME: %s\n", zBuf);
28348  return SQLITE_OK;
28349}
28350
28351/*
28352** The return value of getLastErrorMsg
28353** is zero if the error message fits in the buffer, or non-zero
28354** otherwise (if the message was truncated).
28355*/
28356static int getLastErrorMsg(int nBuf, char *zBuf){
28357  /* FormatMessage returns 0 on failure.  Otherwise it
28358  ** returns the number of TCHARs written to the output
28359  ** buffer, excluding the terminating null char.
28360  */
28361  DWORD error = GetLastError();
28362  DWORD dwLen = 0;
28363  char *zOut = 0;
28364
28365  if( isNT() ){
28366    WCHAR *zTempWide = NULL;
28367    dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
28368                           NULL,
28369                           error,
28370                           0,
28371                           (LPWSTR) &zTempWide,
28372                           0,
28373                           0);
28374    if( dwLen > 0 ){
28375      /* allocate a buffer and convert to UTF8 */
28376      zOut = unicodeToUtf8(zTempWide);
28377      /* free the system buffer allocated by FormatMessage */
28378      LocalFree(zTempWide);
28379    }
28380/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28381** Since the ASCII version of these Windows API do not exist for WINCE,
28382** it's important to not reference them for WINCE builds.
28383*/
28384#if SQLITE_OS_WINCE==0
28385  }else{
28386    char *zTemp = NULL;
28387    dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
28388                           NULL,
28389                           error,
28390                           0,
28391                           (LPSTR) &zTemp,
28392                           0,
28393                           0);
28394    if( dwLen > 0 ){
28395      /* allocate a buffer and convert to UTF8 */
28396      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
28397      /* free the system buffer allocated by FormatMessage */
28398      LocalFree(zTemp);
28399    }
28400#endif
28401  }
28402  if( 0 == dwLen ){
28403    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
28404  }else{
28405    /* copy a maximum of nBuf chars to output buffer */
28406    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
28407    /* free the UTF8 buffer */
28408    free(zOut);
28409  }
28410  return 0;
28411}
28412
28413/*
28414** Open a file.
28415*/
28416static int winOpen(
28417  sqlite3_vfs *pVfs,        /* Not used */
28418  const char *zName,        /* Name of the file (UTF-8) */
28419  sqlite3_file *id,         /* Write the SQLite file handle here */
28420  int flags,                /* Open mode flags */
28421  int *pOutFlags            /* Status return flags */
28422){
28423  HANDLE h;
28424  DWORD dwDesiredAccess;
28425  DWORD dwShareMode;
28426  DWORD dwCreationDisposition;
28427  DWORD dwFlagsAndAttributes = 0;
28428#if SQLITE_OS_WINCE
28429  int isTemp = 0;
28430#endif
28431  winFile *pFile = (winFile*)id;
28432  void *zConverted;                 /* Filename in OS encoding */
28433  const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
28434  char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
28435
28436  assert( id!=0 );
28437  UNUSED_PARAMETER(pVfs);
28438
28439  /* If the second argument to this function is NULL, generate a
28440  ** temporary file name to use
28441  */
28442  if( !zUtf8Name ){
28443    int rc = getTempname(MAX_PATH+1, zTmpname);
28444    if( rc!=SQLITE_OK ){
28445      return rc;
28446    }
28447    zUtf8Name = zTmpname;
28448  }
28449
28450  /* Convert the filename to the system encoding. */
28451  zConverted = convertUtf8Filename(zUtf8Name);
28452  if( zConverted==0 ){
28453    return SQLITE_NOMEM;
28454  }
28455
28456  if( flags & SQLITE_OPEN_READWRITE ){
28457    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
28458  }else{
28459    dwDesiredAccess = GENERIC_READ;
28460  }
28461  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
28462  ** created. SQLite doesn't use it to indicate "exclusive access"
28463  ** as it is usually understood.
28464  */
28465  assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
28466  if( flags & SQLITE_OPEN_EXCLUSIVE ){
28467    /* Creates a new file, only if it does not already exist. */
28468    /* If the file exists, it fails. */
28469    dwCreationDisposition = CREATE_NEW;
28470  }else if( flags & SQLITE_OPEN_CREATE ){
28471    /* Open existing file, or create if it doesn't exist */
28472    dwCreationDisposition = OPEN_ALWAYS;
28473  }else{
28474    /* Opens a file, only if it exists. */
28475    dwCreationDisposition = OPEN_EXISTING;
28476  }
28477  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
28478  if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28479#if SQLITE_OS_WINCE
28480    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
28481    isTemp = 1;
28482#else
28483    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
28484                               | FILE_ATTRIBUTE_HIDDEN
28485                               | FILE_FLAG_DELETE_ON_CLOSE;
28486#endif
28487  }else{
28488    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
28489  }
28490  /* Reports from the internet are that performance is always
28491  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
28492#if SQLITE_OS_WINCE
28493  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
28494#endif
28495  if( isNT() ){
28496    h = CreateFileW((WCHAR*)zConverted,
28497       dwDesiredAccess,
28498       dwShareMode,
28499       NULL,
28500       dwCreationDisposition,
28501       dwFlagsAndAttributes,
28502       NULL
28503    );
28504/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28505** Since the ASCII version of these Windows API do not exist for WINCE,
28506** it's important to not reference them for WINCE builds.
28507*/
28508#if SQLITE_OS_WINCE==0
28509  }else{
28510    h = CreateFileA((char*)zConverted,
28511       dwDesiredAccess,
28512       dwShareMode,
28513       NULL,
28514       dwCreationDisposition,
28515       dwFlagsAndAttributes,
28516       NULL
28517    );
28518#endif
28519  }
28520  if( h==INVALID_HANDLE_VALUE ){
28521    free(zConverted);
28522    if( flags & SQLITE_OPEN_READWRITE ){
28523      return winOpen(pVfs, zName, id,
28524             ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
28525    }else{
28526      return SQLITE_CANTOPEN;
28527    }
28528  }
28529  if( pOutFlags ){
28530    if( flags & SQLITE_OPEN_READWRITE ){
28531      *pOutFlags = SQLITE_OPEN_READWRITE;
28532    }else{
28533      *pOutFlags = SQLITE_OPEN_READONLY;
28534    }
28535  }
28536  memset(pFile, 0, sizeof(*pFile));
28537  pFile->pMethod = &winIoMethod;
28538  pFile->h = h;
28539  pFile->lastErrno = NO_ERROR;
28540  pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
28541#if SQLITE_OS_WINCE
28542  if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
28543               (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
28544       && !winceCreateLock(zName, pFile)
28545  ){
28546    CloseHandle(h);
28547    free(zConverted);
28548    return SQLITE_CANTOPEN;
28549  }
28550  if( isTemp ){
28551    pFile->zDeleteOnClose = zConverted;
28552  }else
28553#endif
28554  {
28555    free(zConverted);
28556  }
28557  OpenCounter(+1);
28558  return SQLITE_OK;
28559}
28560
28561/*
28562** Delete the named file.
28563**
28564** Note that windows does not allow a file to be deleted if some other
28565** process has it open.  Sometimes a virus scanner or indexing program
28566** will open a journal file shortly after it is created in order to do
28567** whatever it does.  While this other process is holding the
28568** file open, we will be unable to delete it.  To work around this
28569** problem, we delay 100 milliseconds and try to delete again.  Up
28570** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
28571** up and returning an error.
28572*/
28573#define MX_DELETION_ATTEMPTS 5
28574static int winDelete(
28575  sqlite3_vfs *pVfs,          /* Not used on win32 */
28576  const char *zFilename,      /* Name of file to delete */
28577  int syncDir                 /* Not used on win32 */
28578){
28579  int cnt = 0;
28580  DWORD rc;
28581  DWORD error = 0;
28582  void *zConverted = convertUtf8Filename(zFilename);
28583  UNUSED_PARAMETER(pVfs);
28584  UNUSED_PARAMETER(syncDir);
28585  if( zConverted==0 ){
28586    return SQLITE_NOMEM;
28587  }
28588  SimulateIOError(return SQLITE_IOERR_DELETE);
28589  if( isNT() ){
28590    do{
28591      DeleteFileW(zConverted);
28592    }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
28593               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
28594           && (++cnt < MX_DELETION_ATTEMPTS)
28595           && (Sleep(100), 1) );
28596/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28597** Since the ASCII version of these Windows API do not exist for WINCE,
28598** it's important to not reference them for WINCE builds.
28599*/
28600#if SQLITE_OS_WINCE==0
28601  }else{
28602    do{
28603      DeleteFileA(zConverted);
28604    }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
28605               || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
28606           && (++cnt < MX_DELETION_ATTEMPTS)
28607           && (Sleep(100), 1) );
28608#endif
28609  }
28610  free(zConverted);
28611  OSTRACE2("DELETE \"%s\"\n", zFilename);
28612  return (   (rc == INVALID_FILE_ATTRIBUTES)
28613          && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
28614}
28615
28616/*
28617** Check the existance and status of a file.
28618*/
28619static int winAccess(
28620  sqlite3_vfs *pVfs,         /* Not used on win32 */
28621  const char *zFilename,     /* Name of file to check */
28622  int flags,                 /* Type of test to make on this file */
28623  int *pResOut               /* OUT: Result */
28624){
28625  DWORD attr;
28626  int rc = 0;
28627  void *zConverted = convertUtf8Filename(zFilename);
28628  UNUSED_PARAMETER(pVfs);
28629  if( zConverted==0 ){
28630    return SQLITE_NOMEM;
28631  }
28632  if( isNT() ){
28633    attr = GetFileAttributesW((WCHAR*)zConverted);
28634/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28635** Since the ASCII version of these Windows API do not exist for WINCE,
28636** it's important to not reference them for WINCE builds.
28637*/
28638#if SQLITE_OS_WINCE==0
28639  }else{
28640    attr = GetFileAttributesA((char*)zConverted);
28641#endif
28642  }
28643  free(zConverted);
28644  switch( flags ){
28645    case SQLITE_ACCESS_READ:
28646    case SQLITE_ACCESS_EXISTS:
28647      rc = attr!=INVALID_FILE_ATTRIBUTES;
28648      break;
28649    case SQLITE_ACCESS_READWRITE:
28650      rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
28651      break;
28652    default:
28653      assert(!"Invalid flags argument");
28654  }
28655  *pResOut = rc;
28656  return SQLITE_OK;
28657}
28658
28659
28660/*
28661** Turn a relative pathname into a full pathname.  Write the full
28662** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
28663** bytes in size.
28664*/
28665static int winFullPathname(
28666  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
28667  const char *zRelative,        /* Possibly relative input path */
28668  int nFull,                    /* Size of output buffer in bytes */
28669  char *zFull                   /* Output buffer */
28670){
28671
28672#if defined(__CYGWIN__)
28673  UNUSED_PARAMETER(nFull);
28674  cygwin_conv_to_full_win32_path(zRelative, zFull);
28675  return SQLITE_OK;
28676#endif
28677
28678#if SQLITE_OS_WINCE
28679  UNUSED_PARAMETER(nFull);
28680  /* WinCE has no concept of a relative pathname, or so I am told. */
28681  sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
28682  return SQLITE_OK;
28683#endif
28684
28685#if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
28686  int nByte;
28687  void *zConverted;
28688  char *zOut;
28689  UNUSED_PARAMETER(nFull);
28690  zConverted = convertUtf8Filename(zRelative);
28691  if( isNT() ){
28692    WCHAR *zTemp;
28693    nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
28694    zTemp = malloc( nByte*sizeof(zTemp[0]) );
28695    if( zTemp==0 ){
28696      free(zConverted);
28697      return SQLITE_NOMEM;
28698    }
28699    GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
28700    free(zConverted);
28701    zOut = unicodeToUtf8(zTemp);
28702    free(zTemp);
28703/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28704** Since the ASCII version of these Windows API do not exist for WINCE,
28705** it's important to not reference them for WINCE builds.
28706*/
28707#if SQLITE_OS_WINCE==0
28708  }else{
28709    char *zTemp;
28710    nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
28711    zTemp = malloc( nByte*sizeof(zTemp[0]) );
28712    if( zTemp==0 ){
28713      free(zConverted);
28714      return SQLITE_NOMEM;
28715    }
28716    GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
28717    free(zConverted);
28718    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
28719    free(zTemp);
28720#endif
28721  }
28722  if( zOut ){
28723    sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
28724    free(zOut);
28725    return SQLITE_OK;
28726  }else{
28727    return SQLITE_NOMEM;
28728  }
28729#endif
28730}
28731
28732/*
28733** Get the sector size of the device used to store
28734** file.
28735*/
28736static int getSectorSize(
28737    sqlite3_vfs *pVfs,
28738    const char *zRelative     /* UTF-8 file name */
28739){
28740  DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
28741  /* GetDiskFreeSpace is not supported under WINCE */
28742#if SQLITE_OS_WINCE
28743  UNUSED_PARAMETER(pVfs);
28744  UNUSED_PARAMETER(zRelative);
28745#else
28746  char zFullpath[MAX_PATH+1];
28747  int rc;
28748  DWORD dwRet = 0;
28749  DWORD dwDummy;
28750
28751  /*
28752  ** We need to get the full path name of the file
28753  ** to get the drive letter to look up the sector
28754  ** size.
28755  */
28756  rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
28757  if( rc == SQLITE_OK )
28758  {
28759    void *zConverted = convertUtf8Filename(zFullpath);
28760    if( zConverted ){
28761      if( isNT() ){
28762        /* trim path to just drive reference */
28763        WCHAR *p = zConverted;
28764        for(;*p;p++){
28765          if( *p == '\\' ){
28766            *p = '\0';
28767            break;
28768          }
28769        }
28770        dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
28771                                  &dwDummy,
28772                                  &bytesPerSector,
28773                                  &dwDummy,
28774                                  &dwDummy);
28775      }else{
28776        /* trim path to just drive reference */
28777        char *p = (char *)zConverted;
28778        for(;*p;p++){
28779          if( *p == '\\' ){
28780            *p = '\0';
28781            break;
28782          }
28783        }
28784        dwRet = GetDiskFreeSpaceA((char*)zConverted,
28785                                  &dwDummy,
28786                                  &bytesPerSector,
28787                                  &dwDummy,
28788                                  &dwDummy);
28789      }
28790      free(zConverted);
28791    }
28792    if( !dwRet ){
28793      bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
28794    }
28795  }
28796#endif
28797  return (int) bytesPerSector;
28798}
28799
28800#ifndef SQLITE_OMIT_LOAD_EXTENSION
28801/*
28802** Interfaces for opening a shared library, finding entry points
28803** within the shared library, and closing the shared library.
28804*/
28805/*
28806** Interfaces for opening a shared library, finding entry points
28807** within the shared library, and closing the shared library.
28808*/
28809static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
28810  HANDLE h;
28811  void *zConverted = convertUtf8Filename(zFilename);
28812  UNUSED_PARAMETER(pVfs);
28813  if( zConverted==0 ){
28814    return 0;
28815  }
28816  if( isNT() ){
28817    h = LoadLibraryW((WCHAR*)zConverted);
28818/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
28819** Since the ASCII version of these Windows API do not exist for WINCE,
28820** it's important to not reference them for WINCE builds.
28821*/
28822#if SQLITE_OS_WINCE==0
28823  }else{
28824    h = LoadLibraryA((char*)zConverted);
28825#endif
28826  }
28827  free(zConverted);
28828  return (void*)h;
28829}
28830static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
28831  UNUSED_PARAMETER(pVfs);
28832  getLastErrorMsg(nBuf, zBufOut);
28833}
28834void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
28835  UNUSED_PARAMETER(pVfs);
28836#if SQLITE_OS_WINCE
28837  /* The GetProcAddressA() routine is only available on wince. */
28838  return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
28839#else
28840  /* All other windows platforms expect GetProcAddress() to take
28841  ** an Ansi string regardless of the _UNICODE setting */
28842  return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
28843#endif
28844}
28845void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
28846  UNUSED_PARAMETER(pVfs);
28847  FreeLibrary((HANDLE)pHandle);
28848}
28849#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
28850  #define winDlOpen  0
28851  #define winDlError 0
28852  #define winDlSym   0
28853  #define winDlClose 0
28854#endif
28855
28856
28857/*
28858** Write up to nBuf bytes of randomness into zBuf.
28859*/
28860static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
28861  int n = 0;
28862  UNUSED_PARAMETER(pVfs);
28863#if defined(SQLITE_TEST)
28864  n = nBuf;
28865  memset(zBuf, 0, nBuf);
28866#else
28867  if( sizeof(SYSTEMTIME)<=nBuf-n ){
28868    SYSTEMTIME x;
28869    GetSystemTime(&x);
28870    memcpy(&zBuf[n], &x, sizeof(x));
28871    n += sizeof(x);
28872  }
28873  if( sizeof(DWORD)<=nBuf-n ){
28874    DWORD pid = GetCurrentProcessId();
28875    memcpy(&zBuf[n], &pid, sizeof(pid));
28876    n += sizeof(pid);
28877  }
28878  if( sizeof(DWORD)<=nBuf-n ){
28879    DWORD cnt = GetTickCount();
28880    memcpy(&zBuf[n], &cnt, sizeof(cnt));
28881    n += sizeof(cnt);
28882  }
28883  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
28884    LARGE_INTEGER i;
28885    QueryPerformanceCounter(&i);
28886    memcpy(&zBuf[n], &i, sizeof(i));
28887    n += sizeof(i);
28888  }
28889#endif
28890  return n;
28891}
28892
28893
28894/*
28895** Sleep for a little while.  Return the amount of time slept.
28896*/
28897static int winSleep(sqlite3_vfs *pVfs, int microsec){
28898  Sleep((microsec+999)/1000);
28899  UNUSED_PARAMETER(pVfs);
28900  return ((microsec+999)/1000)*1000;
28901}
28902
28903/*
28904** The following variable, if set to a non-zero value, becomes the result
28905** returned from sqlite3OsCurrentTime().  This is used for testing.
28906*/
28907#ifdef SQLITE_TEST
28908SQLITE_API int sqlite3_current_time = 0;
28909#endif
28910
28911/*
28912** Find the current time (in Universal Coordinated Time).  Write the
28913** current time and date as a Julian Day number into *prNow and
28914** return 0.  Return 1 if the time and date cannot be found.
28915*/
28916int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
28917  FILETIME ft;
28918  /* FILETIME structure is a 64-bit value representing the number of
28919     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
28920  */
28921  sqlite3_int64 timeW;   /* Whole days */
28922  sqlite3_int64 timeF;   /* Fractional Days */
28923
28924  /* Number of 100-nanosecond intervals in a single day */
28925  static const sqlite3_int64 ntuPerDay =
28926      10000000*(sqlite3_int64)86400;
28927
28928  /* Number of 100-nanosecond intervals in half of a day */
28929  static const sqlite3_int64 ntuPerHalfDay =
28930      10000000*(sqlite3_int64)43200;
28931
28932  /* 2^32 - to avoid use of LL and warnings in gcc */
28933  static const sqlite3_int64 max32BitValue =
28934      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
28935
28936#if SQLITE_OS_WINCE
28937  SYSTEMTIME time;
28938  GetSystemTime(&time);
28939  /* if SystemTimeToFileTime() fails, it returns zero. */
28940  if (!SystemTimeToFileTime(&time,&ft)){
28941    return 1;
28942  }
28943#else
28944  GetSystemTimeAsFileTime( &ft );
28945#endif
28946  UNUSED_PARAMETER(pVfs);
28947  timeW = (((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime;
28948  timeF = timeW % ntuPerDay;          /* fractional days (100-nanoseconds) */
28949  timeW = timeW / ntuPerDay;          /* whole days */
28950  timeW = timeW + 2305813;            /* add whole days (from 2305813.5) */
28951  timeF = timeF + ntuPerHalfDay;      /* add half a day (from 2305813.5) */
28952  timeW = timeW + (timeF/ntuPerDay);  /* add whole day if half day made one */
28953  timeF = timeF % ntuPerDay;          /* compute new fractional days */
28954  *prNow = (double)timeW + ((double)timeF / (double)ntuPerDay);
28955#ifdef SQLITE_TEST
28956  if( sqlite3_current_time ){
28957    *prNow = ((double)sqlite3_current_time + (double)43200) / (double)86400 + (double)2440587;
28958  }
28959#endif
28960  return 0;
28961}
28962
28963/*
28964** The idea is that this function works like a combination of
28965** GetLastError() and FormatMessage() on windows (or errno and
28966** strerror_r() on unix). After an error is returned by an OS
28967** function, SQLite calls this function with zBuf pointing to
28968** a buffer of nBuf bytes. The OS layer should populate the
28969** buffer with a nul-terminated UTF-8 encoded error message
28970** describing the last IO error to have occurred within the calling
28971** thread.
28972**
28973** If the error message is too large for the supplied buffer,
28974** it should be truncated. The return value of xGetLastError
28975** is zero if the error message fits in the buffer, or non-zero
28976** otherwise (if the message was truncated). If non-zero is returned,
28977** then it is not necessary to include the nul-terminator character
28978** in the output buffer.
28979**
28980** Not supplying an error message will have no adverse effect
28981** on SQLite. It is fine to have an implementation that never
28982** returns an error message:
28983**
28984**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
28985**     assert(zBuf[0]=='\0');
28986**     return 0;
28987**   }
28988**
28989** However if an error message is supplied, it will be incorporated
28990** by sqlite into the error message available to the user using
28991** sqlite3_errmsg(), possibly making IO errors easier to debug.
28992*/
28993static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
28994  UNUSED_PARAMETER(pVfs);
28995  return getLastErrorMsg(nBuf, zBuf);
28996}
28997
28998/*
28999** Initialize and deinitialize the operating system interface.
29000*/
29001SQLITE_API int sqlite3_os_init(void){
29002  static sqlite3_vfs winVfs = {
29003    1,                 /* iVersion */
29004    sizeof(winFile),   /* szOsFile */
29005    MAX_PATH,          /* mxPathname */
29006    0,                 /* pNext */
29007    "win32",           /* zName */
29008    0,                 /* pAppData */
29009
29010    winOpen,           /* xOpen */
29011    winDelete,         /* xDelete */
29012    winAccess,         /* xAccess */
29013    winFullPathname,   /* xFullPathname */
29014    winDlOpen,         /* xDlOpen */
29015    winDlError,        /* xDlError */
29016    winDlSym,          /* xDlSym */
29017    winDlClose,        /* xDlClose */
29018    winRandomness,     /* xRandomness */
29019    winSleep,          /* xSleep */
29020    winCurrentTime,    /* xCurrentTime */
29021    winGetLastError    /* xGetLastError */
29022  };
29023
29024  sqlite3_vfs_register(&winVfs, 1);
29025  return SQLITE_OK;
29026}
29027SQLITE_API int sqlite3_os_end(void){
29028  return SQLITE_OK;
29029}
29030
29031#endif /* SQLITE_OS_WIN */
29032
29033/************** End of os_win.c **********************************************/
29034/************** Begin file bitvec.c ******************************************/
29035/*
29036** 2008 February 16
29037**
29038** The author disclaims copyright to this source code.  In place of
29039** a legal notice, here is a blessing:
29040**
29041**    May you do good and not evil.
29042**    May you find forgiveness for yourself and forgive others.
29043**    May you share freely, never taking more than you give.
29044**
29045*************************************************************************
29046** This file implements an object that represents a fixed-length
29047** bitmap.  Bits are numbered starting with 1.
29048**
29049** A bitmap is used to record which pages of a database file have been
29050** journalled during a transaction, or which pages have the "dont-write"
29051** property.  Usually only a few pages are meet either condition.
29052** So the bitmap is usually sparse and has low cardinality.
29053** But sometimes (for example when during a DROP of a large table) most
29054** or all of the pages in a database can get journalled.  In those cases,
29055** the bitmap becomes dense with high cardinality.  The algorithm needs
29056** to handle both cases well.
29057**
29058** The size of the bitmap is fixed when the object is created.
29059**
29060** All bits are clear when the bitmap is created.  Individual bits
29061** may be set or cleared one at a time.
29062**
29063** Test operations are about 100 times more common that set operations.
29064** Clear operations are exceedingly rare.  There are usually between
29065** 5 and 500 set operations per Bitvec object, though the number of sets can
29066** sometimes grow into tens of thousands or larger.  The size of the
29067** Bitvec object is the number of pages in the database file at the
29068** start of a transaction, and is thus usually less than a few thousand,
29069** but can be as large as 2 billion for a really big database.
29070*/
29071
29072/* Size of the Bitvec structure in bytes. */
29073#define BITVEC_SZ        (sizeof(void*)*128)  /* 512 on 32bit.  1024 on 64bit */
29074
29075/* Round the union size down to the nearest pointer boundary, since that's how
29076** it will be aligned within the Bitvec struct. */
29077#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
29078
29079/* Type of the array "element" for the bitmap representation.
29080** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
29081** Setting this to the "natural word" size of your CPU may improve
29082** performance. */
29083#define BITVEC_TELEM     u8
29084/* Size, in bits, of the bitmap element. */
29085#define BITVEC_SZELEM    8
29086/* Number of elements in a bitmap array. */
29087#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
29088/* Number of bits in the bitmap array. */
29089#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
29090
29091/* Number of u32 values in hash table. */
29092#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
29093/* Maximum number of entries in hash table before
29094** sub-dividing and re-hashing. */
29095#define BITVEC_MXHASH    (BITVEC_NINT/2)
29096/* Hashing function for the aHash representation.
29097** Empirical testing showed that the *37 multiplier
29098** (an arbitrary prime)in the hash function provided
29099** no fewer collisions than the no-op *1. */
29100#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
29101
29102#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
29103
29104
29105/*
29106** A bitmap is an instance of the following structure.
29107**
29108** This bitmap records the existance of zero or more bits
29109** with values between 1 and iSize, inclusive.
29110**
29111** There are three possible representations of the bitmap.
29112** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
29113** bitmap.  The least significant bit is bit 1.
29114**
29115** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
29116** a hash table that will hold up to BITVEC_MXHASH distinct values.
29117**
29118** Otherwise, the value i is redirected into one of BITVEC_NPTR
29119** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
29120** handles up to iDivisor separate values of i.  apSub[0] holds
29121** values between 1 and iDivisor.  apSub[1] holds values between
29122** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
29123** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
29124** to hold deal with values between 1 and iDivisor.
29125*/
29126struct Bitvec {
29127  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
29128  u32 nSet;       /* Number of bits that are set - only valid for aHash
29129                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
29130                  ** this would be 125. */
29131  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
29132                  /* Should >=0 for apSub element. */
29133                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
29134                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
29135  union {
29136    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
29137    u32 aHash[BITVEC_NINT];      /* Hash table representation */
29138    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
29139  } u;
29140};
29141
29142/*
29143** Create a new bitmap object able to handle bits between 0 and iSize,
29144** inclusive.  Return a pointer to the new object.  Return NULL if
29145** malloc fails.
29146*/
29147SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
29148  Bitvec *p;
29149  assert( sizeof(*p)==BITVEC_SZ );
29150  p = sqlite3MallocZero( sizeof(*p) );
29151  if( p ){
29152    p->iSize = iSize;
29153  }
29154  return p;
29155}
29156
29157/*
29158** Check to see if the i-th bit is set.  Return true or false.
29159** If p is NULL (if the bitmap has not been created) or if
29160** i is out of range, then return false.
29161*/
29162SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
29163  if( p==0 ) return 0;
29164  if( i>p->iSize || i==0 ) return 0;
29165  i--;
29166  while( p->iDivisor ){
29167    u32 bin = i/p->iDivisor;
29168    i = i%p->iDivisor;
29169    p = p->u.apSub[bin];
29170    if (!p) {
29171      return 0;
29172    }
29173  }
29174  if( p->iSize<=BITVEC_NBIT ){
29175    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
29176  } else{
29177    u32 h = BITVEC_HASH(i++);
29178    while( p->u.aHash[h] ){
29179      if( p->u.aHash[h]==i ) return 1;
29180      h = (h+1) % BITVEC_NINT;
29181    }
29182    return 0;
29183  }
29184}
29185
29186/*
29187** Set the i-th bit.  Return 0 on success and an error code if
29188** anything goes wrong.
29189**
29190** This routine might cause sub-bitmaps to be allocated.  Failing
29191** to get the memory needed to hold the sub-bitmap is the only
29192** that can go wrong with an insert, assuming p and i are valid.
29193**
29194** The calling function must ensure that p is a valid Bitvec object
29195** and that the value for "i" is within range of the Bitvec object.
29196** Otherwise the behavior is undefined.
29197*/
29198SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
29199  u32 h;
29200  if( p==0 ) return SQLITE_OK;
29201  assert( i>0 );
29202  assert( i<=p->iSize );
29203  i--;
29204  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
29205    u32 bin = i/p->iDivisor;
29206    i = i%p->iDivisor;
29207    if( p->u.apSub[bin]==0 ){
29208      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
29209      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
29210    }
29211    p = p->u.apSub[bin];
29212  }
29213  if( p->iSize<=BITVEC_NBIT ){
29214    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
29215    return SQLITE_OK;
29216  }
29217  h = BITVEC_HASH(i++);
29218  /* if there wasn't a hash collision, and this doesn't */
29219  /* completely fill the hash, then just add it without */
29220  /* worring about sub-dividing and re-hashing. */
29221  if( !p->u.aHash[h] ){
29222    if (p->nSet<(BITVEC_NINT-1)) {
29223      goto bitvec_set_end;
29224    } else {
29225      goto bitvec_set_rehash;
29226    }
29227  }
29228  /* there was a collision, check to see if it's already */
29229  /* in hash, if not, try to find a spot for it */
29230  do {
29231    if( p->u.aHash[h]==i ) return SQLITE_OK;
29232    h++;
29233    if( h>=BITVEC_NINT ) h = 0;
29234  } while( p->u.aHash[h] );
29235  /* we didn't find it in the hash.  h points to the first */
29236  /* available free spot. check to see if this is going to */
29237  /* make our hash too "full".  */
29238bitvec_set_rehash:
29239  if( p->nSet>=BITVEC_MXHASH ){
29240    unsigned int j;
29241    int rc;
29242    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
29243    if( aiValues==0 ){
29244      return SQLITE_NOMEM;
29245    }else{
29246      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
29247      memset(p->u.apSub, 0, sizeof(p->u.apSub));
29248      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
29249      rc = sqlite3BitvecSet(p, i);
29250      for(j=0; j<BITVEC_NINT; j++){
29251        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
29252      }
29253      sqlite3StackFree(0, aiValues);
29254      return rc;
29255    }
29256  }
29257bitvec_set_end:
29258  p->nSet++;
29259  p->u.aHash[h] = i;
29260  return SQLITE_OK;
29261}
29262
29263/*
29264** Clear the i-th bit.
29265**
29266** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
29267** that BitvecClear can use to rebuilt its hash table.
29268*/
29269SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
29270  if( p==0 ) return;
29271  assert( i>0 );
29272  i--;
29273  while( p->iDivisor ){
29274    u32 bin = i/p->iDivisor;
29275    i = i%p->iDivisor;
29276    p = p->u.apSub[bin];
29277    if (!p) {
29278      return;
29279    }
29280  }
29281  if( p->iSize<=BITVEC_NBIT ){
29282    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
29283  }else{
29284    unsigned int j;
29285    u32 *aiValues = pBuf;
29286    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
29287    memset(p->u.aHash, 0, sizeof(p->u.aHash));
29288    p->nSet = 0;
29289    for(j=0; j<BITVEC_NINT; j++){
29290      if( aiValues[j] && aiValues[j]!=(i+1) ){
29291        u32 h = BITVEC_HASH(aiValues[j]-1);
29292        p->nSet++;
29293        while( p->u.aHash[h] ){
29294          h++;
29295          if( h>=BITVEC_NINT ) h = 0;
29296        }
29297        p->u.aHash[h] = aiValues[j];
29298      }
29299    }
29300  }
29301}
29302
29303/*
29304** Destroy a bitmap object.  Reclaim all memory used.
29305*/
29306SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
29307  if( p==0 ) return;
29308  if( p->iDivisor ){
29309    unsigned int i;
29310    for(i=0; i<BITVEC_NPTR; i++){
29311      sqlite3BitvecDestroy(p->u.apSub[i]);
29312    }
29313  }
29314  sqlite3_free(p);
29315}
29316
29317/*
29318** Return the value of the iSize parameter specified when Bitvec *p
29319** was created.
29320*/
29321SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
29322  return p->iSize;
29323}
29324
29325#ifndef SQLITE_OMIT_BUILTIN_TEST
29326/*
29327** Let V[] be an array of unsigned characters sufficient to hold
29328** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
29329** Then the following macros can be used to set, clear, or test
29330** individual bits within V.
29331*/
29332#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
29333#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
29334#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
29335
29336/*
29337** This routine runs an extensive test of the Bitvec code.
29338**
29339** The input is an array of integers that acts as a program
29340** to test the Bitvec.  The integers are opcodes followed
29341** by 0, 1, or 3 operands, depending on the opcode.  Another
29342** opcode follows immediately after the last operand.
29343**
29344** There are 6 opcodes numbered from 0 through 5.  0 is the
29345** "halt" opcode and causes the test to end.
29346**
29347**    0          Halt and return the number of errors
29348**    1 N S X    Set N bits beginning with S and incrementing by X
29349**    2 N S X    Clear N bits beginning with S and incrementing by X
29350**    3 N        Set N randomly chosen bits
29351**    4 N        Clear N randomly chosen bits
29352**    5 N S X    Set N bits from S increment X in array only, not in bitvec
29353**
29354** The opcodes 1 through 4 perform set and clear operations are performed
29355** on both a Bitvec object and on a linear array of bits obtained from malloc.
29356** Opcode 5 works on the linear array only, not on the Bitvec.
29357** Opcode 5 is used to deliberately induce a fault in order to
29358** confirm that error detection works.
29359**
29360** At the conclusion of the test the linear array is compared
29361** against the Bitvec object.  If there are any differences,
29362** an error is returned.  If they are the same, zero is returned.
29363**
29364** If a memory allocation error occurs, return -1.
29365*/
29366SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
29367  Bitvec *pBitvec = 0;
29368  unsigned char *pV = 0;
29369  int rc = -1;
29370  int i, nx, pc, op;
29371  void *pTmpSpace;
29372
29373  /* Allocate the Bitvec to be tested and a linear array of
29374  ** bits to act as the reference */
29375  pBitvec = sqlite3BitvecCreate( sz );
29376  pV = sqlite3_malloc( (sz+7)/8 + 1 );
29377  pTmpSpace = sqlite3_malloc(BITVEC_SZ);
29378  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
29379  memset(pV, 0, (sz+7)/8 + 1);
29380
29381  /* NULL pBitvec tests */
29382  sqlite3BitvecSet(0, 1);
29383  sqlite3BitvecClear(0, 1, pTmpSpace);
29384
29385  /* Run the program */
29386  pc = 0;
29387  while( (op = aOp[pc])!=0 ){
29388    switch( op ){
29389      case 1:
29390      case 2:
29391      case 5: {
29392        nx = 4;
29393        i = aOp[pc+2] - 1;
29394        aOp[pc+2] += aOp[pc+3];
29395        break;
29396      }
29397      case 3:
29398      case 4:
29399      default: {
29400        nx = 2;
29401        sqlite3_randomness(sizeof(i), &i);
29402        break;
29403      }
29404    }
29405    if( (--aOp[pc+1]) > 0 ) nx = 0;
29406    pc += nx;
29407    i = (i & 0x7fffffff)%sz;
29408    if( (op & 1)!=0 ){
29409      SETBIT(pV, (i+1));
29410      if( op!=5 ){
29411        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
29412      }
29413    }else{
29414      CLEARBIT(pV, (i+1));
29415      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
29416    }
29417  }
29418
29419  /* Test to make sure the linear array exactly matches the
29420  ** Bitvec object.  Start with the assumption that they do
29421  ** match (rc==0).  Change rc to non-zero if a discrepancy
29422  ** is found.
29423  */
29424  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
29425          + sqlite3BitvecTest(pBitvec, 0)
29426          + (sqlite3BitvecSize(pBitvec) - sz);
29427  for(i=1; i<=sz; i++){
29428    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
29429      rc = i;
29430      break;
29431    }
29432  }
29433
29434  /* Free allocated structure */
29435bitvec_end:
29436  sqlite3_free(pTmpSpace);
29437  sqlite3_free(pV);
29438  sqlite3BitvecDestroy(pBitvec);
29439  return rc;
29440}
29441#endif /* SQLITE_OMIT_BUILTIN_TEST */
29442
29443/************** End of bitvec.c **********************************************/
29444/************** Begin file pcache.c ******************************************/
29445/*
29446** 2008 August 05
29447**
29448** The author disclaims copyright to this source code.  In place of
29449** a legal notice, here is a blessing:
29450**
29451**    May you do good and not evil.
29452**    May you find forgiveness for yourself and forgive others.
29453**    May you share freely, never taking more than you give.
29454**
29455*************************************************************************
29456** This file implements that page cache.
29457*/
29458
29459/*
29460** A complete page cache is an instance of this structure.
29461*/
29462struct PCache {
29463  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
29464  PgHdr *pSynced;                     /* Last synced page in dirty page list */
29465  int nRef;                           /* Number of referenced pages */
29466  int nMax;                           /* Configured cache size */
29467  int szPage;                         /* Size of every page in this cache */
29468  int szExtra;                        /* Size of extra space for each page */
29469  int bPurgeable;                     /* True if pages are on backing store */
29470  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
29471  void *pStress;                      /* Argument to xStress */
29472  sqlite3_pcache *pCache;             /* Pluggable cache module */
29473  PgHdr *pPage1;                      /* Reference to page 1 */
29474};
29475
29476/*
29477** Some of the assert() macros in this code are too expensive to run
29478** even during normal debugging.  Use them only rarely on long-running
29479** tests.  Enable the expensive asserts using the
29480** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
29481*/
29482#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
29483# define expensive_assert(X)  assert(X)
29484#else
29485# define expensive_assert(X)
29486#endif
29487
29488/********************************** Linked List Management ********************/
29489
29490#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
29491/*
29492** Check that the pCache->pSynced variable is set correctly. If it
29493** is not, either fail an assert or return zero. Otherwise, return
29494** non-zero. This is only used in debugging builds, as follows:
29495**
29496**   expensive_assert( pcacheCheckSynced(pCache) );
29497*/
29498static int pcacheCheckSynced(PCache *pCache){
29499  PgHdr *p;
29500  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
29501    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
29502  }
29503  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
29504}
29505#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
29506
29507/*
29508** Remove page pPage from the list of dirty pages.
29509*/
29510static void pcacheRemoveFromDirtyList(PgHdr *pPage){
29511  PCache *p = pPage->pCache;
29512
29513  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
29514  assert( pPage->pDirtyPrev || pPage==p->pDirty );
29515
29516  /* Update the PCache1.pSynced variable if necessary. */
29517  if( p->pSynced==pPage ){
29518    PgHdr *pSynced = pPage->pDirtyPrev;
29519    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
29520      pSynced = pSynced->pDirtyPrev;
29521    }
29522    p->pSynced = pSynced;
29523  }
29524
29525  if( pPage->pDirtyNext ){
29526    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
29527  }else{
29528    assert( pPage==p->pDirtyTail );
29529    p->pDirtyTail = pPage->pDirtyPrev;
29530  }
29531  if( pPage->pDirtyPrev ){
29532    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
29533  }else{
29534    assert( pPage==p->pDirty );
29535    p->pDirty = pPage->pDirtyNext;
29536  }
29537  pPage->pDirtyNext = 0;
29538  pPage->pDirtyPrev = 0;
29539
29540  expensive_assert( pcacheCheckSynced(p) );
29541}
29542
29543/*
29544** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
29545** pPage).
29546*/
29547static void pcacheAddToDirtyList(PgHdr *pPage){
29548  PCache *p = pPage->pCache;
29549
29550  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
29551
29552  pPage->pDirtyNext = p->pDirty;
29553  if( pPage->pDirtyNext ){
29554    assert( pPage->pDirtyNext->pDirtyPrev==0 );
29555    pPage->pDirtyNext->pDirtyPrev = pPage;
29556  }
29557  p->pDirty = pPage;
29558  if( !p->pDirtyTail ){
29559    p->pDirtyTail = pPage;
29560  }
29561  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
29562    p->pSynced = pPage;
29563  }
29564  expensive_assert( pcacheCheckSynced(p) );
29565}
29566
29567/*
29568** Wrapper around the pluggable caches xUnpin method. If the cache is
29569** being used for an in-memory database, this function is a no-op.
29570*/
29571static void pcacheUnpin(PgHdr *p){
29572  PCache *pCache = p->pCache;
29573  if( pCache->bPurgeable ){
29574    if( p->pgno==1 ){
29575      pCache->pPage1 = 0;
29576    }
29577    sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
29578  }
29579}
29580
29581/*************************************************** General Interfaces ******
29582**
29583** Initialize and shutdown the page cache subsystem. Neither of these
29584** functions are threadsafe.
29585*/
29586SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
29587  if( sqlite3GlobalConfig.pcache.xInit==0 ){
29588    sqlite3PCacheSetDefault();
29589  }
29590  return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
29591}
29592SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
29593  if( sqlite3GlobalConfig.pcache.xShutdown ){
29594    sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
29595  }
29596}
29597
29598/*
29599** Return the size in bytes of a PCache object.
29600*/
29601SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
29602
29603/*
29604** Create a new PCache object. Storage space to hold the object
29605** has already been allocated and is passed in as the p pointer.
29606** The caller discovers how much space needs to be allocated by
29607** calling sqlite3PcacheSize().
29608*/
29609SQLITE_PRIVATE void sqlite3PcacheOpen(
29610  int szPage,                  /* Size of every page */
29611  int szExtra,                 /* Extra space associated with each page */
29612  int bPurgeable,              /* True if pages are on backing store */
29613  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
29614  void *pStress,               /* Argument to xStress */
29615  PCache *p                    /* Preallocated space for the PCache */
29616){
29617  memset(p, 0, sizeof(PCache));
29618  p->szPage = szPage;
29619  p->szExtra = szExtra;
29620  p->bPurgeable = bPurgeable;
29621  p->xStress = xStress;
29622  p->pStress = pStress;
29623  p->nMax = 100;
29624}
29625
29626/*
29627** Change the page size for PCache object. The caller must ensure that there
29628** are no outstanding page references when this function is called.
29629*/
29630SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
29631  assert( pCache->nRef==0 && pCache->pDirty==0 );
29632  if( pCache->pCache ){
29633    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
29634    pCache->pCache = 0;
29635  }
29636  pCache->szPage = szPage;
29637}
29638
29639/*
29640** Try to obtain a page from the cache.
29641*/
29642SQLITE_PRIVATE int sqlite3PcacheFetch(
29643  PCache *pCache,       /* Obtain the page from this cache */
29644  Pgno pgno,            /* Page number to obtain */
29645  int createFlag,       /* If true, create page if it does not exist already */
29646  PgHdr **ppPage        /* Write the page here */
29647){
29648  PgHdr *pPage = 0;
29649  int eCreate;
29650
29651  assert( pCache!=0 );
29652  assert( createFlag==1 || createFlag==0 );
29653  assert( pgno>0 );
29654
29655  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
29656  ** allocate it now.
29657  */
29658  if( !pCache->pCache && createFlag ){
29659    sqlite3_pcache *p;
29660    int nByte;
29661    nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
29662    p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
29663    if( !p ){
29664      return SQLITE_NOMEM;
29665    }
29666    sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
29667    pCache->pCache = p;
29668  }
29669
29670  eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
29671  if( pCache->pCache ){
29672    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
29673  }
29674
29675  if( !pPage && eCreate==1 ){
29676    PgHdr *pPg;
29677
29678    /* Find a dirty page to write-out and recycle. First try to find a
29679    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
29680    ** cleared), but if that is not possible settle for any other
29681    ** unreferenced dirty page.
29682    */
29683    expensive_assert( pcacheCheckSynced(pCache) );
29684    for(pPg=pCache->pSynced;
29685        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
29686        pPg=pPg->pDirtyPrev
29687    );
29688    if( !pPg ){
29689      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
29690    }
29691    if( pPg ){
29692      int rc;
29693      rc = pCache->xStress(pCache->pStress, pPg);
29694      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
29695        return rc;
29696      }
29697    }
29698
29699    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
29700  }
29701
29702  if( pPage ){
29703    if( !pPage->pData ){
29704      memset(pPage, 0, sizeof(PgHdr) + pCache->szExtra);
29705      pPage->pExtra = (void*)&pPage[1];
29706      pPage->pData = (void *)&((char *)pPage)[sizeof(PgHdr) + pCache->szExtra];
29707      pPage->pCache = pCache;
29708      pPage->pgno = pgno;
29709    }
29710    assert( pPage->pCache==pCache );
29711    assert( pPage->pgno==pgno );
29712    assert( pPage->pExtra==(void *)&pPage[1] );
29713
29714    if( 0==pPage->nRef ){
29715      pCache->nRef++;
29716    }
29717    pPage->nRef++;
29718    if( pgno==1 ){
29719      pCache->pPage1 = pPage;
29720    }
29721  }
29722  *ppPage = pPage;
29723  return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
29724}
29725
29726/*
29727** Decrement the reference count on a page. If the page is clean and the
29728** reference count drops to 0, then it is made elible for recycling.
29729*/
29730SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
29731  assert( p->nRef>0 );
29732  p->nRef--;
29733  if( p->nRef==0 ){
29734    PCache *pCache = p->pCache;
29735    pCache->nRef--;
29736    if( (p->flags&PGHDR_DIRTY)==0 ){
29737      pcacheUnpin(p);
29738    }else{
29739      /* Move the page to the head of the dirty list. */
29740      pcacheRemoveFromDirtyList(p);
29741      pcacheAddToDirtyList(p);
29742    }
29743  }
29744}
29745
29746/*
29747** Increase the reference count of a supplied page by 1.
29748*/
29749SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
29750  assert(p->nRef>0);
29751  p->nRef++;
29752}
29753
29754/*
29755** Drop a page from the cache. There must be exactly one reference to the
29756** page. This function deletes that reference, so after it returns the
29757** page pointed to by p is invalid.
29758*/
29759SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
29760  PCache *pCache;
29761  assert( p->nRef==1 );
29762  if( p->flags&PGHDR_DIRTY ){
29763    pcacheRemoveFromDirtyList(p);
29764  }
29765  pCache = p->pCache;
29766  pCache->nRef--;
29767  if( p->pgno==1 ){
29768    pCache->pPage1 = 0;
29769  }
29770  sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
29771}
29772
29773/*
29774** Make sure the page is marked as dirty. If it isn't dirty already,
29775** make it so.
29776*/
29777SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
29778  p->flags &= ~PGHDR_DONT_WRITE;
29779  assert( p->nRef>0 );
29780  if( 0==(p->flags & PGHDR_DIRTY) ){
29781    p->flags |= PGHDR_DIRTY;
29782    pcacheAddToDirtyList( p);
29783  }
29784}
29785
29786/*
29787** Make sure the page is marked as clean. If it isn't clean already,
29788** make it so.
29789*/
29790SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
29791  if( (p->flags & PGHDR_DIRTY) ){
29792    pcacheRemoveFromDirtyList(p);
29793    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
29794    if( p->nRef==0 ){
29795      pcacheUnpin(p);
29796    }
29797  }
29798}
29799
29800/*
29801** Make every page in the cache clean.
29802*/
29803SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
29804  PgHdr *p;
29805  while( (p = pCache->pDirty)!=0 ){
29806    sqlite3PcacheMakeClean(p);
29807  }
29808}
29809
29810/*
29811** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
29812*/
29813SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
29814  PgHdr *p;
29815  for(p=pCache->pDirty; p; p=p->pDirtyNext){
29816    p->flags &= ~PGHDR_NEED_SYNC;
29817  }
29818  pCache->pSynced = pCache->pDirtyTail;
29819}
29820
29821/*
29822** Change the page number of page p to newPgno.
29823*/
29824SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
29825  PCache *pCache = p->pCache;
29826  assert( p->nRef>0 );
29827  assert( newPgno>0 );
29828  sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
29829  p->pgno = newPgno;
29830  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
29831    pcacheRemoveFromDirtyList(p);
29832    pcacheAddToDirtyList(p);
29833  }
29834}
29835
29836/*
29837** Drop every cache entry whose page number is greater than "pgno". The
29838** caller must ensure that there are no outstanding references to any pages
29839** other than page 1 with a page number greater than pgno.
29840**
29841** If there is a reference to page 1 and the pgno parameter passed to this
29842** function is 0, then the data area associated with page 1 is zeroed, but
29843** the page object is not dropped.
29844*/
29845SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
29846  if( pCache->pCache ){
29847    PgHdr *p;
29848    PgHdr *pNext;
29849    for(p=pCache->pDirty; p; p=pNext){
29850      pNext = p->pDirtyNext;
29851      if( p->pgno>pgno ){
29852        assert( p->flags&PGHDR_DIRTY );
29853        sqlite3PcacheMakeClean(p);
29854      }
29855    }
29856    if( pgno==0 && pCache->pPage1 ){
29857      memset(pCache->pPage1->pData, 0, pCache->szPage);
29858      pgno = 1;
29859    }
29860    sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
29861  }
29862}
29863
29864/*
29865** Close a cache.
29866*/
29867SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
29868  if( pCache->pCache ){
29869    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
29870  }
29871}
29872
29873/*
29874** Discard the contents of the cache.
29875*/
29876SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
29877  sqlite3PcacheTruncate(pCache, 0);
29878}
29879
29880/*
29881** Merge two lists of pages connected by pDirty and in pgno order.
29882** Do not both fixing the pDirtyPrev pointers.
29883*/
29884static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
29885  PgHdr result, *pTail;
29886  pTail = &result;
29887  while( pA && pB ){
29888    if( pA->pgno<pB->pgno ){
29889      pTail->pDirty = pA;
29890      pTail = pA;
29891      pA = pA->pDirty;
29892    }else{
29893      pTail->pDirty = pB;
29894      pTail = pB;
29895      pB = pB->pDirty;
29896    }
29897  }
29898  if( pA ){
29899    pTail->pDirty = pA;
29900  }else if( pB ){
29901    pTail->pDirty = pB;
29902  }else{
29903    pTail->pDirty = 0;
29904  }
29905  return result.pDirty;
29906}
29907
29908/*
29909** Sort the list of pages in accending order by pgno.  Pages are
29910** connected by pDirty pointers.  The pDirtyPrev pointers are
29911** corrupted by this sort.
29912**
29913** Since there cannot be more than 2^31 distinct pages in a database,
29914** there cannot be more than 31 buckets required by the merge sorter.
29915** One extra bucket is added to catch overflow in case something
29916** ever changes to make the previous sentence incorrect.
29917*/
29918#define N_SORT_BUCKET  32
29919static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
29920  PgHdr *a[N_SORT_BUCKET], *p;
29921  int i;
29922  memset(a, 0, sizeof(a));
29923  while( pIn ){
29924    p = pIn;
29925    pIn = p->pDirty;
29926    p->pDirty = 0;
29927    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
29928      if( a[i]==0 ){
29929        a[i] = p;
29930        break;
29931      }else{
29932        p = pcacheMergeDirtyList(a[i], p);
29933        a[i] = 0;
29934      }
29935    }
29936    if( NEVER(i==N_SORT_BUCKET-1) ){
29937      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
29938      ** the input list.  But that is impossible.
29939      */
29940      a[i] = pcacheMergeDirtyList(a[i], p);
29941    }
29942  }
29943  p = a[0];
29944  for(i=1; i<N_SORT_BUCKET; i++){
29945    p = pcacheMergeDirtyList(p, a[i]);
29946  }
29947  return p;
29948}
29949
29950/*
29951** Return a list of all dirty pages in the cache, sorted by page number.
29952*/
29953SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
29954  PgHdr *p;
29955  for(p=pCache->pDirty; p; p=p->pDirtyNext){
29956    p->pDirty = p->pDirtyNext;
29957  }
29958  return pcacheSortDirtyList(pCache->pDirty);
29959}
29960
29961/*
29962** Return the total number of referenced pages held by the cache.
29963*/
29964SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
29965  return pCache->nRef;
29966}
29967
29968/*
29969** Return the number of references to the page supplied as an argument.
29970*/
29971SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
29972  return p->nRef;
29973}
29974
29975/*
29976** Return the total number of pages in the cache.
29977*/
29978SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
29979  int nPage = 0;
29980  if( pCache->pCache ){
29981    nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
29982  }
29983  return nPage;
29984}
29985
29986#ifdef SQLITE_TEST
29987/*
29988** Get the suggested cache-size value.
29989*/
29990SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
29991  return pCache->nMax;
29992}
29993#endif
29994
29995/*
29996** Set the suggested cache-size value.
29997*/
29998SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
29999  pCache->nMax = mxPage;
30000  if( pCache->pCache ){
30001    sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
30002  }
30003}
30004
30005#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
30006/*
30007** For all dirty pages currently in the cache, invoke the specified
30008** callback. This is only used if the SQLITE_CHECK_PAGES macro is
30009** defined.
30010*/
30011SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
30012  PgHdr *pDirty;
30013  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
30014    xIter(pDirty);
30015  }
30016}
30017#endif
30018
30019/************** End of pcache.c **********************************************/
30020/************** Begin file pcache1.c *****************************************/
30021/*
30022** 2008 November 05
30023**
30024** The author disclaims copyright to this source code.  In place of
30025** a legal notice, here is a blessing:
30026**
30027**    May you do good and not evil.
30028**    May you find forgiveness for yourself and forgive others.
30029**    May you share freely, never taking more than you give.
30030**
30031*************************************************************************
30032**
30033** This file implements the default page cache implementation (the
30034** sqlite3_pcache interface). It also contains part of the implementation
30035** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
30036** If the default page cache implementation is overriden, then neither of
30037** these two features are available.
30038*/
30039
30040
30041typedef struct PCache1 PCache1;
30042typedef struct PgHdr1 PgHdr1;
30043typedef struct PgFreeslot PgFreeslot;
30044
30045/* Pointers to structures of this type are cast and returned as
30046** opaque sqlite3_pcache* handles
30047*/
30048struct PCache1 {
30049  /* Cache configuration parameters. Page size (szPage) and the purgeable
30050  ** flag (bPurgeable) are set when the cache is created. nMax may be
30051  ** modified at any time by a call to the pcache1CacheSize() method.
30052  ** The global mutex must be held when accessing nMax.
30053  */
30054  int szPage;                         /* Size of allocated pages in bytes */
30055  int bPurgeable;                     /* True if cache is purgeable */
30056  unsigned int nMin;                  /* Minimum number of pages reserved */
30057  unsigned int nMax;                  /* Configured "cache_size" value */
30058
30059  /* Hash table of all pages. The following variables may only be accessed
30060  ** when the accessor is holding the global mutex (see pcache1EnterMutex()
30061  ** and pcache1LeaveMutex()).
30062  */
30063  unsigned int nRecyclable;           /* Number of pages in the LRU list */
30064  unsigned int nPage;                 /* Total number of pages in apHash */
30065  unsigned int nHash;                 /* Number of slots in apHash[] */
30066  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
30067
30068  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
30069};
30070
30071/*
30072** Each cache entry is represented by an instance of the following
30073** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
30074** directly before this structure in memory (see the PGHDR1_TO_PAGE()
30075** macro below).
30076*/
30077struct PgHdr1 {
30078  unsigned int iKey;             /* Key value (page number) */
30079  PgHdr1 *pNext;                 /* Next in hash table chain */
30080  PCache1 *pCache;               /* Cache that currently owns this page */
30081  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
30082  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
30083};
30084
30085/*
30086** Free slots in the allocator used to divide up the buffer provided using
30087** the SQLITE_CONFIG_PAGECACHE mechanism.
30088*/
30089struct PgFreeslot {
30090  PgFreeslot *pNext;  /* Next free slot */
30091};
30092
30093/*
30094** Global data used by this cache.
30095*/
30096static SQLITE_WSD struct PCacheGlobal {
30097  sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
30098
30099  int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
30100  int nMinPage;                       /* Sum of nMinPage for purgeable caches */
30101  int nCurrentPage;                   /* Number of purgeable pages allocated */
30102  PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
30103
30104  /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
30105  int szSlot;                         /* Size of each free slot */
30106  void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
30107  PgFreeslot *pFree;                  /* Free page blocks */
30108  int isInit;                         /* True if initialized */
30109} pcache1_g;
30110
30111/*
30112** All code in this file should access the global structure above via the
30113** alias "pcache1". This ensures that the WSD emulation is used when
30114** compiling for systems that do not support real WSD.
30115*/
30116#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
30117
30118/*
30119** When a PgHdr1 structure is allocated, the associated PCache1.szPage
30120** bytes of data are located directly before it in memory (i.e. the total
30121** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
30122** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
30123** an argument and returns a pointer to the associated block of szPage
30124** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
30125** a pointer to a block of szPage bytes of data and the return value is
30126** a pointer to the associated PgHdr1 structure.
30127**
30128**   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
30129*/
30130#define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
30131#define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
30132
30133/*
30134** Macros to enter and leave the global LRU mutex.
30135*/
30136#define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
30137#define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
30138
30139/******************************************************************************/
30140/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
30141
30142/*
30143** This function is called during initialization if a static buffer is
30144** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
30145** verb to sqlite3_config(). Parameter pBuf points to an allocation large
30146** enough to contain 'n' buffers of 'sz' bytes each.
30147*/
30148SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
30149  if( pcache1.isInit ){
30150    PgFreeslot *p;
30151    sz = ROUNDDOWN8(sz);
30152    pcache1.szSlot = sz;
30153    pcache1.pStart = pBuf;
30154    pcache1.pFree = 0;
30155    while( n-- ){
30156      p = (PgFreeslot*)pBuf;
30157      p->pNext = pcache1.pFree;
30158      pcache1.pFree = p;
30159      pBuf = (void*)&((char*)pBuf)[sz];
30160    }
30161    pcache1.pEnd = pBuf;
30162  }
30163}
30164
30165/*
30166** Malloc function used within this file to allocate space from the buffer
30167** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
30168** such buffer exists or there is no space left in it, this function falls
30169** back to sqlite3Malloc().
30170*/
30171static void *pcache1Alloc(int nByte){
30172  void *p;
30173  assert( sqlite3_mutex_held(pcache1.mutex) );
30174  if( nByte<=pcache1.szSlot && pcache1.pFree ){
30175    assert( pcache1.isInit );
30176    p = (PgHdr1 *)pcache1.pFree;
30177    pcache1.pFree = pcache1.pFree->pNext;
30178    sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
30179    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
30180  }else{
30181
30182    /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
30183    ** global pcache mutex and unlock the pager-cache object pCache. This is
30184    ** so that if the attempt to allocate a new buffer causes the the
30185    ** configured soft-heap-limit to be breached, it will be possible to
30186    ** reclaim memory from this pager-cache.
30187    */
30188    pcache1LeaveMutex();
30189    p = sqlite3Malloc(nByte);
30190    pcache1EnterMutex();
30191    if( p ){
30192      int sz = sqlite3MallocSize(p);
30193      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
30194    }
30195  }
30196  return p;
30197}
30198
30199/*
30200** Free an allocated buffer obtained from pcache1Alloc().
30201*/
30202static void pcache1Free(void *p){
30203  assert( sqlite3_mutex_held(pcache1.mutex) );
30204  if( p==0 ) return;
30205  if( p>=pcache1.pStart && p<pcache1.pEnd ){
30206    PgFreeslot *pSlot;
30207    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
30208    pSlot = (PgFreeslot*)p;
30209    pSlot->pNext = pcache1.pFree;
30210    pcache1.pFree = pSlot;
30211  }else{
30212    int iSize = sqlite3MallocSize(p);
30213    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
30214    sqlite3_free(p);
30215  }
30216}
30217
30218/*
30219** Allocate a new page object initially associated with cache pCache.
30220*/
30221static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
30222  int nByte = sizeof(PgHdr1) + pCache->szPage;
30223  void *pPg = pcache1Alloc(nByte);
30224  PgHdr1 *p;
30225  if( pPg ){
30226    p = PAGE_TO_PGHDR1(pCache, pPg);
30227    if( pCache->bPurgeable ){
30228      pcache1.nCurrentPage++;
30229    }
30230  }else{
30231    p = 0;
30232  }
30233  return p;
30234}
30235
30236/*
30237** Free a page object allocated by pcache1AllocPage().
30238**
30239** The pointer is allowed to be NULL, which is prudent.  But it turns out
30240** that the current implementation happens to never call this routine
30241** with a NULL pointer, so we mark the NULL test with ALWAYS().
30242*/
30243static void pcache1FreePage(PgHdr1 *p){
30244  if( ALWAYS(p) ){
30245    if( p->pCache->bPurgeable ){
30246      pcache1.nCurrentPage--;
30247    }
30248    pcache1Free(PGHDR1_TO_PAGE(p));
30249  }
30250}
30251
30252/*
30253** Malloc function used by SQLite to obtain space from the buffer configured
30254** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
30255** exists, this function falls back to sqlite3Malloc().
30256*/
30257SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
30258  void *p;
30259  pcache1EnterMutex();
30260  p = pcache1Alloc(sz);
30261  pcache1LeaveMutex();
30262  return p;
30263}
30264
30265/*
30266** Free an allocated buffer obtained from sqlite3PageMalloc().
30267*/
30268SQLITE_PRIVATE void sqlite3PageFree(void *p){
30269  pcache1EnterMutex();
30270  pcache1Free(p);
30271  pcache1LeaveMutex();
30272}
30273
30274/******************************************************************************/
30275/******** General Implementation Functions ************************************/
30276
30277/*
30278** This function is used to resize the hash table used by the cache passed
30279** as the first argument.
30280**
30281** The global mutex must be held when this function is called.
30282*/
30283static int pcache1ResizeHash(PCache1 *p){
30284  PgHdr1 **apNew;
30285  unsigned int nNew;
30286  unsigned int i;
30287
30288  assert( sqlite3_mutex_held(pcache1.mutex) );
30289
30290  nNew = p->nHash*2;
30291  if( nNew<256 ){
30292    nNew = 256;
30293  }
30294
30295  pcache1LeaveMutex();
30296  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
30297  apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
30298  if( p->nHash ){ sqlite3EndBenignMalloc(); }
30299  pcache1EnterMutex();
30300  if( apNew ){
30301    memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
30302    for(i=0; i<p->nHash; i++){
30303      PgHdr1 *pPage;
30304      PgHdr1 *pNext = p->apHash[i];
30305      while( (pPage = pNext)!=0 ){
30306        unsigned int h = pPage->iKey % nNew;
30307        pNext = pPage->pNext;
30308        pPage->pNext = apNew[h];
30309        apNew[h] = pPage;
30310      }
30311    }
30312    sqlite3_free(p->apHash);
30313    p->apHash = apNew;
30314    p->nHash = nNew;
30315  }
30316
30317  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
30318}
30319
30320/*
30321** This function is used internally to remove the page pPage from the
30322** global LRU list, if is part of it. If pPage is not part of the global
30323** LRU list, then this function is a no-op.
30324**
30325** The global mutex must be held when this function is called.
30326*/
30327static void pcache1PinPage(PgHdr1 *pPage){
30328  assert( sqlite3_mutex_held(pcache1.mutex) );
30329  if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
30330    if( pPage->pLruPrev ){
30331      pPage->pLruPrev->pLruNext = pPage->pLruNext;
30332    }
30333    if( pPage->pLruNext ){
30334      pPage->pLruNext->pLruPrev = pPage->pLruPrev;
30335    }
30336    if( pcache1.pLruHead==pPage ){
30337      pcache1.pLruHead = pPage->pLruNext;
30338    }
30339    if( pcache1.pLruTail==pPage ){
30340      pcache1.pLruTail = pPage->pLruPrev;
30341    }
30342    pPage->pLruNext = 0;
30343    pPage->pLruPrev = 0;
30344    pPage->pCache->nRecyclable--;
30345  }
30346}
30347
30348
30349/*
30350** Remove the page supplied as an argument from the hash table
30351** (PCache1.apHash structure) that it is currently stored in.
30352**
30353** The global mutex must be held when this function is called.
30354*/
30355static void pcache1RemoveFromHash(PgHdr1 *pPage){
30356  unsigned int h;
30357  PCache1 *pCache = pPage->pCache;
30358  PgHdr1 **pp;
30359
30360  h = pPage->iKey % pCache->nHash;
30361  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
30362  *pp = (*pp)->pNext;
30363
30364  pCache->nPage--;
30365}
30366
30367/*
30368** If there are currently more than pcache.nMaxPage pages allocated, try
30369** to recycle pages to reduce the number allocated to pcache.nMaxPage.
30370*/
30371static void pcache1EnforceMaxPage(void){
30372  assert( sqlite3_mutex_held(pcache1.mutex) );
30373  while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
30374    PgHdr1 *p = pcache1.pLruTail;
30375    pcache1PinPage(p);
30376    pcache1RemoveFromHash(p);
30377    pcache1FreePage(p);
30378  }
30379}
30380
30381/*
30382** Discard all pages from cache pCache with a page number (key value)
30383** greater than or equal to iLimit. Any pinned pages that meet this
30384** criteria are unpinned before they are discarded.
30385**
30386** The global mutex must be held when this function is called.
30387*/
30388static void pcache1TruncateUnsafe(
30389  PCache1 *pCache,
30390  unsigned int iLimit
30391){
30392  TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
30393  unsigned int h;
30394  assert( sqlite3_mutex_held(pcache1.mutex) );
30395  for(h=0; h<pCache->nHash; h++){
30396    PgHdr1 **pp = &pCache->apHash[h];
30397    PgHdr1 *pPage;
30398    while( (pPage = *pp)!=0 ){
30399      if( pPage->iKey>=iLimit ){
30400        pCache->nPage--;
30401        *pp = pPage->pNext;
30402        pcache1PinPage(pPage);
30403        pcache1FreePage(pPage);
30404      }else{
30405        pp = &pPage->pNext;
30406        TESTONLY( nPage++; )
30407      }
30408    }
30409  }
30410  assert( pCache->nPage==nPage );
30411}
30412
30413/******************************************************************************/
30414/******** sqlite3_pcache Methods **********************************************/
30415
30416/*
30417** Implementation of the sqlite3_pcache.xInit method.
30418*/
30419static int pcache1Init(void *NotUsed){
30420  UNUSED_PARAMETER(NotUsed);
30421  assert( pcache1.isInit==0 );
30422  memset(&pcache1, 0, sizeof(pcache1));
30423  if( sqlite3GlobalConfig.bCoreMutex ){
30424    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
30425  }
30426  pcache1.isInit = 1;
30427  return SQLITE_OK;
30428}
30429
30430/*
30431** Implementation of the sqlite3_pcache.xShutdown method.
30432** Note that the static mutex allocated in xInit does
30433** not need to be freed.
30434*/
30435static void pcache1Shutdown(void *NotUsed){
30436  UNUSED_PARAMETER(NotUsed);
30437  assert( pcache1.isInit!=0 );
30438  memset(&pcache1, 0, sizeof(pcache1));
30439}
30440
30441/*
30442** Implementation of the sqlite3_pcache.xCreate method.
30443**
30444** Allocate a new cache.
30445*/
30446static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
30447  PCache1 *pCache;
30448
30449  pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
30450  if( pCache ){
30451    memset(pCache, 0, sizeof(PCache1));
30452    pCache->szPage = szPage;
30453    pCache->bPurgeable = (bPurgeable ? 1 : 0);
30454    if( bPurgeable ){
30455      pCache->nMin = 10;
30456      pcache1EnterMutex();
30457      pcache1.nMinPage += pCache->nMin;
30458      pcache1LeaveMutex();
30459    }
30460  }
30461  return (sqlite3_pcache *)pCache;
30462}
30463
30464/*
30465** Implementation of the sqlite3_pcache.xCachesize method.
30466**
30467** Configure the cache_size limit for a cache.
30468*/
30469static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
30470  PCache1 *pCache = (PCache1 *)p;
30471  if( pCache->bPurgeable ){
30472    pcache1EnterMutex();
30473    pcache1.nMaxPage += (nMax - pCache->nMax);
30474    pCache->nMax = nMax;
30475    pcache1EnforceMaxPage();
30476    pcache1LeaveMutex();
30477  }
30478}
30479
30480/*
30481** Implementation of the sqlite3_pcache.xPagecount method.
30482*/
30483static int pcache1Pagecount(sqlite3_pcache *p){
30484  int n;
30485  pcache1EnterMutex();
30486  n = ((PCache1 *)p)->nPage;
30487  pcache1LeaveMutex();
30488  return n;
30489}
30490
30491/*
30492** Implementation of the sqlite3_pcache.xFetch method.
30493**
30494** Fetch a page by key value.
30495**
30496** Whether or not a new page may be allocated by this function depends on
30497** the value of the createFlag argument.  0 means do not allocate a new
30498** page.  1 means allocate a new page if space is easily available.  2
30499** means to try really hard to allocate a new page.
30500**
30501** For a non-purgeable cache (a cache used as the storage for an in-memory
30502** database) there is really no difference between createFlag 1 and 2.  So
30503** the calling function (pcache.c) will never have a createFlag of 1 on
30504** a non-purgable cache.
30505**
30506** There are three different approaches to obtaining space for a page,
30507** depending on the value of parameter createFlag (which may be 0, 1 or 2).
30508**
30509**   1. Regardless of the value of createFlag, the cache is searched for a
30510**      copy of the requested page. If one is found, it is returned.
30511**
30512**   2. If createFlag==0 and the page is not already in the cache, NULL is
30513**      returned.
30514**
30515**   3. If createFlag is 1, and the page is not already in the cache,
30516**      and if either of the following are true, return NULL:
30517**
30518**       (a) the number of pages pinned by the cache is greater than
30519**           PCache1.nMax, or
30520**       (b) the number of pages pinned by the cache is greater than
30521**           the sum of nMax for all purgeable caches, less the sum of
30522**           nMin for all other purgeable caches.
30523**
30524**   4. If none of the first three conditions apply and the cache is marked
30525**      as purgeable, and if one of the following is true:
30526**
30527**       (a) The number of pages allocated for the cache is already
30528**           PCache1.nMax, or
30529**
30530**       (b) The number of pages allocated for all purgeable caches is
30531**           already equal to or greater than the sum of nMax for all
30532**           purgeable caches,
30533**
30534**      then attempt to recycle a page from the LRU list. If it is the right
30535**      size, return the recycled buffer. Otherwise, free the buffer and
30536**      proceed to step 5.
30537**
30538**   5. Otherwise, allocate and return a new page buffer.
30539*/
30540static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
30541  unsigned int nPinned;
30542  PCache1 *pCache = (PCache1 *)p;
30543  PgHdr1 *pPage = 0;
30544
30545  assert( pCache->bPurgeable || createFlag!=1 );
30546  pcache1EnterMutex();
30547  if( createFlag==1 ) sqlite3BeginBenignMalloc();
30548
30549  /* Search the hash table for an existing entry. */
30550  if( pCache->nHash>0 ){
30551    unsigned int h = iKey % pCache->nHash;
30552    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
30553  }
30554
30555  if( pPage || createFlag==0 ){
30556    pcache1PinPage(pPage);
30557    goto fetch_out;
30558  }
30559
30560  /* Step 3 of header comment. */
30561  nPinned = pCache->nPage - pCache->nRecyclable;
30562  if( createFlag==1 && (
30563        nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
30564     || nPinned>=(pCache->nMax * 9 / 10)
30565  )){
30566    goto fetch_out;
30567  }
30568
30569  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
30570    goto fetch_out;
30571  }
30572
30573  /* Step 4. Try to recycle a page buffer if appropriate. */
30574  if( pCache->bPurgeable && pcache1.pLruTail && (
30575     (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
30576  )){
30577    pPage = pcache1.pLruTail;
30578    pcache1RemoveFromHash(pPage);
30579    pcache1PinPage(pPage);
30580    if( pPage->pCache->szPage!=pCache->szPage ){
30581      pcache1FreePage(pPage);
30582      pPage = 0;
30583    }else{
30584      pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
30585    }
30586  }
30587
30588  /* Step 5. If a usable page buffer has still not been found,
30589  ** attempt to allocate a new one.
30590  */
30591  if( !pPage ){
30592    pPage = pcache1AllocPage(pCache);
30593  }
30594
30595  if( pPage ){
30596    unsigned int h = iKey % pCache->nHash;
30597    pCache->nPage++;
30598    pPage->iKey = iKey;
30599    pPage->pNext = pCache->apHash[h];
30600    pPage->pCache = pCache;
30601    pPage->pLruPrev = 0;
30602    pPage->pLruNext = 0;
30603    *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
30604    pCache->apHash[h] = pPage;
30605  }
30606
30607fetch_out:
30608  if( pPage && iKey>pCache->iMaxKey ){
30609    pCache->iMaxKey = iKey;
30610  }
30611  if( createFlag==1 ) sqlite3EndBenignMalloc();
30612  pcache1LeaveMutex();
30613  return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
30614}
30615
30616
30617/*
30618** Implementation of the sqlite3_pcache.xUnpin method.
30619**
30620** Mark a page as unpinned (eligible for asynchronous recycling).
30621*/
30622static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
30623  PCache1 *pCache = (PCache1 *)p;
30624  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
30625
30626  assert( pPage->pCache==pCache );
30627  pcache1EnterMutex();
30628
30629  /* It is an error to call this function if the page is already
30630  ** part of the global LRU list.
30631  */
30632  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
30633  assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
30634
30635  if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
30636    pcache1RemoveFromHash(pPage);
30637    pcache1FreePage(pPage);
30638  }else{
30639    /* Add the page to the global LRU list. Normally, the page is added to
30640    ** the head of the list (last page to be recycled). However, if the
30641    ** reuseUnlikely flag passed to this function is true, the page is added
30642    ** to the tail of the list (first page to be recycled).
30643    */
30644    if( pcache1.pLruHead ){
30645      pcache1.pLruHead->pLruPrev = pPage;
30646      pPage->pLruNext = pcache1.pLruHead;
30647      pcache1.pLruHead = pPage;
30648    }else{
30649      pcache1.pLruTail = pPage;
30650      pcache1.pLruHead = pPage;
30651    }
30652    pCache->nRecyclable++;
30653  }
30654
30655  pcache1LeaveMutex();
30656}
30657
30658/*
30659** Implementation of the sqlite3_pcache.xRekey method.
30660*/
30661static void pcache1Rekey(
30662  sqlite3_pcache *p,
30663  void *pPg,
30664  unsigned int iOld,
30665  unsigned int iNew
30666){
30667  PCache1 *pCache = (PCache1 *)p;
30668  PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
30669  PgHdr1 **pp;
30670  unsigned int h;
30671  assert( pPage->iKey==iOld );
30672  assert( pPage->pCache==pCache );
30673
30674  pcache1EnterMutex();
30675
30676  h = iOld%pCache->nHash;
30677  pp = &pCache->apHash[h];
30678  while( (*pp)!=pPage ){
30679    pp = &(*pp)->pNext;
30680  }
30681  *pp = pPage->pNext;
30682
30683  h = iNew%pCache->nHash;
30684  pPage->iKey = iNew;
30685  pPage->pNext = pCache->apHash[h];
30686  pCache->apHash[h] = pPage;
30687  if( iNew>pCache->iMaxKey ){
30688    pCache->iMaxKey = iNew;
30689  }
30690
30691  pcache1LeaveMutex();
30692}
30693
30694/*
30695** Implementation of the sqlite3_pcache.xTruncate method.
30696**
30697** Discard all unpinned pages in the cache with a page number equal to
30698** or greater than parameter iLimit. Any pinned pages with a page number
30699** equal to or greater than iLimit are implicitly unpinned.
30700*/
30701static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
30702  PCache1 *pCache = (PCache1 *)p;
30703  pcache1EnterMutex();
30704  if( iLimit<=pCache->iMaxKey ){
30705    pcache1TruncateUnsafe(pCache, iLimit);
30706    pCache->iMaxKey = iLimit-1;
30707  }
30708  pcache1LeaveMutex();
30709}
30710
30711/*
30712** Implementation of the sqlite3_pcache.xDestroy method.
30713**
30714** Destroy a cache allocated using pcache1Create().
30715*/
30716static void pcache1Destroy(sqlite3_pcache *p){
30717  PCache1 *pCache = (PCache1 *)p;
30718  pcache1EnterMutex();
30719  pcache1TruncateUnsafe(pCache, 0);
30720  pcache1.nMaxPage -= pCache->nMax;
30721  pcache1.nMinPage -= pCache->nMin;
30722  pcache1EnforceMaxPage();
30723  pcache1LeaveMutex();
30724  sqlite3_free(pCache->apHash);
30725  sqlite3_free(pCache);
30726}
30727
30728/*
30729** This function is called during initialization (sqlite3_initialize()) to
30730** install the default pluggable cache module, assuming the user has not
30731** already provided an alternative.
30732*/
30733SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
30734  static sqlite3_pcache_methods defaultMethods = {
30735    0,                       /* pArg */
30736    pcache1Init,             /* xInit */
30737    pcache1Shutdown,         /* xShutdown */
30738    pcache1Create,           /* xCreate */
30739    pcache1Cachesize,        /* xCachesize */
30740    pcache1Pagecount,        /* xPagecount */
30741    pcache1Fetch,            /* xFetch */
30742    pcache1Unpin,            /* xUnpin */
30743    pcache1Rekey,            /* xRekey */
30744    pcache1Truncate,         /* xTruncate */
30745    pcache1Destroy           /* xDestroy */
30746  };
30747  sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
30748}
30749
30750#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
30751/*
30752** This function is called to free superfluous dynamically allocated memory
30753** held by the pager system. Memory in use by any SQLite pager allocated
30754** by the current thread may be sqlite3_free()ed.
30755**
30756** nReq is the number of bytes of memory required. Once this much has
30757** been released, the function returns. The return value is the total number
30758** of bytes of memory released.
30759*/
30760SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
30761  int nFree = 0;
30762  if( pcache1.pStart==0 ){
30763    PgHdr1 *p;
30764    pcache1EnterMutex();
30765    while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
30766      nFree += sqlite3MallocSize(PGHDR1_TO_PAGE(p));
30767      pcache1PinPage(p);
30768      pcache1RemoveFromHash(p);
30769      pcache1FreePage(p);
30770    }
30771    pcache1LeaveMutex();
30772  }
30773  return nFree;
30774}
30775#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
30776
30777#ifdef SQLITE_TEST
30778/*
30779** This function is used by test procedures to inspect the internal state
30780** of the global cache.
30781*/
30782SQLITE_PRIVATE void sqlite3PcacheStats(
30783  int *pnCurrent,      /* OUT: Total number of pages cached */
30784  int *pnMax,          /* OUT: Global maximum cache size */
30785  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
30786  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
30787){
30788  PgHdr1 *p;
30789  int nRecyclable = 0;
30790  for(p=pcache1.pLruHead; p; p=p->pLruNext){
30791    nRecyclable++;
30792  }
30793  *pnCurrent = pcache1.nCurrentPage;
30794  *pnMax = pcache1.nMaxPage;
30795  *pnMin = pcache1.nMinPage;
30796  *pnRecyclable = nRecyclable;
30797}
30798#endif
30799
30800/************** End of pcache1.c *********************************************/
30801/************** Begin file rowset.c ******************************************/
30802/*
30803** 2008 December 3
30804**
30805** The author disclaims copyright to this source code.  In place of
30806** a legal notice, here is a blessing:
30807**
30808**    May you do good and not evil.
30809**    May you find forgiveness for yourself and forgive others.
30810**    May you share freely, never taking more than you give.
30811**
30812*************************************************************************
30813**
30814** This module implements an object we call a "RowSet".
30815**
30816** The RowSet object is a collection of rowids.  Rowids
30817** are inserted into the RowSet in an arbitrary order.  Inserts
30818** can be intermixed with tests to see if a given rowid has been
30819** previously inserted into the RowSet.
30820**
30821** After all inserts are finished, it is possible to extract the
30822** elements of the RowSet in sorted order.  Once this extraction
30823** process has started, no new elements may be inserted.
30824**
30825** Hence, the primitive operations for a RowSet are:
30826**
30827**    CREATE
30828**    INSERT
30829**    TEST
30830**    SMALLEST
30831**    DESTROY
30832**
30833** The CREATE and DESTROY primitives are the constructor and destructor,
30834** obviously.  The INSERT primitive adds a new element to the RowSet.
30835** TEST checks to see if an element is already in the RowSet.  SMALLEST
30836** extracts the least value from the RowSet.
30837**
30838** The INSERT primitive might allocate additional memory.  Memory is
30839** allocated in chunks so most INSERTs do no allocation.  There is an
30840** upper bound on the size of allocated memory.  No memory is freed
30841** until DESTROY.
30842**
30843** The TEST primitive includes a "batch" number.  The TEST primitive
30844** will only see elements that were inserted before the last change
30845** in the batch number.  In other words, if an INSERT occurs between
30846** two TESTs where the TESTs have the same batch nubmer, then the
30847** value added by the INSERT will not be visible to the second TEST.
30848** The initial batch number is zero, so if the very first TEST contains
30849** a non-zero batch number, it will see all prior INSERTs.
30850**
30851** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
30852** that is attempted.
30853**
30854** The cost of an INSERT is roughly constant.  (Sometime new memory
30855** has to be allocated on an INSERT.)  The cost of a TEST with a new
30856** batch number is O(NlogN) where N is the number of elements in the RowSet.
30857** The cost of a TEST using the same batch number is O(logN).  The cost
30858** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
30859** primitives are constant time.  The cost of DESTROY is O(N).
30860**
30861** There is an added cost of O(N) when switching between TEST and
30862** SMALLEST primitives.
30863*/
30864
30865
30866/*
30867** Target size for allocation chunks.
30868*/
30869#define ROWSET_ALLOCATION_SIZE 1024
30870
30871/*
30872** The number of rowset entries per allocation chunk.
30873*/
30874#define ROWSET_ENTRY_PER_CHUNK  \
30875                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
30876
30877/*
30878** Each entry in a RowSet is an instance of the following object.
30879*/
30880struct RowSetEntry {
30881  i64 v;                        /* ROWID value for this entry */
30882  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
30883  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
30884};
30885
30886/*
30887** RowSetEntry objects are allocated in large chunks (instances of the
30888** following structure) to reduce memory allocation overhead.  The
30889** chunks are kept on a linked list so that they can be deallocated
30890** when the RowSet is destroyed.
30891*/
30892struct RowSetChunk {
30893  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
30894  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
30895};
30896
30897/*
30898** A RowSet in an instance of the following structure.
30899**
30900** A typedef of this structure if found in sqliteInt.h.
30901*/
30902struct RowSet {
30903  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
30904  sqlite3 *db;                   /* The database connection */
30905  struct RowSetEntry *pEntry;    /* List of entries using pRight */
30906  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
30907  struct RowSetEntry *pFresh;    /* Source of new entry objects */
30908  struct RowSetEntry *pTree;     /* Binary tree of entries */
30909  u16 nFresh;                    /* Number of objects on pFresh */
30910  u8 isSorted;                   /* True if pEntry is sorted */
30911  u8 iBatch;                     /* Current insert batch */
30912};
30913
30914/*
30915** Turn bulk memory into a RowSet object.  N bytes of memory
30916** are available at pSpace.  The db pointer is used as a memory context
30917** for any subsequent allocations that need to occur.
30918** Return a pointer to the new RowSet object.
30919**
30920** It must be the case that N is sufficient to make a Rowset.  If not
30921** an assertion fault occurs.
30922**
30923** If N is larger than the minimum, use the surplus as an initial
30924** allocation of entries available to be filled.
30925*/
30926SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
30927  RowSet *p;
30928  assert( N >= ROUND8(sizeof(*p)) );
30929  p = pSpace;
30930  p->pChunk = 0;
30931  p->db = db;
30932  p->pEntry = 0;
30933  p->pLast = 0;
30934  p->pTree = 0;
30935  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
30936  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
30937  p->isSorted = 1;
30938  p->iBatch = 0;
30939  return p;
30940}
30941
30942/*
30943** Deallocate all chunks from a RowSet.  This frees all memory that
30944** the RowSet has allocated over its lifetime.  This routine is
30945** the destructor for the RowSet.
30946*/
30947SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
30948  struct RowSetChunk *pChunk, *pNextChunk;
30949  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
30950    pNextChunk = pChunk->pNextChunk;
30951    sqlite3DbFree(p->db, pChunk);
30952  }
30953  p->pChunk = 0;
30954  p->nFresh = 0;
30955  p->pEntry = 0;
30956  p->pLast = 0;
30957  p->pTree = 0;
30958  p->isSorted = 1;
30959}
30960
30961/*
30962** Insert a new value into a RowSet.
30963**
30964** The mallocFailed flag of the database connection is set if a
30965** memory allocation fails.
30966*/
30967SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
30968  struct RowSetEntry *pEntry;  /* The new entry */
30969  struct RowSetEntry *pLast;   /* The last prior entry */
30970  assert( p!=0 );
30971  if( p->nFresh==0 ){
30972    struct RowSetChunk *pNew;
30973    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
30974    if( pNew==0 ){
30975      return;
30976    }
30977    pNew->pNextChunk = p->pChunk;
30978    p->pChunk = pNew;
30979    p->pFresh = pNew->aEntry;
30980    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
30981  }
30982  pEntry = p->pFresh++;
30983  p->nFresh--;
30984  pEntry->v = rowid;
30985  pEntry->pRight = 0;
30986  pLast = p->pLast;
30987  if( pLast ){
30988    if( p->isSorted && rowid<=pLast->v ){
30989      p->isSorted = 0;
30990    }
30991    pLast->pRight = pEntry;
30992  }else{
30993    assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
30994    p->pEntry = pEntry;
30995  }
30996  p->pLast = pEntry;
30997}
30998
30999/*
31000** Merge two lists of RowSetEntry objects.  Remove duplicates.
31001**
31002** The input lists are connected via pRight pointers and are
31003** assumed to each already be in sorted order.
31004*/
31005static struct RowSetEntry *rowSetMerge(
31006  struct RowSetEntry *pA,    /* First sorted list to be merged */
31007  struct RowSetEntry *pB     /* Second sorted list to be merged */
31008){
31009  struct RowSetEntry head;
31010  struct RowSetEntry *pTail;
31011
31012  pTail = &head;
31013  while( pA && pB ){
31014    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
31015    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
31016    if( pA->v<pB->v ){
31017      pTail->pRight = pA;
31018      pA = pA->pRight;
31019      pTail = pTail->pRight;
31020    }else if( pB->v<pA->v ){
31021      pTail->pRight = pB;
31022      pB = pB->pRight;
31023      pTail = pTail->pRight;
31024    }else{
31025      pA = pA->pRight;
31026    }
31027  }
31028  if( pA ){
31029    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
31030    pTail->pRight = pA;
31031  }else{
31032    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
31033    pTail->pRight = pB;
31034  }
31035  return head.pRight;
31036}
31037
31038/*
31039** Sort all elements on the pEntry list of the RowSet into ascending order.
31040*/
31041static void rowSetSort(RowSet *p){
31042  unsigned int i;
31043  struct RowSetEntry *pEntry;
31044  struct RowSetEntry *aBucket[40];
31045
31046  assert( p->isSorted==0 );
31047  memset(aBucket, 0, sizeof(aBucket));
31048  while( p->pEntry ){
31049    pEntry = p->pEntry;
31050    p->pEntry = pEntry->pRight;
31051    pEntry->pRight = 0;
31052    for(i=0; aBucket[i]; i++){
31053      pEntry = rowSetMerge(aBucket[i], pEntry);
31054      aBucket[i] = 0;
31055    }
31056    aBucket[i] = pEntry;
31057  }
31058  pEntry = 0;
31059  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
31060    pEntry = rowSetMerge(pEntry, aBucket[i]);
31061  }
31062  p->pEntry = pEntry;
31063  p->pLast = 0;
31064  p->isSorted = 1;
31065}
31066
31067
31068/*
31069** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
31070** Convert this tree into a linked list connected by the pRight pointers
31071** and return pointers to the first and last elements of the new list.
31072*/
31073static void rowSetTreeToList(
31074  struct RowSetEntry *pIn,         /* Root of the input tree */
31075  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
31076  struct RowSetEntry **ppLast      /* Write tail of the output list here */
31077){
31078  assert( pIn!=0 );
31079  if( pIn->pLeft ){
31080    struct RowSetEntry *p;
31081    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
31082    p->pRight = pIn;
31083  }else{
31084    *ppFirst = pIn;
31085  }
31086  if( pIn->pRight ){
31087    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
31088  }else{
31089    *ppLast = pIn;
31090  }
31091  assert( (*ppLast)->pRight==0 );
31092}
31093
31094
31095/*
31096** Convert a sorted list of elements (connected by pRight) into a binary
31097** tree with depth of iDepth.  A depth of 1 means the tree contains a single
31098** node taken from the head of *ppList.  A depth of 2 means a tree with
31099** three nodes.  And so forth.
31100**
31101** Use as many entries from the input list as required and update the
31102** *ppList to point to the unused elements of the list.  If the input
31103** list contains too few elements, then construct an incomplete tree
31104** and leave *ppList set to NULL.
31105**
31106** Return a pointer to the root of the constructed binary tree.
31107*/
31108static struct RowSetEntry *rowSetNDeepTree(
31109  struct RowSetEntry **ppList,
31110  int iDepth
31111){
31112  struct RowSetEntry *p;         /* Root of the new tree */
31113  struct RowSetEntry *pLeft;     /* Left subtree */
31114  if( *ppList==0 ){
31115    return 0;
31116  }
31117  if( iDepth==1 ){
31118    p = *ppList;
31119    *ppList = p->pRight;
31120    p->pLeft = p->pRight = 0;
31121    return p;
31122  }
31123  pLeft = rowSetNDeepTree(ppList, iDepth-1);
31124  p = *ppList;
31125  if( p==0 ){
31126    return pLeft;
31127  }
31128  p->pLeft = pLeft;
31129  *ppList = p->pRight;
31130  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
31131  return p;
31132}
31133
31134/*
31135** Convert a sorted list of elements into a binary tree. Make the tree
31136** as deep as it needs to be in order to contain the entire list.
31137*/
31138static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
31139  int iDepth;           /* Depth of the tree so far */
31140  struct RowSetEntry *p;       /* Current tree root */
31141  struct RowSetEntry *pLeft;   /* Left subtree */
31142
31143  assert( pList!=0 );
31144  p = pList;
31145  pList = p->pRight;
31146  p->pLeft = p->pRight = 0;
31147  for(iDepth=1; pList; iDepth++){
31148    pLeft = p;
31149    p = pList;
31150    pList = p->pRight;
31151    p->pLeft = pLeft;
31152    p->pRight = rowSetNDeepTree(&pList, iDepth);
31153  }
31154  return p;
31155}
31156
31157/*
31158** Convert the list in p->pEntry into a sorted list if it is not
31159** sorted already.  If there is a binary tree on p->pTree, then
31160** convert it into a list too and merge it into the p->pEntry list.
31161*/
31162static void rowSetToList(RowSet *p){
31163  if( !p->isSorted ){
31164    rowSetSort(p);
31165  }
31166  if( p->pTree ){
31167    struct RowSetEntry *pHead, *pTail;
31168    rowSetTreeToList(p->pTree, &pHead, &pTail);
31169    p->pTree = 0;
31170    p->pEntry = rowSetMerge(p->pEntry, pHead);
31171  }
31172}
31173
31174/*
31175** Extract the smallest element from the RowSet.
31176** Write the element into *pRowid.  Return 1 on success.  Return
31177** 0 if the RowSet is already empty.
31178**
31179** After this routine has been called, the sqlite3RowSetInsert()
31180** routine may not be called again.
31181*/
31182SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
31183  rowSetToList(p);
31184  if( p->pEntry ){
31185    *pRowid = p->pEntry->v;
31186    p->pEntry = p->pEntry->pRight;
31187    if( p->pEntry==0 ){
31188      sqlite3RowSetClear(p);
31189    }
31190    return 1;
31191  }else{
31192    return 0;
31193  }
31194}
31195
31196/*
31197** Check to see if element iRowid was inserted into the the rowset as
31198** part of any insert batch prior to iBatch.  Return 1 or 0.
31199*/
31200SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
31201  struct RowSetEntry *p;
31202  if( iBatch!=pRowSet->iBatch ){
31203    if( pRowSet->pEntry ){
31204      rowSetToList(pRowSet);
31205      pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
31206      pRowSet->pEntry = 0;
31207      pRowSet->pLast = 0;
31208    }
31209    pRowSet->iBatch = iBatch;
31210  }
31211  p = pRowSet->pTree;
31212  while( p ){
31213    if( p->v<iRowid ){
31214      p = p->pRight;
31215    }else if( p->v>iRowid ){
31216      p = p->pLeft;
31217    }else{
31218      return 1;
31219    }
31220  }
31221  return 0;
31222}
31223
31224/************** End of rowset.c **********************************************/
31225/************** Begin file pager.c *******************************************/
31226/*
31227** 2001 September 15
31228**
31229** The author disclaims copyright to this source code.  In place of
31230** a legal notice, here is a blessing:
31231**
31232**    May you do good and not evil.
31233**    May you find forgiveness for yourself and forgive others.
31234**    May you share freely, never taking more than you give.
31235**
31236*************************************************************************
31237** This is the implementation of the page cache subsystem or "pager".
31238**
31239** The pager is used to access a database disk file.  It implements
31240** atomic commit and rollback through the use of a journal file that
31241** is separate from the database file.  The pager also implements file
31242** locking to prevent two processes from writing the same database
31243** file simultaneously, or one process from reading the database while
31244** another is writing.
31245*/
31246#ifndef SQLITE_OMIT_DISKIO
31247
31248/*
31249** Macros for troubleshooting.  Normally turned off
31250*/
31251#if 0
31252int sqlite3PagerTrace=1;  /* True to enable tracing */
31253#define sqlite3DebugPrintf printf
31254#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
31255#else
31256#define PAGERTRACE(X)
31257#endif
31258
31259/*
31260** The following two macros are used within the PAGERTRACE() macros above
31261** to print out file-descriptors.
31262**
31263** PAGERID() takes a pointer to a Pager struct as its argument. The
31264** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
31265** struct as its argument.
31266*/
31267#define PAGERID(p) ((int)(p->fd))
31268#define FILEHANDLEID(fd) ((int)fd)
31269
31270/*
31271** The page cache as a whole is always in one of the following
31272** states:
31273**
31274**   PAGER_UNLOCK        The page cache is not currently reading or
31275**                       writing the database file.  There is no
31276**                       data held in memory.  This is the initial
31277**                       state.
31278**
31279**   PAGER_SHARED        The page cache is reading the database.
31280**                       Writing is not permitted.  There can be
31281**                       multiple readers accessing the same database
31282**                       file at the same time.
31283**
31284**   PAGER_RESERVED      This process has reserved the database for writing
31285**                       but has not yet made any changes.  Only one process
31286**                       at a time can reserve the database.  The original
31287**                       database file has not been modified so other
31288**                       processes may still be reading the on-disk
31289**                       database file.
31290**
31291**   PAGER_EXCLUSIVE     The page cache is writing the database.
31292**                       Access is exclusive.  No other processes or
31293**                       threads can be reading or writing while one
31294**                       process is writing.
31295**
31296**   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
31297**                       after all dirty pages have been written to the
31298**                       database file and the file has been synced to
31299**                       disk. All that remains to do is to remove or
31300**                       truncate the journal file and the transaction
31301**                       will be committed.
31302**
31303** The page cache comes up in PAGER_UNLOCK.  The first time a
31304** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
31305** After all pages have been released using sqlite_page_unref(),
31306** the state transitions back to PAGER_UNLOCK.  The first time
31307** that sqlite3PagerWrite() is called, the state transitions to
31308** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
31309** called on an outstanding page which means that the pager must
31310** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
31311** PAGER_RESERVED means that there is an open rollback journal.
31312** The transition to PAGER_EXCLUSIVE occurs before any changes
31313** are made to the database file, though writes to the rollback
31314** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
31315** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
31316** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
31317*/
31318#define PAGER_UNLOCK      0
31319#define PAGER_SHARED      1   /* same as SHARED_LOCK */
31320#define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
31321#define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
31322#define PAGER_SYNCED      5
31323
31324/*
31325** A macro used for invoking the codec if there is one
31326*/
31327#ifdef SQLITE_HAS_CODEC
31328# define CODEC1(P,D,N,X,E) \
31329    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
31330# define CODEC2(P,D,N,X,E,O) \
31331    if( P->xCodec==0 ){ O=(char*)D; }else \
31332    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
31333#else
31334# define CODEC1(P,D,N,X,E)   /* NO-OP */
31335# define CODEC2(P,D,N,X,E,O) O=(char*)D
31336#endif
31337
31338/*
31339** The maximum allowed sector size. 64KiB. If the xSectorsize() method
31340** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
31341** This could conceivably cause corruption following a power failure on
31342** such a system. This is currently an undocumented limit.
31343*/
31344#define MAX_SECTOR_SIZE 0x10000
31345
31346/*
31347** An instance of the following structure is allocated for each active
31348** savepoint and statement transaction in the system. All such structures
31349** are stored in the Pager.aSavepoint[] array, which is allocated and
31350** resized using sqlite3Realloc().
31351**
31352** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
31353** set to 0. If a journal-header is written into the main journal while
31354** the savepoint is active, then iHdrOffset is set to the byte offset
31355** immediately following the last journal record written into the main
31356** journal before the journal-header. This is required during savepoint
31357** rollback (see pagerPlaybackSavepoint()).
31358*/
31359typedef struct PagerSavepoint PagerSavepoint;
31360struct PagerSavepoint {
31361  i64 iOffset;                 /* Starting offset in main journal */
31362  i64 iHdrOffset;              /* See above */
31363  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
31364  Pgno nOrig;                  /* Original number of pages in file */
31365  Pgno iSubRec;                /* Index of first record in sub-journal */
31366};
31367
31368/*
31369** A open page cache is an instance of the following structure.
31370**
31371** errCode
31372**
31373**   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
31374**   or SQLITE_FULL. Once one of the first three errors occurs, it persists
31375**   and is returned as the result of every major pager API call.  The
31376**   SQLITE_FULL return code is slightly different. It persists only until the
31377**   next successful rollback is performed on the pager cache. Also,
31378**   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
31379**   APIs, they may still be used successfully.
31380**
31381** dbSizeValid, dbSize, dbOrigSize, dbFileSize
31382**
31383**   Managing the size of the database file in pages is a little complicated.
31384**   The variable Pager.dbSize contains the number of pages that the database
31385**   image currently contains. As the database image grows or shrinks this
31386**   variable is updated. The variable Pager.dbFileSize contains the number
31387**   of pages in the database file. This may be different from Pager.dbSize
31388**   if some pages have been appended to the database image but not yet written
31389**   out from the cache to the actual file on disk. Or if the image has been
31390**   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
31391**   contains the number of pages in the database image when the current
31392**   transaction was opened. The contents of all three of these variables is
31393**   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
31394**
31395**   TODO: Under what conditions is dbSizeValid set? Cleared?
31396**
31397** changeCountDone
31398**
31399**   This boolean variable is used to make sure that the change-counter
31400**   (the 4-byte header field at byte offset 24 of the database file) is
31401**   not updated more often than necessary.
31402**
31403**   It is set to true when the change-counter field is updated, which
31404**   can only happen if an exclusive lock is held on the database file.
31405**   It is cleared (set to false) whenever an exclusive lock is
31406**   relinquished on the database file. Each time a transaction is committed,
31407**   The changeCountDone flag is inspected. If it is true, the work of
31408**   updating the change-counter is omitted for the current transaction.
31409**
31410**   This mechanism means that when running in exclusive mode, a connection
31411**   need only update the change-counter once, for the first transaction
31412**   committed.
31413**
31414** dbModified
31415**
31416**   The dbModified flag is set whenever a database page is dirtied.
31417**   It is cleared at the end of each transaction.
31418**
31419**   It is used when committing or otherwise ending a transaction. If
31420**   the dbModified flag is clear then less work has to be done.
31421**
31422** journalStarted
31423**
31424**   This flag is set whenever the the main journal is synced.
31425**
31426**   The point of this flag is that it must be set after the
31427**   first journal header in a journal file has been synced to disk.
31428**   After this has happened, new pages appended to the database
31429**   do not need the PGHDR_NEED_SYNC flag set, as they do not need
31430**   to wait for a journal sync before they can be written out to
31431**   the database file (see function pager_write()).
31432**
31433** setMaster
31434**
31435**   This variable is used to ensure that the master journal file name
31436**   (if any) is only written into the journal file once.
31437**
31438**   When committing a transaction, the master journal file name (if any)
31439**   may be written into the journal file while the pager is still in
31440**   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
31441**   then attempts to upgrade to an exclusive lock. If this attempt
31442**   fails, then SQLITE_BUSY may be returned to the user and the user
31443**   may attempt to commit the transaction again later (calling
31444**   CommitPhaseOne() again). This flag is used to ensure that the
31445**   master journal name is only written to the journal file the first
31446**   time CommitPhaseOne() is called.
31447**
31448** doNotSync
31449**
31450**   This variable is set and cleared by sqlite3PagerWrite().
31451**
31452** needSync
31453**
31454**   TODO: It might be easier to set this variable in writeJournalHdr()
31455**   and writeMasterJournal() only. Change its meaning to "unsynced data
31456**   has been written to the journal".
31457**
31458** subjInMemory
31459**
31460**   This is a boolean variable. If true, then any required sub-journal
31461**   is opened as an in-memory journal file. If false, then in-memory
31462**   sub-journals are only used for in-memory pager files.
31463*/
31464struct Pager {
31465  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
31466  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
31467  u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
31468  u8 useJournal;              /* Use a rollback journal on this file */
31469  u8 noReadlock;              /* Do not bother to obtain readlocks */
31470  u8 noSync;                  /* Do not sync the journal if true */
31471  u8 fullSync;                /* Do extra syncs of the journal for robustness */
31472  u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
31473  u8 tempFile;                /* zFilename is a temporary file */
31474  u8 readOnly;                /* True for a read-only database */
31475  u8 memDb;                   /* True to inhibit all file I/O */
31476
31477  /* The following block contains those class members that are dynamically
31478  ** modified during normal operations. The other variables in this structure
31479  ** are either constant throughout the lifetime of the pager, or else
31480  ** used to store configuration parameters that affect the way the pager
31481  ** operates.
31482  **
31483  ** The 'state' variable is described in more detail along with the
31484  ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
31485  ** other variables in this block are described in the comment directly
31486  ** above this class definition.
31487  */
31488  u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
31489  u8 dbModified;              /* True if there are any changes to the Db */
31490  u8 needSync;                /* True if an fsync() is needed on the journal */
31491  u8 journalStarted;          /* True if header of journal is synced */
31492  u8 changeCountDone;         /* Set after incrementing the change-counter */
31493  u8 setMaster;               /* True if a m-j name has been written to jrnl */
31494  u8 doNotSync;               /* Boolean. While true, do not spill the cache */
31495  u8 dbSizeValid;             /* Set when dbSize is correct */
31496  u8 subjInMemory;            /* True to use in-memory sub-journals */
31497  Pgno dbSize;                /* Number of pages in the database */
31498  Pgno dbOrigSize;            /* dbSize before the current transaction */
31499  Pgno dbFileSize;            /* Number of pages in the database file */
31500  int errCode;                /* One of several kinds of errors */
31501  int nRec;                   /* Pages journalled since last j-header written */
31502  u32 cksumInit;              /* Quasi-random value added to every checksum */
31503  u32 nSubRec;                /* Number of records written to sub-journal */
31504  Bitvec *pInJournal;         /* One bit for each page in the database file */
31505  sqlite3_file *fd;           /* File descriptor for database */
31506  sqlite3_file *jfd;          /* File descriptor for main journal */
31507  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
31508  i64 journalOff;             /* Current write offset in the journal file */
31509  i64 journalHdr;             /* Byte offset to previous journal header */
31510  PagerSavepoint *aSavepoint; /* Array of active savepoints */
31511  int nSavepoint;             /* Number of elements in aSavepoint[] */
31512  char dbFileVers[16];        /* Changes whenever database file changes */
31513  u32 sectorSize;             /* Assumed sector size during rollback */
31514
31515  u16 nExtra;                 /* Add this many bytes to each in-memory page */
31516  i16 nReserve;               /* Number of unused bytes at end of each page */
31517  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
31518  int pageSize;               /* Number of bytes in a page */
31519  Pgno mxPgno;                /* Maximum allowed size of the database */
31520  char *zFilename;            /* Name of the database file */
31521  char *zJournal;             /* Name of the journal file */
31522  int (*xBusyHandler)(void*); /* Function to call when busy */
31523  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
31524#ifdef SQLITE_TEST
31525  int nHit, nMiss;            /* Cache hits and missing */
31526  int nRead, nWrite;          /* Database pages read/written */
31527#endif
31528  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
31529#ifdef SQLITE_HAS_CODEC
31530  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
31531  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
31532  void (*xCodecFree)(void*);             /* Destructor for the codec */
31533  void *pCodec;               /* First argument to xCodec... methods */
31534#endif
31535  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
31536  i64 journalSizeLimit;       /* Size limit for persistent journal files */
31537  PCache *pPCache;            /* Pointer to page cache object */
31538  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
31539};
31540
31541/*
31542** The following global variables hold counters used for
31543** testing purposes only.  These variables do not exist in
31544** a non-testing build.  These variables are not thread-safe.
31545*/
31546#ifdef SQLITE_TEST
31547SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
31548SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
31549SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
31550# define PAGER_INCR(v)  v++
31551#else
31552# define PAGER_INCR(v)
31553#endif
31554
31555
31556
31557/*
31558** Journal files begin with the following magic string.  The data
31559** was obtained from /dev/random.  It is used only as a sanity check.
31560**
31561** Since version 2.8.0, the journal format contains additional sanity
31562** checking information.  If the power fails while the journal is being
31563** written, semi-random garbage data might appear in the journal
31564** file after power is restored.  If an attempt is then made
31565** to roll the journal back, the database could be corrupted.  The additional
31566** sanity checking data is an attempt to discover the garbage in the
31567** journal and ignore it.
31568**
31569** The sanity checking information for the new journal format consists
31570** of a 32-bit checksum on each page of data.  The checksum covers both
31571** the page number and the pPager->pageSize bytes of data for the page.
31572** This cksum is initialized to a 32-bit random value that appears in the
31573** journal file right after the header.  The random initializer is important,
31574** because garbage data that appears at the end of a journal is likely
31575** data that was once in other files that have now been deleted.  If the
31576** garbage data came from an obsolete journal file, the checksums might
31577** be correct.  But by initializing the checksum to random value which
31578** is different for every journal, we minimize that risk.
31579*/
31580static const unsigned char aJournalMagic[] = {
31581  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
31582};
31583
31584/*
31585** The size of the of each page record in the journal is given by
31586** the following macro.
31587*/
31588#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
31589
31590/*
31591** The journal header size for this pager. This is usually the same
31592** size as a single disk sector. See also setSectorSize().
31593*/
31594#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
31595
31596/*
31597** The macro MEMDB is true if we are dealing with an in-memory database.
31598** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
31599** the value of MEMDB will be a constant and the compiler will optimize
31600** out code that would never execute.
31601*/
31602#ifdef SQLITE_OMIT_MEMORYDB
31603# define MEMDB 0
31604#else
31605# define MEMDB pPager->memDb
31606#endif
31607
31608/*
31609** The maximum legal page number is (2^31 - 1).
31610*/
31611#define PAGER_MAX_PGNO 2147483647
31612
31613#ifndef NDEBUG
31614/*
31615** Usage:
31616**
31617**   assert( assert_pager_state(pPager) );
31618*/
31619static int assert_pager_state(Pager *pPager){
31620
31621  /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
31622  assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );
31623
31624  /* The changeCountDone flag is always set for temp-files */
31625  assert( pPager->tempFile==0 || pPager->changeCountDone );
31626
31627  return 1;
31628}
31629#endif
31630
31631/*
31632** Return true if it is necessary to write page *pPg into the sub-journal.
31633** A page needs to be written into the sub-journal if there exists one
31634** or more open savepoints for which:
31635**
31636**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
31637**   * The bit corresponding to the page-number is not set in
31638**     PagerSavepoint.pInSavepoint.
31639*/
31640static int subjRequiresPage(PgHdr *pPg){
31641  Pgno pgno = pPg->pgno;
31642  Pager *pPager = pPg->pPager;
31643  int i;
31644  for(i=0; i<pPager->nSavepoint; i++){
31645    PagerSavepoint *p = &pPager->aSavepoint[i];
31646    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
31647      return 1;
31648    }
31649  }
31650  return 0;
31651}
31652
31653/*
31654** Return true if the page is already in the journal file.
31655*/
31656static int pageInJournal(PgHdr *pPg){
31657  return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
31658}
31659
31660/*
31661** Read a 32-bit integer from the given file descriptor.  Store the integer
31662** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
31663** error code is something goes wrong.
31664**
31665** All values are stored on disk as big-endian.
31666*/
31667static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
31668  unsigned char ac[4];
31669  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
31670  if( rc==SQLITE_OK ){
31671    *pRes = sqlite3Get4byte(ac);
31672  }
31673  return rc;
31674}
31675
31676/*
31677** Write a 32-bit integer into a string buffer in big-endian byte order.
31678*/
31679#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
31680
31681/*
31682** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
31683** on success or an error code is something goes wrong.
31684*/
31685static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
31686  char ac[4];
31687  put32bits(ac, val);
31688  return sqlite3OsWrite(fd, ac, 4, offset);
31689}
31690
31691/*
31692** The argument to this macro is a file descriptor (type sqlite3_file*).
31693** Return 0 if it is not open, or non-zero (but not 1) if it is.
31694**
31695** This is so that expressions can be written as:
31696**
31697**   if( isOpen(pPager->jfd) ){ ...
31698**
31699** instead of
31700**
31701**   if( pPager->jfd->pMethods ){ ...
31702*/
31703#define isOpen(pFd) ((pFd)->pMethods)
31704
31705/*
31706** If file pFd is open, call sqlite3OsUnlock() on it.
31707*/
31708static int osUnlock(sqlite3_file *pFd, int eLock){
31709  if( !isOpen(pFd) ){
31710    return SQLITE_OK;
31711  }
31712  return sqlite3OsUnlock(pFd, eLock);
31713}
31714
31715/*
31716** This function determines whether or not the atomic-write optimization
31717** can be used with this pager. The optimization can be used if:
31718**
31719**  (a) the value returned by OsDeviceCharacteristics() indicates that
31720**      a database page may be written atomically, and
31721**  (b) the value returned by OsSectorSize() is less than or equal
31722**      to the page size.
31723**
31724** The optimization is also always enabled for temporary files. It is
31725** an error to call this function if pPager is opened on an in-memory
31726** database.
31727**
31728** If the optimization cannot be used, 0 is returned. If it can be used,
31729** then the value returned is the size of the journal file when it
31730** contains rollback data for exactly one page.
31731*/
31732#ifdef SQLITE_ENABLE_ATOMIC_WRITE
31733static int jrnlBufferSize(Pager *pPager){
31734  assert( !MEMDB );
31735  if( !pPager->tempFile ){
31736    int dc;                           /* Device characteristics */
31737    int nSector;                      /* Sector size */
31738    int szPage;                       /* Page size */
31739
31740    assert( isOpen(pPager->fd) );
31741    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
31742    nSector = pPager->sectorSize;
31743    szPage = pPager->pageSize;
31744
31745    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
31746    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
31747    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
31748      return 0;
31749    }
31750  }
31751
31752  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
31753}
31754#endif
31755
31756/*
31757** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
31758** on the cache using a hash function.  This is used for testing
31759** and debugging only.
31760*/
31761#ifdef SQLITE_CHECK_PAGES
31762/*
31763** Return a 32-bit hash of the page data for pPage.
31764*/
31765static u32 pager_datahash(int nByte, unsigned char *pData){
31766  u32 hash = 0;
31767  int i;
31768  for(i=0; i<nByte; i++){
31769    hash = (hash*1039) + pData[i];
31770  }
31771  return hash;
31772}
31773static u32 pager_pagehash(PgHdr *pPage){
31774  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
31775}
31776static void pager_set_pagehash(PgHdr *pPage){
31777  pPage->pageHash = pager_pagehash(pPage);
31778}
31779
31780/*
31781** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
31782** is defined, and NDEBUG is not defined, an assert() statement checks
31783** that the page is either dirty or still matches the calculated page-hash.
31784*/
31785#define CHECK_PAGE(x) checkPage(x)
31786static void checkPage(PgHdr *pPg){
31787  Pager *pPager = pPg->pPager;
31788  assert( !pPg->pageHash || pPager->errCode
31789      || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
31790}
31791
31792#else
31793#define pager_datahash(X,Y)  0
31794#define pager_pagehash(X)  0
31795#define CHECK_PAGE(x)
31796#endif  /* SQLITE_CHECK_PAGES */
31797
31798/*
31799** When this is called the journal file for pager pPager must be open.
31800** This function attempts to read a master journal file name from the
31801** end of the file and, if successful, copies it into memory supplied
31802** by the caller. See comments above writeMasterJournal() for the format
31803** used to store a master journal file name at the end of a journal file.
31804**
31805** zMaster must point to a buffer of at least nMaster bytes allocated by
31806** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
31807** enough space to write the master journal name). If the master journal
31808** name in the journal is longer than nMaster bytes (including a
31809** nul-terminator), then this is handled as if no master journal name
31810** were present in the journal.
31811**
31812** If a master journal file name is present at the end of the journal
31813** file, then it is copied into the buffer pointed to by zMaster. A
31814** nul-terminator byte is appended to the buffer following the master
31815** journal file name.
31816**
31817** If it is determined that no master journal file name is present
31818** zMaster[0] is set to 0 and SQLITE_OK returned.
31819**
31820** If an error occurs while reading from the journal file, an SQLite
31821** error code is returned.
31822*/
31823static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
31824  int rc;                    /* Return code */
31825  u32 len;                   /* Length in bytes of master journal name */
31826  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
31827  u32 cksum;                 /* MJ checksum value read from journal */
31828  u32 u;                     /* Unsigned loop counter */
31829  unsigned char aMagic[8];   /* A buffer to hold the magic header */
31830  zMaster[0] = '\0';
31831
31832  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
31833   || szJ<16
31834   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
31835   || len>=nMaster
31836   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
31837   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
31838   || memcmp(aMagic, aJournalMagic, 8)
31839   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
31840  ){
31841    return rc;
31842  }
31843
31844  /* See if the checksum matches the master journal name */
31845  for(u=0; u<len; u++){
31846    cksum -= zMaster[u];
31847  }
31848  if( cksum ){
31849    /* If the checksum doesn't add up, then one or more of the disk sectors
31850    ** containing the master journal filename is corrupted. This means
31851    ** definitely roll back, so just return SQLITE_OK and report a (nul)
31852    ** master-journal filename.
31853    */
31854    len = 0;
31855  }
31856  zMaster[len] = '\0';
31857
31858  return SQLITE_OK;
31859}
31860
31861/*
31862** Return the offset of the sector boundary at or immediately
31863** following the value in pPager->journalOff, assuming a sector
31864** size of pPager->sectorSize bytes.
31865**
31866** i.e for a sector size of 512:
31867**
31868**   Pager.journalOff          Return value
31869**   ---------------------------------------
31870**   0                         0
31871**   512                       512
31872**   100                       512
31873**   2000                      2048
31874**
31875*/
31876static i64 journalHdrOffset(Pager *pPager){
31877  i64 offset = 0;
31878  i64 c = pPager->journalOff;
31879  if( c ){
31880    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
31881  }
31882  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
31883  assert( offset>=c );
31884  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
31885  return offset;
31886}
31887
31888/*
31889** The journal file must be open when this function is called.
31890**
31891** This function is a no-op if the journal file has not been written to
31892** within the current transaction (i.e. if Pager.journalOff==0).
31893**
31894** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
31895** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
31896** zero the 28-byte header at the start of the journal file. In either case,
31897** if the pager is not in no-sync mode, sync the journal file immediately
31898** after writing or truncating it.
31899**
31900** If Pager.journalSizeLimit is set to a positive, non-zero value, and
31901** following the truncation or zeroing described above the size of the
31902** journal file in bytes is larger than this value, then truncate the
31903** journal file to Pager.journalSizeLimit bytes. The journal file does
31904** not need to be synced following this operation.
31905**
31906** If an IO error occurs, abandon processing and return the IO error code.
31907** Otherwise, return SQLITE_OK.
31908*/
31909static int zeroJournalHdr(Pager *pPager, int doTruncate){
31910  int rc = SQLITE_OK;                               /* Return code */
31911  assert( isOpen(pPager->jfd) );
31912  if( pPager->journalOff ){
31913    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
31914
31915    IOTRACE(("JZEROHDR %p\n", pPager))
31916    if( doTruncate || iLimit==0 ){
31917      rc = sqlite3OsTruncate(pPager->jfd, 0);
31918    }else{
31919      static const char zeroHdr[28] = {0};
31920      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
31921    }
31922    if( rc==SQLITE_OK && !pPager->noSync ){
31923      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
31924    }
31925
31926    /* At this point the transaction is committed but the write lock
31927    ** is still held on the file. If there is a size limit configured for
31928    ** the persistent journal and the journal file currently consumes more
31929    ** space than that limit allows for, truncate it now. There is no need
31930    ** to sync the file following this operation.
31931    */
31932    if( rc==SQLITE_OK && iLimit>0 ){
31933      i64 sz;
31934      rc = sqlite3OsFileSize(pPager->jfd, &sz);
31935      if( rc==SQLITE_OK && sz>iLimit ){
31936        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
31937      }
31938    }
31939  }
31940  return rc;
31941}
31942
31943/*
31944** The journal file must be open when this routine is called. A journal
31945** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
31946** current location.
31947**
31948** The format for the journal header is as follows:
31949** - 8 bytes: Magic identifying journal format.
31950** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
31951** - 4 bytes: Random number used for page hash.
31952** - 4 bytes: Initial database page count.
31953** - 4 bytes: Sector size used by the process that wrote this journal.
31954** - 4 bytes: Database page size.
31955**
31956** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
31957*/
31958static int writeJournalHdr(Pager *pPager){
31959  int rc = SQLITE_OK;                 /* Return code */
31960  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
31961  u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
31962  u32 nWrite;                         /* Bytes of header sector written */
31963  int ii;                             /* Loop counter */
31964
31965  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
31966
31967  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
31968    nHeader = JOURNAL_HDR_SZ(pPager);
31969  }
31970
31971  /* If there are active savepoints and any of them were created
31972  ** since the most recent journal header was written, update the
31973  ** PagerSavepoint.iHdrOffset fields now.
31974  */
31975  for(ii=0; ii<pPager->nSavepoint; ii++){
31976    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
31977      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
31978    }
31979  }
31980
31981  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
31982
31983  /*
31984  ** Write the nRec Field - the number of page records that follow this
31985  ** journal header. Normally, zero is written to this value at this time.
31986  ** After the records are added to the journal (and the journal synced,
31987  ** if in full-sync mode), the zero is overwritten with the true number
31988  ** of records (see syncJournal()).
31989  **
31990  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
31991  ** reading the journal this value tells SQLite to assume that the
31992  ** rest of the journal file contains valid page records. This assumption
31993  ** is dangerous, as if a failure occurred whilst writing to the journal
31994  ** file it may contain some garbage data. There are two scenarios
31995  ** where this risk can be ignored:
31996  **
31997  **   * When the pager is in no-sync mode. Corruption can follow a
31998  **     power failure in this case anyway.
31999  **
32000  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
32001  **     that garbage data is never appended to the journal file.
32002  */
32003  assert( isOpen(pPager->fd) || pPager->noSync );
32004  if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
32005   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
32006  ){
32007    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
32008    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
32009  }else{
32010    memset(zHeader, 0, sizeof(aJournalMagic)+4);
32011  }
32012
32013  /* The random check-hash initialiser */
32014  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
32015  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
32016  /* The initial database size */
32017  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
32018  /* The assumed sector size for this process */
32019  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
32020
32021  /* The page size */
32022  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
32023
32024  /* Initializing the tail of the buffer is not necessary.  Everything
32025  ** works find if the following memset() is omitted.  But initializing
32026  ** the memory prevents valgrind from complaining, so we are willing to
32027  ** take the performance hit.
32028  */
32029  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
32030         nHeader-(sizeof(aJournalMagic)+20));
32031
32032  /* In theory, it is only necessary to write the 28 bytes that the
32033  ** journal header consumes to the journal file here. Then increment the
32034  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
32035  ** record is written to the following sector (leaving a gap in the file
32036  ** that will be implicitly filled in by the OS).
32037  **
32038  ** However it has been discovered that on some systems this pattern can
32039  ** be significantly slower than contiguously writing data to the file,
32040  ** even if that means explicitly writing data to the block of
32041  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
32042  ** is done.
32043  **
32044  ** The loop is required here in case the sector-size is larger than the
32045  ** database page size. Since the zHeader buffer is only Pager.pageSize
32046  ** bytes in size, more than one call to sqlite3OsWrite() may be required
32047  ** to populate the entire journal header sector.
32048  */
32049  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
32050    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
32051    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
32052    pPager->journalOff += nHeader;
32053  }
32054
32055  return rc;
32056}
32057
32058/*
32059** The journal file must be open when this is called. A journal header file
32060** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
32061** file. The current location in the journal file is given by
32062** pPager->journalOff. See comments above function writeJournalHdr() for
32063** a description of the journal header format.
32064**
32065** If the header is read successfully, *pNRec is set to the number of
32066** page records following this header and *pDbSize is set to the size of the
32067** database before the transaction began, in pages. Also, pPager->cksumInit
32068** is set to the value read from the journal header. SQLITE_OK is returned
32069** in this case.
32070**
32071** If the journal header file appears to be corrupted, SQLITE_DONE is
32072** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
32073** cannot be read from the journal file an error code is returned.
32074*/
32075static int readJournalHdr(
32076  Pager *pPager,               /* Pager object */
32077  int isHot,
32078  i64 journalSize,             /* Size of the open journal file in bytes */
32079  u32 *pNRec,                  /* OUT: Value read from the nRec field */
32080  u32 *pDbSize                 /* OUT: Value of original database size field */
32081){
32082  int rc;                      /* Return code */
32083  unsigned char aMagic[8];     /* A buffer to hold the magic header */
32084  i64 iHdrOff;                 /* Offset of journal header being read */
32085
32086  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
32087
32088  /* Advance Pager.journalOff to the start of the next sector. If the
32089  ** journal file is too small for there to be a header stored at this
32090  ** point, return SQLITE_DONE.
32091  */
32092  pPager->journalOff = journalHdrOffset(pPager);
32093  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
32094    return SQLITE_DONE;
32095  }
32096  iHdrOff = pPager->journalOff;
32097
32098  /* Read in the first 8 bytes of the journal header. If they do not match
32099  ** the  magic string found at the start of each journal header, return
32100  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
32101  ** proceed.
32102  */
32103  if( isHot || iHdrOff!=pPager->journalHdr ){
32104    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
32105    if( rc ){
32106      return rc;
32107    }
32108    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
32109      return SQLITE_DONE;
32110    }
32111  }
32112
32113  /* Read the first three 32-bit fields of the journal header: The nRec
32114  ** field, the checksum-initializer and the database size at the start
32115  ** of the transaction. Return an error code if anything goes wrong.
32116  */
32117  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
32118   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
32119   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
32120  ){
32121    return rc;
32122  }
32123
32124  if( pPager->journalOff==0 ){
32125    u32 iPageSize;               /* Page-size field of journal header */
32126    u32 iSectorSize;             /* Sector-size field of journal header */
32127    u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */
32128
32129    /* Read the page-size and sector-size journal header fields. */
32130    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
32131     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
32132    ){
32133      return rc;
32134    }
32135
32136    /* Check that the values read from the page-size and sector-size fields
32137    ** are within range. To be 'in range', both values need to be a power
32138    ** of two greater than or equal to 512 or 32, and not greater than their
32139    ** respective compile time maximum limits.
32140    */
32141    if( iPageSize<512                  || iSectorSize<32
32142     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
32143     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
32144    ){
32145      /* If the either the page-size or sector-size in the journal-header is
32146      ** invalid, then the process that wrote the journal-header must have
32147      ** crashed before the header was synced. In this case stop reading
32148      ** the journal file here.
32149      */
32150      return SQLITE_DONE;
32151    }
32152
32153    /* Update the page-size to match the value read from the journal.
32154    ** Use a testcase() macro to make sure that malloc failure within
32155    ** PagerSetPagesize() is tested.
32156    */
32157    iPageSize16 = (u16)iPageSize;
32158    rc = sqlite3PagerSetPagesize(pPager, &iPageSize16, -1);
32159    testcase( rc!=SQLITE_OK );
32160    assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );
32161
32162    /* Update the assumed sector-size to match the value used by
32163    ** the process that created this journal. If this journal was
32164    ** created by a process other than this one, then this routine
32165    ** is being called from within pager_playback(). The local value
32166    ** of Pager.sectorSize is restored at the end of that routine.
32167    */
32168    pPager->sectorSize = iSectorSize;
32169  }
32170
32171  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
32172  return rc;
32173}
32174
32175
32176/*
32177** Write the supplied master journal name into the journal file for pager
32178** pPager at the current location. The master journal name must be the last
32179** thing written to a journal file. If the pager is in full-sync mode, the
32180** journal file descriptor is advanced to the next sector boundary before
32181** anything is written. The format is:
32182**
32183**   + 4 bytes: PAGER_MJ_PGNO.
32184**   + N bytes: Master journal filename in utf-8.
32185**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
32186**   + 4 bytes: Master journal name checksum.
32187**   + 8 bytes: aJournalMagic[].
32188**
32189** The master journal page checksum is the sum of the bytes in the master
32190** journal name, where each byte is interpreted as a signed 8-bit integer.
32191**
32192** If zMaster is a NULL pointer (occurs for a single database transaction),
32193** this call is a no-op.
32194*/
32195static int writeMasterJournal(Pager *pPager, const char *zMaster){
32196  int rc;                          /* Return code */
32197  int nMaster;                     /* Length of string zMaster */
32198  i64 iHdrOff;                     /* Offset of header in journal file */
32199  i64 jrnlSize;                    /* Size of journal file on disk */
32200  u32 cksum = 0;                   /* Checksum of string zMaster */
32201
32202  if( !zMaster || pPager->setMaster
32203   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
32204   || pPager->journalMode==PAGER_JOURNALMODE_OFF
32205  ){
32206    return SQLITE_OK;
32207  }
32208  pPager->setMaster = 1;
32209  assert( isOpen(pPager->jfd) );
32210
32211  /* Calculate the length in bytes and the checksum of zMaster */
32212  for(nMaster=0; zMaster[nMaster]; nMaster++){
32213    cksum += zMaster[nMaster];
32214  }
32215
32216  /* If in full-sync mode, advance to the next disk sector before writing
32217  ** the master journal name. This is in case the previous page written to
32218  ** the journal has already been synced.
32219  */
32220  if( pPager->fullSync ){
32221    pPager->journalOff = journalHdrOffset(pPager);
32222  }
32223  iHdrOff = pPager->journalOff;
32224
32225  /* Write the master journal data to the end of the journal file. If
32226  ** an error occurs, return the error code to the caller.
32227  */
32228  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
32229   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
32230   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
32231   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
32232   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
32233  ){
32234    return rc;
32235  }
32236  pPager->journalOff += (nMaster+20);
32237  pPager->needSync = !pPager->noSync;
32238
32239  /* If the pager is in peristent-journal mode, then the physical
32240  ** journal-file may extend past the end of the master-journal name
32241  ** and 8 bytes of magic data just written to the file. This is
32242  ** dangerous because the code to rollback a hot-journal file
32243  ** will not be able to find the master-journal name to determine
32244  ** whether or not the journal is hot.
32245  **
32246  ** Easiest thing to do in this scenario is to truncate the journal
32247  ** file to the required size.
32248  */
32249  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
32250   && jrnlSize>pPager->journalOff
32251  ){
32252    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
32253  }
32254  return rc;
32255}
32256
32257/*
32258** Find a page in the hash table given its page number. Return
32259** a pointer to the page or NULL if the requested page is not
32260** already in memory.
32261*/
32262static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
32263  PgHdr *p;                         /* Return value */
32264
32265  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
32266  ** fail, since no attempt to allocate dynamic memory will be made.
32267  */
32268  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
32269  return p;
32270}
32271
32272/*
32273** Unless the pager is in error-state, discard all in-memory pages. If
32274** the pager is in error-state, then this call is a no-op.
32275**
32276** TODO: Why can we not reset the pager while in error state?
32277*/
32278static void pager_reset(Pager *pPager){
32279  if( SQLITE_OK==pPager->errCode ){
32280    sqlite3BackupRestart(pPager->pBackup);
32281    sqlite3PcacheClear(pPager->pPCache);
32282    pPager->dbSizeValid = 0;
32283  }
32284}
32285
32286/*
32287** Free all structures in the Pager.aSavepoint[] array and set both
32288** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
32289** if it is open and the pager is not in exclusive mode.
32290*/
32291static void releaseAllSavepoints(Pager *pPager){
32292  int ii;               /* Iterator for looping through Pager.aSavepoint */
32293  for(ii=0; ii<pPager->nSavepoint; ii++){
32294    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
32295  }
32296  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
32297    sqlite3OsClose(pPager->sjfd);
32298  }
32299  sqlite3_free(pPager->aSavepoint);
32300  pPager->aSavepoint = 0;
32301  pPager->nSavepoint = 0;
32302  pPager->nSubRec = 0;
32303}
32304
32305/*
32306** Set the bit number pgno in the PagerSavepoint.pInSavepoint
32307** bitvecs of all open savepoints. Return SQLITE_OK if successful
32308** or SQLITE_NOMEM if a malloc failure occurs.
32309*/
32310static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
32311  int ii;                   /* Loop counter */
32312  int rc = SQLITE_OK;       /* Result code */
32313
32314  for(ii=0; ii<pPager->nSavepoint; ii++){
32315    PagerSavepoint *p = &pPager->aSavepoint[ii];
32316    if( pgno<=p->nOrig ){
32317      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
32318      testcase( rc==SQLITE_NOMEM );
32319      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
32320    }
32321  }
32322  return rc;
32323}
32324
32325/*
32326** Unlock the database file. This function is a no-op if the pager
32327** is in exclusive mode.
32328**
32329** If the pager is currently in error state, discard the contents of
32330** the cache and reset the Pager structure internal state. If there is
32331** an open journal-file, then the next time a shared-lock is obtained
32332** on the pager file (by this or any other process), it will be
32333** treated as a hot-journal and rolled back.
32334*/
32335static void pager_unlock(Pager *pPager){
32336  if( !pPager->exclusiveMode ){
32337    int rc;                      /* Return code */
32338
32339    /* Always close the journal file when dropping the database lock.
32340    ** Otherwise, another connection with journal_mode=delete might
32341    ** delete the file out from under us.
32342    */
32343    sqlite3OsClose(pPager->jfd);
32344    sqlite3BitvecDestroy(pPager->pInJournal);
32345    pPager->pInJournal = 0;
32346    releaseAllSavepoints(pPager);
32347
32348    /* If the file is unlocked, somebody else might change it. The
32349    ** values stored in Pager.dbSize etc. might become invalid if
32350    ** this happens. TODO: Really, this doesn't need to be cleared
32351    ** until the change-counter check fails in PagerSharedLock().
32352    */
32353    pPager->dbSizeValid = 0;
32354
32355    rc = osUnlock(pPager->fd, NO_LOCK);
32356    if( rc ){
32357      pPager->errCode = rc;
32358    }
32359    IOTRACE(("UNLOCK %p\n", pPager))
32360
32361    /* If Pager.errCode is set, the contents of the pager cache cannot be
32362    ** trusted. Now that the pager file is unlocked, the contents of the
32363    ** cache can be discarded and the error code safely cleared.
32364    */
32365    if( pPager->errCode ){
32366      if( rc==SQLITE_OK ){
32367        pPager->errCode = SQLITE_OK;
32368      }
32369      pager_reset(pPager);
32370    }
32371
32372    pPager->changeCountDone = 0;
32373    pPager->state = PAGER_UNLOCK;
32374    pPager->dbModified = 0;
32375  }
32376}
32377
32378/*
32379** This function should be called when an IOERR, CORRUPT or FULL error
32380** may have occurred. The first argument is a pointer to the pager
32381** structure, the second the error-code about to be returned by a pager
32382** API function. The value returned is a copy of the second argument
32383** to this function.
32384**
32385** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
32386** the error becomes persistent. Until the persisten error is cleared,
32387** subsequent API calls on this Pager will immediately return the same
32388** error code.
32389**
32390** A persistent error indicates that the contents of the pager-cache
32391** cannot be trusted. This state can be cleared by completely discarding
32392** the contents of the pager-cache. If a transaction was active when
32393** the persistent error occurred, then the rollback journal may need
32394** to be replayed to restore the contents of the database file (as if
32395** it were a hot-journal).
32396*/
32397static int pager_error(Pager *pPager, int rc){
32398  int rc2 = rc & 0xff;
32399  assert( rc==SQLITE_OK || !MEMDB );
32400  assert(
32401       pPager->errCode==SQLITE_FULL ||
32402       pPager->errCode==SQLITE_OK ||
32403       (pPager->errCode & 0xff)==SQLITE_IOERR
32404  );
32405  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
32406    pPager->errCode = rc;
32407  }
32408  return rc;
32409}
32410
32411/*
32412** Execute a rollback if a transaction is active and unlock the
32413** database file.
32414**
32415** If the pager has already entered the error state, do not attempt
32416** the rollback at this time. Instead, pager_unlock() is called. The
32417** call to pager_unlock() will discard all in-memory pages, unlock
32418** the database file and clear the error state. If this means that
32419** there is a hot-journal left in the file-system, the next connection
32420** to obtain a shared lock on the pager (which may be this one) will
32421** roll it back.
32422**
32423** If the pager has not already entered the error state, but an IO or
32424** malloc error occurs during a rollback, then this will itself cause
32425** the pager to enter the error state. Which will be cleared by the
32426** call to pager_unlock(), as described above.
32427*/
32428static void pagerUnlockAndRollback(Pager *pPager){
32429  if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
32430    sqlite3BeginBenignMalloc();
32431    sqlite3PagerRollback(pPager);
32432    sqlite3EndBenignMalloc();
32433  }
32434  pager_unlock(pPager);
32435}
32436
32437/*
32438** This routine ends a transaction. A transaction is usually ended by
32439** either a COMMIT or a ROLLBACK operation. This routine may be called
32440** after rollback of a hot-journal, or if an error occurs while opening
32441** the journal file or writing the very first journal-header of a
32442** database transaction.
32443**
32444** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
32445** routine is called, it is a no-op (returns SQLITE_OK).
32446**
32447** Otherwise, any active savepoints are released.
32448**
32449** If the journal file is open, then it is "finalized". Once a journal
32450** file has been finalized it is not possible to use it to roll back a
32451** transaction. Nor will it be considered to be a hot-journal by this
32452** or any other database connection. Exactly how a journal is finalized
32453** depends on whether or not the pager is running in exclusive mode and
32454** the current journal-mode (Pager.journalMode value), as follows:
32455**
32456**   journalMode==MEMORY
32457**     Journal file descriptor is simply closed. This destroys an
32458**     in-memory journal.
32459**
32460**   journalMode==TRUNCATE
32461**     Journal file is truncated to zero bytes in size.
32462**
32463**   journalMode==PERSIST
32464**     The first 28 bytes of the journal file are zeroed. This invalidates
32465**     the first journal header in the file, and hence the entire journal
32466**     file. An invalid journal file cannot be rolled back.
32467**
32468**   journalMode==DELETE
32469**     The journal file is closed and deleted using sqlite3OsDelete().
32470**
32471**     If the pager is running in exclusive mode, this method of finalizing
32472**     the journal file is never used. Instead, if the journalMode is
32473**     DELETE and the pager is in exclusive mode, the method described under
32474**     journalMode==PERSIST is used instead.
32475**
32476** After the journal is finalized, if running in non-exclusive mode, the
32477** pager moves to PAGER_SHARED state (and downgrades the lock on the
32478** database file accordingly).
32479**
32480** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
32481** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
32482** exclusive mode.
32483**
32484** SQLITE_OK is returned if no error occurs. If an error occurs during
32485** any of the IO operations to finalize the journal file or unlock the
32486** database then the IO error code is returned to the user. If the
32487** operation to finalize the journal file fails, then the code still
32488** tries to unlock the database file if not in exclusive mode. If the
32489** unlock operation fails as well, then the first error code related
32490** to the first error encountered (the journal finalization one) is
32491** returned.
32492*/
32493static int pager_end_transaction(Pager *pPager, int hasMaster){
32494  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
32495  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
32496
32497  if( pPager->state<PAGER_RESERVED ){
32498    return SQLITE_OK;
32499  }
32500  releaseAllSavepoints(pPager);
32501
32502  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
32503  if( isOpen(pPager->jfd) ){
32504
32505    /* Finalize the journal file. */
32506    if( sqlite3IsMemJournal(pPager->jfd) ){
32507      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
32508      sqlite3OsClose(pPager->jfd);
32509    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
32510      if( pPager->journalOff==0 ){
32511        rc = SQLITE_OK;
32512      }else{
32513        rc = sqlite3OsTruncate(pPager->jfd, 0);
32514      }
32515      pPager->journalOff = 0;
32516      pPager->journalStarted = 0;
32517    }else if( pPager->exclusiveMode
32518     || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
32519    ){
32520      rc = zeroJournalHdr(pPager, hasMaster);
32521      pager_error(pPager, rc);
32522      pPager->journalOff = 0;
32523      pPager->journalStarted = 0;
32524    }else{
32525      /* This branch may be executed with Pager.journalMode==MEMORY if
32526      ** a hot-journal was just rolled back. In this case the journal
32527      ** file should be closed and deleted. If this connection writes to
32528      ** the database file, it will do so using an in-memory journal.  */
32529      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
32530           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
32531      );
32532      sqlite3OsClose(pPager->jfd);
32533      if( !pPager->tempFile ){
32534        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
32535      }
32536    }
32537
32538#ifdef SQLITE_CHECK_PAGES
32539    sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
32540#endif
32541
32542    sqlite3PcacheCleanAll(pPager->pPCache);
32543    sqlite3BitvecDestroy(pPager->pInJournal);
32544    pPager->pInJournal = 0;
32545    pPager->nRec = 0;
32546  }
32547
32548  if( !pPager->exclusiveMode ){
32549    rc2 = osUnlock(pPager->fd, SHARED_LOCK);
32550    pPager->state = PAGER_SHARED;
32551    pPager->changeCountDone = 0;
32552  }else if( pPager->state==PAGER_SYNCED ){
32553    pPager->state = PAGER_EXCLUSIVE;
32554  }
32555  pPager->setMaster = 0;
32556  pPager->needSync = 0;
32557  pPager->dbModified = 0;
32558
32559  /* TODO: Is this optimal? Why is the db size invalidated here
32560  ** when the database file is not unlocked? */
32561  pPager->dbOrigSize = 0;
32562  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
32563  if( !MEMDB ){
32564    pPager->dbSizeValid = 0;
32565  }
32566
32567  return (rc==SQLITE_OK?rc2:rc);
32568}
32569
32570/*
32571** Parameter aData must point to a buffer of pPager->pageSize bytes
32572** of data. Compute and return a checksum based ont the contents of the
32573** page of data and the current value of pPager->cksumInit.
32574**
32575** This is not a real checksum. It is really just the sum of the
32576** random initial value (pPager->cksumInit) and every 200th byte
32577** of the page data, starting with byte offset (pPager->pageSize%200).
32578** Each byte is interpreted as an 8-bit unsigned integer.
32579**
32580** Changing the formula used to compute this checksum results in an
32581** incompatible journal file format.
32582**
32583** If journal corruption occurs due to a power failure, the most likely
32584** scenario is that one end or the other of the record will be changed.
32585** It is much less likely that the two ends of the journal record will be
32586** correct and the middle be corrupt.  Thus, this "checksum" scheme,
32587** though fast and simple, catches the mostly likely kind of corruption.
32588*/
32589static u32 pager_cksum(Pager *pPager, const u8 *aData){
32590  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
32591  int i = pPager->pageSize-200;          /* Loop counter */
32592  while( i>0 ){
32593    cksum += aData[i];
32594    i -= 200;
32595  }
32596  return cksum;
32597}
32598
32599/*
32600** Read a single page from either the journal file (if isMainJrnl==1) or
32601** from the sub-journal (if isMainJrnl==0) and playback that page.
32602** The page begins at offset *pOffset into the file. The *pOffset
32603** value is increased to the start of the next page in the journal.
32604**
32605** The isMainJrnl flag is true if this is the main rollback journal and
32606** false for the statement journal.  The main rollback journal uses
32607** checksums - the statement journal does not.
32608**
32609** If the page number of the page record read from the (sub-)journal file
32610** is greater than the current value of Pager.dbSize, then playback is
32611** skipped and SQLITE_OK is returned.
32612**
32613** If pDone is not NULL, then it is a record of pages that have already
32614** been played back.  If the page at *pOffset has already been played back
32615** (if the corresponding pDone bit is set) then skip the playback.
32616** Make sure the pDone bit corresponding to the *pOffset page is set
32617** prior to returning.
32618**
32619** If the page record is successfully read from the (sub-)journal file
32620** and played back, then SQLITE_OK is returned. If an IO error occurs
32621** while reading the record from the (sub-)journal file or while writing
32622** to the database file, then the IO error code is returned. If data
32623** is successfully read from the (sub-)journal file but appears to be
32624** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
32625** two circumstances:
32626**
32627**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
32628**   * If the record is being rolled back from the main journal file
32629**     and the checksum field does not match the record content.
32630**
32631** Neither of these two scenarios are possible during a savepoint rollback.
32632**
32633** If this is a savepoint rollback, then memory may have to be dynamically
32634** allocated by this function. If this is the case and an allocation fails,
32635** SQLITE_NOMEM is returned.
32636*/
32637static int pager_playback_one_page(
32638  Pager *pPager,                /* The pager being played back */
32639  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
32640  int isUnsync,                 /* True if reading from unsynced main journal */
32641  i64 *pOffset,                 /* Offset of record to playback */
32642  int isSavepnt,                /* True for a savepoint rollback */
32643  Bitvec *pDone                 /* Bitvec of pages already played back */
32644){
32645  int rc;
32646  PgHdr *pPg;                   /* An existing page in the cache */
32647  Pgno pgno;                    /* The page number of a page in journal */
32648  u32 cksum;                    /* Checksum used for sanity checking */
32649  char *aData;                  /* Temporary storage for the page */
32650  sqlite3_file *jfd;            /* The file descriptor for the journal file */
32651
32652  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
32653  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
32654  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
32655  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
32656
32657  aData = pPager->pTmpSpace;
32658  assert( aData );         /* Temp storage must have already been allocated */
32659
32660  /* Read the page number and page data from the journal or sub-journal
32661  ** file. Return an error code to the caller if an IO error occurs.
32662  */
32663  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
32664  rc = read32bits(jfd, *pOffset, &pgno);
32665  if( rc!=SQLITE_OK ) return rc;
32666  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
32667  if( rc!=SQLITE_OK ) return rc;
32668  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
32669
32670  /* Sanity checking on the page.  This is more important that I originally
32671  ** thought.  If a power failure occurs while the journal is being written,
32672  ** it could cause invalid data to be written into the journal.  We need to
32673  ** detect this invalid data (with high probability) and ignore it.
32674  */
32675  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
32676    assert( !isSavepnt );
32677    return SQLITE_DONE;
32678  }
32679  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
32680    return SQLITE_OK;
32681  }
32682  if( isMainJrnl ){
32683    rc = read32bits(jfd, (*pOffset)-4, &cksum);
32684    if( rc ) return rc;
32685    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
32686      return SQLITE_DONE;
32687    }
32688  }
32689
32690  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
32691    return rc;
32692  }
32693
32694  assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
32695
32696  /* If the pager is in RESERVED state, then there must be a copy of this
32697  ** page in the pager cache. In this case just update the pager cache,
32698  ** not the database file. The page is left marked dirty in this case.
32699  **
32700  ** An exception to the above rule: If the database is in no-sync mode
32701  ** and a page is moved during an incremental vacuum then the page may
32702  ** not be in the pager cache. Later: if a malloc() or IO error occurs
32703  ** during a Movepage() call, then the page may not be in the cache
32704  ** either. So the condition described in the above paragraph is not
32705  ** assert()able.
32706  **
32707  ** If in EXCLUSIVE state, then we update the pager cache if it exists
32708  ** and the main file. The page is then marked not dirty.
32709  **
32710  ** Ticket #1171:  The statement journal might contain page content that is
32711  ** different from the page content at the start of the transaction.
32712  ** This occurs when a page is changed prior to the start of a statement
32713  ** then changed again within the statement.  When rolling back such a
32714  ** statement we must not write to the original database unless we know
32715  ** for certain that original page contents are synced into the main rollback
32716  ** journal.  Otherwise, a power loss might leave modified data in the
32717  ** database file without an entry in the rollback journal that can
32718  ** restore the database to its original form.  Two conditions must be
32719  ** met before writing to the database files. (1) the database must be
32720  ** locked.  (2) we know that the original page content is fully synced
32721  ** in the main journal either because the page is not in cache or else
32722  ** the page is marked as needSync==0.
32723  **
32724  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
32725  ** is possible to fail a statement on a database that does not yet exist.
32726  ** Do not attempt to write if database file has never been opened.
32727  */
32728  pPg = pager_lookup(pPager, pgno);
32729  assert( pPg || !MEMDB );
32730  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
32731           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
32732           (isMainJrnl?"main-journal":"sub-journal")
32733  ));
32734  if( (pPager->state>=PAGER_EXCLUSIVE)
32735   && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
32736   && isOpen(pPager->fd)
32737   && !isUnsync
32738  ){
32739    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
32740    rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
32741    if( pgno>pPager->dbFileSize ){
32742      pPager->dbFileSize = pgno;
32743    }
32744    if( pPager->pBackup ){
32745      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
32746      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
32747      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
32748    }
32749  }else if( !isMainJrnl && pPg==0 ){
32750    /* If this is a rollback of a savepoint and data was not written to
32751    ** the database and the page is not in-memory, there is a potential
32752    ** problem. When the page is next fetched by the b-tree layer, it
32753    ** will be read from the database file, which may or may not be
32754    ** current.
32755    **
32756    ** There are a couple of different ways this can happen. All are quite
32757    ** obscure. When running in synchronous mode, this can only happen
32758    ** if the page is on the free-list at the start of the transaction, then
32759    ** populated, then moved using sqlite3PagerMovepage().
32760    **
32761    ** The solution is to add an in-memory page to the cache containing
32762    ** the data just read from the sub-journal. Mark the page as dirty
32763    ** and if the pager requires a journal-sync, then mark the page as
32764    ** requiring a journal-sync before it is written.
32765    */
32766    assert( isSavepnt );
32767    if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1))!=SQLITE_OK ){
32768      return rc;
32769    }
32770    pPg->flags &= ~PGHDR_NEED_READ;
32771    sqlite3PcacheMakeDirty(pPg);
32772  }
32773  if( pPg ){
32774    /* No page should ever be explicitly rolled back that is in use, except
32775    ** for page 1 which is held in use in order to keep the lock on the
32776    ** database active. However such a page may be rolled back as a result
32777    ** of an internal error resulting in an automatic call to
32778    ** sqlite3PagerRollback().
32779    */
32780    void *pData;
32781    pData = pPg->pData;
32782    memcpy(pData, (u8*)aData, pPager->pageSize);
32783    pPager->xReiniter(pPg);
32784    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
32785      /* If the contents of this page were just restored from the main
32786      ** journal file, then its content must be as they were when the
32787      ** transaction was first opened. In this case we can mark the page
32788      ** as clean, since there will be no need to write it out to the.
32789      **
32790      ** There is one exception to this rule. If the page is being rolled
32791      ** back as part of a savepoint (or statement) rollback from an
32792      ** unsynced portion of the main journal file, then it is not safe
32793      ** to mark the page as clean. This is because marking the page as
32794      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
32795      ** already in the journal file (recorded in Pager.pInJournal) and
32796      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
32797      ** again within this transaction, it will be marked as dirty but
32798      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
32799      ** be written out into the database file before its journal file
32800      ** segment is synced. If a crash occurs during or following this,
32801      ** database corruption may ensue.
32802      */
32803      sqlite3PcacheMakeClean(pPg);
32804    }
32805#ifdef SQLITE_CHECK_PAGES
32806    pPg->pageHash = pager_pagehash(pPg);
32807#endif
32808    /* If this was page 1, then restore the value of Pager.dbFileVers.
32809    ** Do this before any decoding. */
32810    if( pgno==1 ){
32811      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
32812    }
32813
32814    /* Decode the page just read from disk */
32815    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
32816    sqlite3PcacheRelease(pPg);
32817  }
32818  return rc;
32819}
32820
32821/*
32822** Parameter zMaster is the name of a master journal file. A single journal
32823** file that referred to the master journal file has just been rolled back.
32824** This routine checks if it is possible to delete the master journal file,
32825** and does so if it is.
32826**
32827** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
32828** available for use within this function.
32829**
32830** When a master journal file is created, it is populated with the names
32831** of all of its child journals, one after another, formatted as utf-8
32832** encoded text. The end of each child journal file is marked with a
32833** nul-terminator byte (0x00). i.e. the entire contents of a master journal
32834** file for a transaction involving two databases might be:
32835**
32836**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
32837**
32838** A master journal file may only be deleted once all of its child
32839** journals have been rolled back.
32840**
32841** This function reads the contents of the master-journal file into
32842** memory and loops through each of the child journal names. For
32843** each child journal, it checks if:
32844**
32845**   * if the child journal exists, and if so
32846**   * if the child journal contains a reference to master journal
32847**     file zMaster
32848**
32849** If a child journal can be found that matches both of the criteria
32850** above, this function returns without doing anything. Otherwise, if
32851** no such child journal can be found, file zMaster is deleted from
32852** the file-system using sqlite3OsDelete().
32853**
32854** If an IO error within this function, an error code is returned. This
32855** function allocates memory by calling sqlite3Malloc(). If an allocation
32856** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
32857** occur, SQLITE_OK is returned.
32858**
32859** TODO: This function allocates a single block of memory to load
32860** the entire contents of the master journal file. This could be
32861** a couple of kilobytes or so - potentially larger than the page
32862** size.
32863*/
32864static int pager_delmaster(Pager *pPager, const char *zMaster){
32865  sqlite3_vfs *pVfs = pPager->pVfs;
32866  int rc;                   /* Return code */
32867  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
32868  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
32869  char *zMasterJournal = 0; /* Contents of master journal file */
32870  i64 nMasterJournal;       /* Size of master journal file */
32871
32872  /* Allocate space for both the pJournal and pMaster file descriptors.
32873  ** If successful, open the master journal file for reading.
32874  */
32875  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
32876  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
32877  if( !pMaster ){
32878    rc = SQLITE_NOMEM;
32879  }else{
32880    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
32881    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
32882  }
32883  if( rc!=SQLITE_OK ) goto delmaster_out;
32884
32885  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
32886  if( rc!=SQLITE_OK ) goto delmaster_out;
32887
32888  if( nMasterJournal>0 ){
32889    char *zJournal;
32890    char *zMasterPtr = 0;
32891    int nMasterPtr = pVfs->mxPathname+1;
32892
32893    /* Load the entire master journal file into space obtained from
32894    ** sqlite3_malloc() and pointed to by zMasterJournal.
32895    */
32896    zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
32897    if( !zMasterJournal ){
32898      rc = SQLITE_NOMEM;
32899      goto delmaster_out;
32900    }
32901    zMasterPtr = &zMasterJournal[nMasterJournal+1];
32902    rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
32903    if( rc!=SQLITE_OK ) goto delmaster_out;
32904    zMasterJournal[nMasterJournal] = 0;
32905
32906    zJournal = zMasterJournal;
32907    while( (zJournal-zMasterJournal)<nMasterJournal ){
32908      int exists;
32909      rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
32910      if( rc!=SQLITE_OK ){
32911        goto delmaster_out;
32912      }
32913      if( exists ){
32914        /* One of the journals pointed to by the master journal exists.
32915        ** Open it and check if it points at the master journal. If
32916        ** so, return without deleting the master journal file.
32917        */
32918        int c;
32919        int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
32920        rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
32921        if( rc!=SQLITE_OK ){
32922          goto delmaster_out;
32923        }
32924
32925        rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
32926        sqlite3OsClose(pJournal);
32927        if( rc!=SQLITE_OK ){
32928          goto delmaster_out;
32929        }
32930
32931        c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
32932        if( c ){
32933          /* We have a match. Do not delete the master journal file. */
32934          goto delmaster_out;
32935        }
32936      }
32937      zJournal += (sqlite3Strlen30(zJournal)+1);
32938    }
32939  }
32940
32941  rc = sqlite3OsDelete(pVfs, zMaster, 0);
32942
32943delmaster_out:
32944  if( zMasterJournal ){
32945    sqlite3_free(zMasterJournal);
32946  }
32947  if( pMaster ){
32948    sqlite3OsClose(pMaster);
32949    assert( !isOpen(pJournal) );
32950  }
32951  sqlite3_free(pMaster);
32952  return rc;
32953}
32954
32955
32956/*
32957** This function is used to change the actual size of the database
32958** file in the file-system. This only happens when committing a transaction,
32959** or rolling back a transaction (including rolling back a hot-journal).
32960**
32961** If the main database file is not open, or an exclusive lock is not
32962** held, this function is a no-op. Otherwise, the size of the file is
32963** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
32964** on disk is currently larger than nPage pages, then use the VFS
32965** xTruncate() method to truncate it.
32966**
32967** Or, it might might be the case that the file on disk is smaller than
32968** nPage pages. Some operating system implementations can get confused if
32969** you try to truncate a file to some size that is larger than it
32970** currently is, so detect this case and write a single zero byte to
32971** the end of the new file instead.
32972**
32973** If successful, return SQLITE_OK. If an IO error occurs while modifying
32974** the database file, return the error code to the caller.
32975*/
32976static int pager_truncate(Pager *pPager, Pgno nPage){
32977  int rc = SQLITE_OK;
32978  if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
32979    i64 currentSize, newSize;
32980    /* TODO: Is it safe to use Pager.dbFileSize here? */
32981    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
32982    newSize = pPager->pageSize*(i64)nPage;
32983    if( rc==SQLITE_OK && currentSize!=newSize ){
32984      if( currentSize>newSize ){
32985        rc = sqlite3OsTruncate(pPager->fd, newSize);
32986      }else{
32987        rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
32988      }
32989      if( rc==SQLITE_OK ){
32990        pPager->dbFileSize = nPage;
32991      }
32992    }
32993  }
32994  return rc;
32995}
32996
32997/*
32998** Set the value of the Pager.sectorSize variable for the given
32999** pager based on the value returned by the xSectorSize method
33000** of the open database file. The sector size will be used used
33001** to determine the size and alignment of journal header and
33002** master journal pointers within created journal files.
33003**
33004** For temporary files the effective sector size is always 512 bytes.
33005**
33006** Otherwise, for non-temporary files, the effective sector size is
33007** the value returned by the xSectorSize() method rounded up to 32 if
33008** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
33009** is greater than MAX_SECTOR_SIZE.
33010*/
33011static void setSectorSize(Pager *pPager){
33012  assert( isOpen(pPager->fd) || pPager->tempFile );
33013
33014  if( !pPager->tempFile ){
33015    /* Sector size doesn't matter for temporary files. Also, the file
33016    ** may not have been opened yet, in which case the OsSectorSize()
33017    ** call will segfault.
33018    */
33019    pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
33020  }
33021  if( pPager->sectorSize<32 ){
33022    pPager->sectorSize = 512;
33023  }
33024  if( pPager->sectorSize>MAX_SECTOR_SIZE ){
33025    assert( MAX_SECTOR_SIZE>=512 );
33026    pPager->sectorSize = MAX_SECTOR_SIZE;
33027  }
33028}
33029
33030/*
33031** Playback the journal and thus restore the database file to
33032** the state it was in before we started making changes.
33033**
33034** The journal file format is as follows:
33035**
33036**  (1)  8 byte prefix.  A copy of aJournalMagic[].
33037**  (2)  4 byte big-endian integer which is the number of valid page records
33038**       in the journal.  If this value is 0xffffffff, then compute the
33039**       number of page records from the journal size.
33040**  (3)  4 byte big-endian integer which is the initial value for the
33041**       sanity checksum.
33042**  (4)  4 byte integer which is the number of pages to truncate the
33043**       database to during a rollback.
33044**  (5)  4 byte big-endian integer which is the sector size.  The header
33045**       is this many bytes in size.
33046**  (6)  4 byte big-endian integer which is the page size.
33047**  (7)  zero padding out to the next sector size.
33048**  (8)  Zero or more pages instances, each as follows:
33049**        +  4 byte page number.
33050**        +  pPager->pageSize bytes of data.
33051**        +  4 byte checksum
33052**
33053** When we speak of the journal header, we mean the first 7 items above.
33054** Each entry in the journal is an instance of the 8th item.
33055**
33056** Call the value from the second bullet "nRec".  nRec is the number of
33057** valid page entries in the journal.  In most cases, you can compute the
33058** value of nRec from the size of the journal file.  But if a power
33059** failure occurred while the journal was being written, it could be the
33060** case that the size of the journal file had already been increased but
33061** the extra entries had not yet made it safely to disk.  In such a case,
33062** the value of nRec computed from the file size would be too large.  For
33063** that reason, we always use the nRec value in the header.
33064**
33065** If the nRec value is 0xffffffff it means that nRec should be computed
33066** from the file size.  This value is used when the user selects the
33067** no-sync option for the journal.  A power failure could lead to corruption
33068** in this case.  But for things like temporary table (which will be
33069** deleted when the power is restored) we don't care.
33070**
33071** If the file opened as the journal file is not a well-formed
33072** journal file then all pages up to the first corrupted page are rolled
33073** back (or no pages if the journal header is corrupted). The journal file
33074** is then deleted and SQLITE_OK returned, just as if no corruption had
33075** been encountered.
33076**
33077** If an I/O or malloc() error occurs, the journal-file is not deleted
33078** and an error code is returned.
33079**
33080** The isHot parameter indicates that we are trying to rollback a journal
33081** that might be a hot journal.  Or, it could be that the journal is
33082** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
33083** If the journal really is hot, reset the pager cache prior rolling
33084** back any content.  If the journal is merely persistent, no reset is
33085** needed.
33086*/
33087static int pager_playback(Pager *pPager, int isHot){
33088  sqlite3_vfs *pVfs = pPager->pVfs;
33089  i64 szJ;                 /* Size of the journal file in bytes */
33090  u32 nRec;                /* Number of Records in the journal */
33091  u32 u;                   /* Unsigned loop counter */
33092  Pgno mxPg = 0;           /* Size of the original file in pages */
33093  int rc;                  /* Result code of a subroutine */
33094  int res = 1;             /* Value returned by sqlite3OsAccess() */
33095  char *zMaster = 0;       /* Name of master journal file if any */
33096  int needPagerReset;      /* True to reset page prior to first page rollback */
33097
33098  /* Figure out how many records are in the journal.  Abort early if
33099  ** the journal is empty.
33100  */
33101  assert( isOpen(pPager->jfd) );
33102  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
33103  if( rc!=SQLITE_OK || szJ==0 ){
33104    goto end_playback;
33105  }
33106
33107  /* Read the master journal name from the journal, if it is present.
33108  ** If a master journal file name is specified, but the file is not
33109  ** present on disk, then the journal is not hot and does not need to be
33110  ** played back.
33111  **
33112  ** TODO: Technically the following is an error because it assumes that
33113  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
33114  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
33115  **  mxPathname is 512, which is the same as the minimum allowable value
33116  ** for pageSize.
33117  */
33118  zMaster = pPager->pTmpSpace;
33119  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
33120  if( rc==SQLITE_OK && zMaster[0] ){
33121    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
33122  }
33123  zMaster = 0;
33124  if( rc!=SQLITE_OK || !res ){
33125    goto end_playback;
33126  }
33127  pPager->journalOff = 0;
33128  needPagerReset = isHot;
33129
33130  /* This loop terminates either when a readJournalHdr() or
33131  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
33132  ** occurs.
33133  */
33134  while( 1 ){
33135    int isUnsync = 0;
33136
33137    /* Read the next journal header from the journal file.  If there are
33138    ** not enough bytes left in the journal file for a complete header, or
33139    ** it is corrupted, then a process must of failed while writing it.
33140    ** This indicates nothing more needs to be rolled back.
33141    */
33142    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
33143    if( rc!=SQLITE_OK ){
33144      if( rc==SQLITE_DONE ){
33145        rc = SQLITE_OK;
33146      }
33147      goto end_playback;
33148    }
33149
33150    /* If nRec is 0xffffffff, then this journal was created by a process
33151    ** working in no-sync mode. This means that the rest of the journal
33152    ** file consists of pages, there are no more journal headers. Compute
33153    ** the value of nRec based on this assumption.
33154    */
33155    if( nRec==0xffffffff ){
33156      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
33157      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
33158    }
33159
33160    /* If nRec is 0 and this rollback is of a transaction created by this
33161    ** process and if this is the final header in the journal, then it means
33162    ** that this part of the journal was being filled but has not yet been
33163    ** synced to disk.  Compute the number of pages based on the remaining
33164    ** size of the file.
33165    **
33166    ** The third term of the test was added to fix ticket #2565.
33167    ** When rolling back a hot journal, nRec==0 always means that the next
33168    ** chunk of the journal contains zero pages to be rolled back.  But
33169    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
33170    ** the journal, it means that the journal might contain additional
33171    ** pages that need to be rolled back and that the number of pages
33172    ** should be computed based on the journal file size.
33173    */
33174    if( nRec==0 && !isHot &&
33175        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
33176      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
33177      isUnsync = 1;
33178    }
33179
33180    /* If this is the first header read from the journal, truncate the
33181    ** database file back to its original size.
33182    */
33183    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
33184      rc = pager_truncate(pPager, mxPg);
33185      if( rc!=SQLITE_OK ){
33186        goto end_playback;
33187      }
33188      pPager->dbSize = mxPg;
33189    }
33190
33191    /* Copy original pages out of the journal and back into the
33192    ** database file and/or page cache.
33193    */
33194    for(u=0; u<nRec; u++){
33195      if( needPagerReset ){
33196        pager_reset(pPager);
33197        needPagerReset = 0;
33198      }
33199      rc = pager_playback_one_page(pPager,1,isUnsync,&pPager->journalOff,0,0);
33200      if( rc!=SQLITE_OK ){
33201        if( rc==SQLITE_DONE ){
33202          rc = SQLITE_OK;
33203          pPager->journalOff = szJ;
33204          break;
33205        }else{
33206          /* If we are unable to rollback, quit and return the error
33207          ** code.  This will cause the pager to enter the error state
33208          ** so that no further harm will be done.  Perhaps the next
33209          ** process to come along will be able to rollback the database.
33210          */
33211          goto end_playback;
33212        }
33213      }
33214    }
33215  }
33216  /*NOTREACHED*/
33217  assert( 0 );
33218
33219end_playback:
33220  /* Following a rollback, the database file should be back in its original
33221  ** state prior to the start of the transaction, so invoke the
33222  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
33223  ** assertion that the transaction counter was modified.
33224  */
33225  assert(
33226    pPager->fd->pMethods==0 ||
33227    sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
33228  );
33229
33230  /* If this playback is happening automatically as a result of an IO or
33231  ** malloc error that occurred after the change-counter was updated but
33232  ** before the transaction was committed, then the change-counter
33233  ** modification may just have been reverted. If this happens in exclusive
33234  ** mode, then subsequent transactions performed by the connection will not
33235  ** update the change-counter at all. This may lead to cache inconsistency
33236  ** problems for other processes at some point in the future. So, just
33237  ** in case this has happened, clear the changeCountDone flag now.
33238  */
33239  pPager->changeCountDone = pPager->tempFile;
33240
33241  if( rc==SQLITE_OK ){
33242    zMaster = pPager->pTmpSpace;
33243    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
33244    testcase( rc!=SQLITE_OK );
33245  }
33246  if( rc==SQLITE_OK ){
33247    rc = pager_end_transaction(pPager, zMaster[0]!='\0');
33248    testcase( rc!=SQLITE_OK );
33249  }
33250  if( rc==SQLITE_OK && zMaster[0] && res ){
33251    /* If there was a master journal and this routine will return success,
33252    ** see if it is possible to delete the master journal.
33253    */
33254    rc = pager_delmaster(pPager, zMaster);
33255    testcase( rc!=SQLITE_OK );
33256  }
33257
33258  /* The Pager.sectorSize variable may have been updated while rolling
33259  ** back a journal created by a process with a different sector size
33260  ** value. Reset it to the correct value for this process.
33261  */
33262  setSectorSize(pPager);
33263  return rc;
33264}
33265
33266/*
33267** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
33268** the entire master journal file. The case pSavepoint==NULL occurs when
33269** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
33270** savepoint.
33271**
33272** When pSavepoint is not NULL (meaning a non-transaction savepoint is
33273** being rolled back), then the rollback consists of up to three stages,
33274** performed in the order specified:
33275**
33276**   * Pages are played back from the main journal starting at byte
33277**     offset PagerSavepoint.iOffset and continuing to
33278**     PagerSavepoint.iHdrOffset, or to the end of the main journal
33279**     file if PagerSavepoint.iHdrOffset is zero.
33280**
33281**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
33282**     back starting from the journal header immediately following
33283**     PagerSavepoint.iHdrOffset to the end of the main journal file.
33284**
33285**   * Pages are then played back from the sub-journal file, starting
33286**     with the PagerSavepoint.iSubRec and continuing to the end of
33287**     the journal file.
33288**
33289** Throughout the rollback process, each time a page is rolled back, the
33290** corresponding bit is set in a bitvec structure (variable pDone in the
33291** implementation below). This is used to ensure that a page is only
33292** rolled back the first time it is encountered in either journal.
33293**
33294** If pSavepoint is NULL, then pages are only played back from the main
33295** journal file. There is no need for a bitvec in this case.
33296**
33297** In either case, before playback commences the Pager.dbSize variable
33298** is reset to the value that it held at the start of the savepoint
33299** (or transaction). No page with a page-number greater than this value
33300** is played back. If one is encountered it is simply skipped.
33301*/
33302static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
33303  i64 szJ;                 /* Effective size of the main journal */
33304  i64 iHdrOff;             /* End of first segment of main-journal records */
33305  int rc = SQLITE_OK;      /* Return code */
33306  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
33307
33308  assert( pPager->state>=PAGER_SHARED );
33309
33310  /* Allocate a bitvec to use to store the set of pages rolled back */
33311  if( pSavepoint ){
33312    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
33313    if( !pDone ){
33314      return SQLITE_NOMEM;
33315    }
33316  }
33317
33318  /* Set the database size back to the value it was before the savepoint
33319  ** being reverted was opened.
33320  */
33321  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
33322
33323  /* Use pPager->journalOff as the effective size of the main rollback
33324  ** journal.  The actual file might be larger than this in
33325  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
33326  ** past pPager->journalOff is off-limits to us.
33327  */
33328  szJ = pPager->journalOff;
33329
33330  /* Begin by rolling back records from the main journal starting at
33331  ** PagerSavepoint.iOffset and continuing to the next journal header.
33332  ** There might be records in the main journal that have a page number
33333  ** greater than the current database size (pPager->dbSize) but those
33334  ** will be skipped automatically.  Pages are added to pDone as they
33335  ** are played back.
33336  */
33337  if( pSavepoint ){
33338    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
33339    pPager->journalOff = pSavepoint->iOffset;
33340    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
33341      rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
33342    }
33343    assert( rc!=SQLITE_DONE );
33344  }else{
33345    pPager->journalOff = 0;
33346  }
33347
33348  /* Continue rolling back records out of the main journal starting at
33349  ** the first journal header seen and continuing until the effective end
33350  ** of the main journal file.  Continue to skip out-of-range pages and
33351  ** continue adding pages rolled back to pDone.
33352  */
33353  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
33354    u32 ii;            /* Loop counter */
33355    u32 nJRec = 0;     /* Number of Journal Records */
33356    u32 dummy;
33357    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
33358    assert( rc!=SQLITE_DONE );
33359
33360    /*
33361    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
33362    ** test is related to ticket #2565.  See the discussion in the
33363    ** pager_playback() function for additional information.
33364    */
33365    if( nJRec==0
33366     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
33367    ){
33368      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
33369    }
33370    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
33371      rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
33372    }
33373    assert( rc!=SQLITE_DONE );
33374  }
33375  assert( rc!=SQLITE_OK || pPager->journalOff==szJ );
33376
33377  /* Finally,  rollback pages from the sub-journal.  Page that were
33378  ** previously rolled back out of the main journal (and are hence in pDone)
33379  ** will be skipped.  Out-of-range pages are also skipped.
33380  */
33381  if( pSavepoint ){
33382    u32 ii;            /* Loop counter */
33383    i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
33384    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
33385      assert( offset==ii*(4+pPager->pageSize) );
33386      rc = pager_playback_one_page(pPager, 0, 0, &offset, 1, pDone);
33387    }
33388    assert( rc!=SQLITE_DONE );
33389  }
33390
33391  sqlite3BitvecDestroy(pDone);
33392  if( rc==SQLITE_OK ){
33393    pPager->journalOff = szJ;
33394  }
33395  return rc;
33396}
33397
33398/*
33399** Change the maximum number of in-memory pages that are allowed.
33400*/
33401SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
33402  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
33403}
33404
33405/*
33406** Adjust the robustness of the database to damage due to OS crashes
33407** or power failures by changing the number of syncs()s when writing
33408** the rollback journal.  There are three levels:
33409**
33410**    OFF       sqlite3OsSync() is never called.  This is the default
33411**              for temporary and transient files.
33412**
33413**    NORMAL    The journal is synced once before writes begin on the
33414**              database.  This is normally adequate protection, but
33415**              it is theoretically possible, though very unlikely,
33416**              that an inopertune power failure could leave the journal
33417**              in a state which would cause damage to the database
33418**              when it is rolled back.
33419**
33420**    FULL      The journal is synced twice before writes begin on the
33421**              database (with some additional information - the nRec field
33422**              of the journal header - being written in between the two
33423**              syncs).  If we assume that writing a
33424**              single disk sector is atomic, then this mode provides
33425**              assurance that the journal will not be corrupted to the
33426**              point of causing damage to the database during rollback.
33427**
33428** Numeric values associated with these states are OFF==1, NORMAL=2,
33429** and FULL=3.
33430*/
33431#ifndef SQLITE_OMIT_PAGER_PRAGMAS
33432SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
33433  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
33434  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
33435  pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
33436  if( pPager->noSync ) pPager->needSync = 0;
33437}
33438#endif
33439
33440/*
33441** The following global variable is incremented whenever the library
33442** attempts to open a temporary file.  This information is used for
33443** testing and analysis only.
33444*/
33445#ifdef SQLITE_TEST
33446SQLITE_API int sqlite3_opentemp_count = 0;
33447#endif
33448
33449/*
33450** Open a temporary file.
33451**
33452** Write the file descriptor into *pFile. Return SQLITE_OK on success
33453** or some other error code if we fail. The OS will automatically
33454** delete the temporary file when it is closed.
33455**
33456** The flags passed to the VFS layer xOpen() call are those specified
33457** by parameter vfsFlags ORed with the following:
33458**
33459**     SQLITE_OPEN_READWRITE
33460**     SQLITE_OPEN_CREATE
33461**     SQLITE_OPEN_EXCLUSIVE
33462**     SQLITE_OPEN_DELETEONCLOSE
33463*/
33464static int pagerOpentemp(
33465  Pager *pPager,        /* The pager object */
33466  sqlite3_file *pFile,  /* Write the file descriptor here */
33467  int vfsFlags          /* Flags passed through to the VFS */
33468){
33469  int rc;               /* Return code */
33470
33471#ifdef SQLITE_TEST
33472  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
33473#endif
33474
33475  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
33476            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
33477  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
33478  assert( rc!=SQLITE_OK || isOpen(pFile) );
33479  return rc;
33480}
33481
33482/*
33483** Set the busy handler function.
33484**
33485** The pager invokes the busy-handler if sqlite3OsLock() returns
33486** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
33487** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
33488** lock. It does *not* invoke the busy handler when upgrading from
33489** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
33490** (which occurs during hot-journal rollback). Summary:
33491**
33492**   Transition                        | Invokes xBusyHandler
33493**   --------------------------------------------------------
33494**   NO_LOCK       -> SHARED_LOCK      | Yes
33495**   SHARED_LOCK   -> RESERVED_LOCK    | No
33496**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
33497**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
33498**
33499** If the busy-handler callback returns non-zero, the lock is
33500** retried. If it returns zero, then the SQLITE_BUSY error is
33501** returned to the caller of the pager API function.
33502*/
33503SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
33504  Pager *pPager,                       /* Pager object */
33505  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
33506  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
33507){
33508  pPager->xBusyHandler = xBusyHandler;
33509  pPager->pBusyHandlerArg = pBusyHandlerArg;
33510}
33511
33512/*
33513** Report the current page size and number of reserved bytes back
33514** to the codec.
33515*/
33516#ifdef SQLITE_HAS_CODEC
33517static void pagerReportSize(Pager *pPager){
33518  if( pPager->xCodecSizeChng ){
33519    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
33520                           (int)pPager->nReserve);
33521  }
33522}
33523#else
33524# define pagerReportSize(X)     /* No-op if we do not support a codec */
33525#endif
33526
33527/*
33528** Change the page size used by the Pager object. The new page size
33529** is passed in *pPageSize.
33530**
33531** If the pager is in the error state when this function is called, it
33532** is a no-op. The value returned is the error state error code (i.e.
33533** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
33534**
33535** Otherwise, if all of the following are true:
33536**
33537**   * the new page size (value of *pPageSize) is valid (a power
33538**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
33539**
33540**   * there are no outstanding page references, and
33541**
33542**   * the database is either not an in-memory database or it is
33543**     an in-memory database that currently consists of zero pages.
33544**
33545** then the pager object page size is set to *pPageSize.
33546**
33547** If the page size is changed, then this function uses sqlite3PagerMalloc()
33548** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
33549** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
33550** In all other cases, SQLITE_OK is returned.
33551**
33552** If the page size is not changed, either because one of the enumerated
33553** conditions above is not true, the pager was in error state when this
33554** function was called, or because the memory allocation attempt failed,
33555** then *pPageSize is set to the old, retained page size before returning.
33556*/
33557SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize, int nReserve){
33558  int rc = pPager->errCode;
33559
33560  if( rc==SQLITE_OK ){
33561    u16 pageSize = *pPageSize;
33562    assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
33563    if( (pPager->memDb==0 || pPager->dbSize==0)
33564     && sqlite3PcacheRefCount(pPager->pPCache)==0
33565     && pageSize && pageSize!=pPager->pageSize
33566    ){
33567      char *pNew = (char *)sqlite3PageMalloc(pageSize);
33568      if( !pNew ){
33569        rc = SQLITE_NOMEM;
33570      }else{
33571        pager_reset(pPager);
33572        pPager->pageSize = pageSize;
33573        sqlite3PageFree(pPager->pTmpSpace);
33574        pPager->pTmpSpace = pNew;
33575        sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
33576      }
33577    }
33578    *pPageSize = (u16)pPager->pageSize;
33579    if( nReserve<0 ) nReserve = pPager->nReserve;
33580    assert( nReserve>=0 && nReserve<1000 );
33581    pPager->nReserve = (i16)nReserve;
33582    pagerReportSize(pPager);
33583  }
33584  return rc;
33585}
33586
33587/*
33588** Return a pointer to the "temporary page" buffer held internally
33589** by the pager.  This is a buffer that is big enough to hold the
33590** entire content of a database page.  This buffer is used internally
33591** during rollback and will be overwritten whenever a rollback
33592** occurs.  But other modules are free to use it too, as long as
33593** no rollbacks are happening.
33594*/
33595SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
33596  return pPager->pTmpSpace;
33597}
33598
33599/*
33600** Attempt to set the maximum database page count if mxPage is positive.
33601** Make no changes if mxPage is zero or negative.  And never reduce the
33602** maximum page count below the current size of the database.
33603**
33604** Regardless of mxPage, return the current maximum page count.
33605*/
33606SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
33607  if( mxPage>0 ){
33608    pPager->mxPgno = mxPage;
33609  }
33610  sqlite3PagerPagecount(pPager, 0);
33611  return pPager->mxPgno;
33612}
33613
33614/*
33615** The following set of routines are used to disable the simulated
33616** I/O error mechanism.  These routines are used to avoid simulated
33617** errors in places where we do not care about errors.
33618**
33619** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
33620** and generate no code.
33621*/
33622#ifdef SQLITE_TEST
33623SQLITE_API extern int sqlite3_io_error_pending;
33624SQLITE_API extern int sqlite3_io_error_hit;
33625static int saved_cnt;
33626void disable_simulated_io_errors(void){
33627  saved_cnt = sqlite3_io_error_pending;
33628  sqlite3_io_error_pending = -1;
33629}
33630void enable_simulated_io_errors(void){
33631  sqlite3_io_error_pending = saved_cnt;
33632}
33633#else
33634# define disable_simulated_io_errors()
33635# define enable_simulated_io_errors()
33636#endif
33637
33638/*
33639** Read the first N bytes from the beginning of the file into memory
33640** that pDest points to.
33641**
33642** If the pager was opened on a transient file (zFilename==""), or
33643** opened on a file less than N bytes in size, the output buffer is
33644** zeroed and SQLITE_OK returned. The rationale for this is that this
33645** function is used to read database headers, and a new transient or
33646** zero sized database has a header than consists entirely of zeroes.
33647**
33648** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
33649** the error code is returned to the caller and the contents of the
33650** output buffer undefined.
33651*/
33652SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
33653  int rc = SQLITE_OK;
33654  memset(pDest, 0, N);
33655  assert( isOpen(pPager->fd) || pPager->tempFile );
33656  if( isOpen(pPager->fd) ){
33657    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
33658    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
33659    if( rc==SQLITE_IOERR_SHORT_READ ){
33660      rc = SQLITE_OK;
33661    }
33662  }
33663  return rc;
33664}
33665
33666/*
33667** Return the total number of pages in the database file associated
33668** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
33669** However, if the file is between 1 and <page-size> bytes in size, then
33670** this is considered a 1 page file.
33671**
33672** If the pager is in error state when this function is called, then the
33673** error state error code is returned and *pnPage left unchanged. Or,
33674** if the file system has to be queried for the size of the file and
33675** the query attempt returns an IO error, the IO error code is returned
33676** and *pnPage is left unchanged.
33677**
33678** Otherwise, if everything is successful, then SQLITE_OK is returned
33679** and *pnPage is set to the number of pages in the database.
33680*/
33681SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
33682  Pgno nPage;               /* Value to return via *pnPage */
33683
33684  /* If the pager is already in the error state, return the error code. */
33685  if( pPager->errCode ){
33686    return pPager->errCode;
33687  }
33688
33689  /* Determine the number of pages in the file. Store this in nPage. */
33690  if( pPager->dbSizeValid ){
33691    nPage = pPager->dbSize;
33692  }else{
33693    int rc;                 /* Error returned by OsFileSize() */
33694    i64 n = 0;              /* File size in bytes returned by OsFileSize() */
33695
33696    assert( isOpen(pPager->fd) || pPager->tempFile );
33697    if( isOpen(pPager->fd) && (0 != (rc = sqlite3OsFileSize(pPager->fd, &n))) ){
33698      pager_error(pPager, rc);
33699      return rc;
33700    }
33701    if( n>0 && n<pPager->pageSize ){
33702      nPage = 1;
33703    }else{
33704      nPage = (Pgno)(n / pPager->pageSize);
33705    }
33706    if( pPager->state!=PAGER_UNLOCK ){
33707      pPager->dbSize = nPage;
33708      pPager->dbFileSize = nPage;
33709      pPager->dbSizeValid = 1;
33710    }
33711  }
33712
33713  /* If the current number of pages in the file is greater than the
33714  ** configured maximum pager number, increase the allowed limit so
33715  ** that the file can be read.
33716  */
33717  if( nPage>pPager->mxPgno ){
33718    pPager->mxPgno = (Pgno)nPage;
33719  }
33720
33721  /* Set the output variable and return SQLITE_OK */
33722  if( pnPage ){
33723    *pnPage = nPage;
33724  }
33725  return SQLITE_OK;
33726}
33727
33728
33729/*
33730** Try to obtain a lock of type locktype on the database file. If
33731** a similar or greater lock is already held, this function is a no-op
33732** (returning SQLITE_OK immediately).
33733**
33734** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
33735** the busy callback if the lock is currently not available. Repeat
33736** until the busy callback returns false or until the attempt to
33737** obtain the lock succeeds.
33738**
33739** Return SQLITE_OK on success and an error code if we cannot obtain
33740** the lock. If the lock is obtained successfully, set the Pager.state
33741** variable to locktype before returning.
33742*/
33743static int pager_wait_on_lock(Pager *pPager, int locktype){
33744  int rc;                              /* Return code */
33745
33746  /* The OS lock values must be the same as the Pager lock values */
33747  assert( PAGER_SHARED==SHARED_LOCK );
33748  assert( PAGER_RESERVED==RESERVED_LOCK );
33749  assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
33750
33751  /* If the file is currently unlocked then the size must be unknown. It
33752  ** must not have been modified at this point.
33753  */
33754  assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
33755  assert( pPager->state>=PAGER_SHARED || pPager->dbModified==0 );
33756
33757  /* Check that this is either a no-op (because the requested lock is
33758  ** already held, or one of the transistions that the busy-handler
33759  ** may be invoked during, according to the comment above
33760  ** sqlite3PagerSetBusyhandler().
33761  */
33762  assert( (pPager->state>=locktype)
33763       || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
33764       || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
33765  );
33766
33767  if( pPager->state>=locktype ){
33768    rc = SQLITE_OK;
33769  }else{
33770    do {
33771      rc = sqlite3OsLock(pPager->fd, locktype);
33772    }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
33773    if( rc==SQLITE_OK ){
33774      pPager->state = (u8)locktype;
33775      IOTRACE(("LOCK %p %d\n", pPager, locktype))
33776    }
33777  }
33778  return rc;
33779}
33780
33781/*
33782** Function assertTruncateConstraint(pPager) checks that one of the
33783** following is true for all dirty pages currently in the page-cache:
33784**
33785**   a) The page number is less than or equal to the size of the
33786**      current database image, in pages, OR
33787**
33788**   b) if the page content were written at this time, it would not
33789**      be necessary to write the current content out to the sub-journal
33790**      (as determined by function subjRequiresPage()).
33791**
33792** If the condition asserted by this function were not true, and the
33793** dirty page were to be discarded from the cache via the pagerStress()
33794** routine, pagerStress() would not write the current page content to
33795** the database file. If a savepoint transaction were rolled back after
33796** this happened, the correct behaviour would be to restore the current
33797** content of the page. However, since this content is not present in either
33798** the database file or the portion of the rollback journal and
33799** sub-journal rolled back the content could not be restored and the
33800** database image would become corrupt. It is therefore fortunate that
33801** this circumstance cannot arise.
33802*/
33803#if defined(SQLITE_DEBUG)
33804static void assertTruncateConstraintCb(PgHdr *pPg){
33805  assert( pPg->flags&PGHDR_DIRTY );
33806  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
33807}
33808static void assertTruncateConstraint(Pager *pPager){
33809  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
33810}
33811#else
33812# define assertTruncateConstraint(pPager)
33813#endif
33814
33815/*
33816** Truncate the in-memory database file image to nPage pages. This
33817** function does not actually modify the database file on disk. It
33818** just sets the internal state of the pager object so that the
33819** truncation will be done when the current transaction is committed.
33820*/
33821SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
33822  assert( pPager->dbSizeValid );
33823  assert( pPager->dbSize>=nPage );
33824  assert( pPager->state>=PAGER_RESERVED );
33825  pPager->dbSize = nPage;
33826  assertTruncateConstraint(pPager);
33827}
33828
33829/*
33830** Shutdown the page cache.  Free all memory and close all files.
33831**
33832** If a transaction was in progress when this routine is called, that
33833** transaction is rolled back.  All outstanding pages are invalidated
33834** and their memory is freed.  Any attempt to use a page associated
33835** with this page cache after this function returns will likely
33836** result in a coredump.
33837**
33838** This function always succeeds. If a transaction is active an attempt
33839** is made to roll it back. If an error occurs during the rollback
33840** a hot journal may be left in the filesystem but no error is returned
33841** to the caller.
33842*/
33843SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
33844  disable_simulated_io_errors();
33845  sqlite3BeginBenignMalloc();
33846  pPager->errCode = 0;
33847  pPager->exclusiveMode = 0;
33848  pager_reset(pPager);
33849  if( MEMDB ){
33850    pager_unlock(pPager);
33851  }else{
33852    /* Set Pager.journalHdr to -1 for the benefit of the pager_playback()
33853    ** call which may be made from within pagerUnlockAndRollback(). If it
33854    ** is not -1, then the unsynced portion of an open journal file may
33855    ** be played back into the database. If a power failure occurs while
33856    ** this is happening, the database may become corrupt.
33857    */
33858    pPager->journalHdr = -1;
33859    pagerUnlockAndRollback(pPager);
33860  }
33861  sqlite3EndBenignMalloc();
33862  enable_simulated_io_errors();
33863  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
33864  IOTRACE(("CLOSE %p\n", pPager))
33865  sqlite3OsClose(pPager->fd);
33866  sqlite3PageFree(pPager->pTmpSpace);
33867  sqlite3PcacheClose(pPager->pPCache);
33868
33869#ifdef SQLITE_HAS_CODEC
33870  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
33871#endif
33872
33873  assert( !pPager->aSavepoint && !pPager->pInJournal );
33874  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
33875
33876  sqlite3_free(pPager);
33877  return SQLITE_OK;
33878}
33879
33880#if !defined(NDEBUG) || defined(SQLITE_TEST)
33881/*
33882** Return the page number for page pPg.
33883*/
33884SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
33885  return pPg->pgno;
33886}
33887#endif
33888
33889/*
33890** Increment the reference count for page pPg.
33891*/
33892SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
33893  sqlite3PcacheRef(pPg);
33894}
33895
33896/*
33897** Sync the journal. In other words, make sure all the pages that have
33898** been written to the journal have actually reached the surface of the
33899** disk and can be restored in the event of a hot-journal rollback.
33900**
33901** If the Pager.needSync flag is not set, then this function is a
33902** no-op. Otherwise, the actions required depend on the journal-mode
33903** and the device characteristics of the the file-system, as follows:
33904**
33905**   * If the journal file is an in-memory journal file, no action need
33906**     be taken.
33907**
33908**   * Otherwise, if the device does not support the SAFE_APPEND property,
33909**     then the nRec field of the most recently written journal header
33910**     is updated to contain the number of journal records that have
33911**     been written following it. If the pager is operating in full-sync
33912**     mode, then the journal file is synced before this field is updated.
33913**
33914**   * If the device does not support the SEQUENTIAL property, then
33915**     journal file is synced.
33916**
33917** Or, in pseudo-code:
33918**
33919**   if( NOT <in-memory journal> ){
33920**     if( NOT SAFE_APPEND ){
33921**       if( <full-sync mode> ) xSync(<journal file>);
33922**       <update nRec field>
33923**     }
33924**     if( NOT SEQUENTIAL ) xSync(<journal file>);
33925**   }
33926**
33927** The Pager.needSync flag is never be set for temporary files, or any
33928** file operating in no-sync mode (Pager.noSync set to non-zero).
33929**
33930** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
33931** page currently held in memory before returning SQLITE_OK. If an IO
33932** error is encountered, then the IO error code is returned to the caller.
33933*/
33934static int syncJournal(Pager *pPager){
33935  if( pPager->needSync ){
33936    assert( !pPager->tempFile );
33937    if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
33938      int rc;                              /* Return code */
33939      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
33940      assert( isOpen(pPager->jfd) );
33941
33942      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
33943        /* This block deals with an obscure problem. If the last connection
33944        ** that wrote to this database was operating in persistent-journal
33945        ** mode, then the journal file may at this point actually be larger
33946        ** than Pager.journalOff bytes. If the next thing in the journal
33947        ** file happens to be a journal-header (written as part of the
33948        ** previous connections transaction), and a crash or power-failure
33949        ** occurs after nRec is updated but before this connection writes
33950        ** anything else to the journal file (or commits/rolls back its
33951        ** transaction), then SQLite may become confused when doing the
33952        ** hot-journal rollback following recovery. It may roll back all
33953        ** of this connections data, then proceed to rolling back the old,
33954        ** out-of-date data that follows it. Database corruption.
33955        **
33956        ** To work around this, if the journal file does appear to contain
33957        ** a valid header following Pager.journalOff, then write a 0x00
33958        ** byte to the start of it to prevent it from being recognized.
33959        **
33960        ** Variable iNextHdrOffset is set to the offset at which this
33961        ** problematic header will occur, if it exists. aMagic is used
33962        ** as a temporary buffer to inspect the first couple of bytes of
33963        ** the potential journal header.
33964        */
33965        i64 iNextHdrOffset;
33966        u8 aMagic[8];
33967	u8 zHeader[sizeof(aJournalMagic)+4];
33968
33969	memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
33970	put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
33971
33972        iNextHdrOffset = journalHdrOffset(pPager);
33973        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
33974        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
33975          static const u8 zerobyte = 0;
33976          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
33977        }
33978        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
33979          return rc;
33980        }
33981
33982        /* Write the nRec value into the journal file header. If in
33983        ** full-synchronous mode, sync the journal first. This ensures that
33984        ** all data has really hit the disk before nRec is updated to mark
33985        ** it as a candidate for rollback.
33986        **
33987        ** This is not required if the persistent media supports the
33988        ** SAFE_APPEND property. Because in this case it is not possible
33989        ** for garbage data to be appended to the file, the nRec field
33990        ** is populated with 0xFFFFFFFF when the journal header is written
33991        ** and never needs to be updated.
33992        */
33993        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
33994          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
33995          IOTRACE(("JSYNC %p\n", pPager))
33996          rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
33997          if( rc!=SQLITE_OK ) return rc;
33998        }
33999        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
34000        rc = sqlite3OsWrite(
34001            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
34002	);
34003        if( rc!=SQLITE_OK ) return rc;
34004      }
34005      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
34006        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
34007        IOTRACE(("JSYNC %p\n", pPager))
34008        rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags|
34009          (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
34010        );
34011        if( rc!=SQLITE_OK ) return rc;
34012      }
34013    }
34014
34015    /* The journal file was just successfully synced. Set Pager.needSync
34016    ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
34017    */
34018    pPager->needSync = 0;
34019    pPager->journalStarted = 1;
34020    sqlite3PcacheClearSyncFlags(pPager->pPCache);
34021  }
34022
34023  return SQLITE_OK;
34024}
34025
34026/*
34027** The argument is the first in a linked list of dirty pages connected
34028** by the PgHdr.pDirty pointer. This function writes each one of the
34029** in-memory pages in the list to the database file. The argument may
34030** be NULL, representing an empty list. In this case this function is
34031** a no-op.
34032**
34033** The pager must hold at least a RESERVED lock when this function
34034** is called. Before writing anything to the database file, this lock
34035** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
34036** SQLITE_BUSY is returned and no data is written to the database file.
34037**
34038** If the pager is a temp-file pager and the actual file-system file
34039** is not yet open, it is created and opened before any data is
34040** written out.
34041**
34042** Once the lock has been upgraded and, if necessary, the file opened,
34043** the pages are written out to the database file in list order. Writing
34044** a page is skipped if it meets either of the following criteria:
34045**
34046**   * The page number is greater than Pager.dbSize, or
34047**   * The PGHDR_DONT_WRITE flag is set on the page.
34048**
34049** If writing out a page causes the database file to grow, Pager.dbFileSize
34050** is updated accordingly. If page 1 is written out, then the value cached
34051** in Pager.dbFileVers[] is updated to match the new value stored in
34052** the database file.
34053**
34054** If everything is successful, SQLITE_OK is returned. If an IO error
34055** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
34056** be obtained, SQLITE_BUSY is returned.
34057*/
34058static int pager_write_pagelist(PgHdr *pList){
34059  Pager *pPager;                       /* Pager object */
34060  int rc;                              /* Return code */
34061
34062  if( NEVER(pList==0) ) return SQLITE_OK;
34063  pPager = pList->pPager;
34064
34065  /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
34066  ** database file. If there is already an EXCLUSIVE lock, the following
34067  ** call is a no-op.
34068  **
34069  ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
34070  ** through an intermediate state PENDING.   A PENDING lock prevents new
34071  ** readers from attaching to the database but is unsufficient for us to
34072  ** write.  The idea of a PENDING lock is to prevent new readers from
34073  ** coming in while we wait for existing readers to clear.
34074  **
34075  ** While the pager is in the RESERVED state, the original database file
34076  ** is unchanged and we can rollback without having to playback the
34077  ** journal into the original database file.  Once we transition to
34078  ** EXCLUSIVE, it means the database file has been changed and any rollback
34079  ** will require a journal playback.
34080  */
34081  assert( pPager->state>=PAGER_RESERVED );
34082  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
34083
34084  /* If the file is a temp-file has not yet been opened, open it now. It
34085  ** is not possible for rc to be other than SQLITE_OK if this branch
34086  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
34087  */
34088  if( !isOpen(pPager->fd) ){
34089    assert( pPager->tempFile && rc==SQLITE_OK );
34090    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
34091  }
34092
34093  while( rc==SQLITE_OK && pList ){
34094    Pgno pgno = pList->pgno;
34095
34096    /* If there are dirty pages in the page cache with page numbers greater
34097    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
34098    ** make the file smaller (presumably by auto-vacuum code). Do not write
34099    ** any such pages to the file.
34100    **
34101    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
34102    ** set (set by sqlite3PagerDontWrite()).  Note that if compiled with
34103    ** SQLITE_SECURE_DELETE the PGHDR_DONT_WRITE bit is never set and so
34104    ** the second test is always true.
34105    */
34106    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
34107      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
34108      char *pData;                                   /* Data to write */
34109
34110      /* Encode the database */
34111      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
34112
34113      /* Write out the page data. */
34114      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
34115
34116      /* If page 1 was just written, update Pager.dbFileVers to match
34117      ** the value now stored in the database file. If writing this
34118      ** page caused the database file to grow, update dbFileSize.
34119      */
34120      if( pgno==1 ){
34121        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
34122      }
34123      if( pgno>pPager->dbFileSize ){
34124        pPager->dbFileSize = pgno;
34125      }
34126
34127      /* Update any backup objects copying the contents of this pager. */
34128      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
34129
34130      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
34131                   PAGERID(pPager), pgno, pager_pagehash(pList)));
34132      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
34133      PAGER_INCR(sqlite3_pager_writedb_count);
34134      PAGER_INCR(pPager->nWrite);
34135    }else{
34136      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
34137    }
34138#ifdef SQLITE_CHECK_PAGES
34139    pList->pageHash = pager_pagehash(pList);
34140#endif
34141    pList = pList->pDirty;
34142  }
34143
34144  return rc;
34145}
34146
34147/*
34148** Append a record of the current state of page pPg to the sub-journal.
34149** It is the callers responsibility to use subjRequiresPage() to check
34150** that it is really required before calling this function.
34151**
34152** If successful, set the bit corresponding to pPg->pgno in the bitvecs
34153** for all open savepoints before returning.
34154**
34155** This function returns SQLITE_OK if everything is successful, an IO
34156** error code if the attempt to write to the sub-journal fails, or
34157** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
34158** bitvec.
34159*/
34160static int subjournalPage(PgHdr *pPg){
34161  int rc = SQLITE_OK;
34162  Pager *pPager = pPg->pPager;
34163  if( isOpen(pPager->sjfd) ){
34164    void *pData = pPg->pData;
34165    i64 offset = pPager->nSubRec*(4+pPager->pageSize);
34166    char *pData2;
34167
34168    CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
34169    PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
34170
34171    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
34172    rc = write32bits(pPager->sjfd, offset, pPg->pgno);
34173    if( rc==SQLITE_OK ){
34174      rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
34175    }
34176  }
34177  if( rc==SQLITE_OK ){
34178    pPager->nSubRec++;
34179    assert( pPager->nSavepoint>0 );
34180    rc = addToSavepointBitvecs(pPager, pPg->pgno);
34181  }
34182  return rc;
34183}
34184
34185
34186/*
34187** This function is called by the pcache layer when it has reached some
34188** soft memory limit. The first argument is a pointer to a Pager object
34189** (cast as a void*). The pager is always 'purgeable' (not an in-memory
34190** database). The second argument is a reference to a page that is
34191** currently dirty but has no outstanding references. The page
34192** is always associated with the Pager object passed as the first
34193** argument.
34194**
34195** The job of this function is to make pPg clean by writing its contents
34196** out to the database file, if possible. This may involve syncing the
34197** journal file.
34198**
34199** If successful, sqlite3PcacheMakeClean() is called on the page and
34200** SQLITE_OK returned. If an IO error occurs while trying to make the
34201** page clean, the IO error code is returned. If the page cannot be
34202** made clean for some other reason, but no error occurs, then SQLITE_OK
34203** is returned by sqlite3PcacheMakeClean() is not called.
34204*/
34205static int pagerStress(void *p, PgHdr *pPg){
34206  Pager *pPager = (Pager *)p;
34207  int rc = SQLITE_OK;
34208
34209  assert( pPg->pPager==pPager );
34210  assert( pPg->flags&PGHDR_DIRTY );
34211
34212  /* The doNotSync flag is set by the sqlite3PagerWrite() function while it
34213  ** is journalling a set of two or more database pages that are stored
34214  ** on the same disk sector. Syncing the journal is not allowed while
34215  ** this is happening as it is important that all members of such a
34216  ** set of pages are synced to disk together. So, if the page this function
34217  ** is trying to make clean will require a journal sync and the doNotSync
34218  ** flag is set, return without doing anything. The pcache layer will
34219  ** just have to go ahead and allocate a new page buffer instead of
34220  ** reusing pPg.
34221  **
34222  ** Similarly, if the pager has already entered the error state, do not
34223  ** try to write the contents of pPg to disk.
34224  */
34225  if( NEVER(pPager->errCode)
34226   || (pPager->doNotSync && pPg->flags&PGHDR_NEED_SYNC)
34227  ){
34228    return SQLITE_OK;
34229  }
34230
34231  /* Sync the journal file if required. */
34232  if( pPg->flags&PGHDR_NEED_SYNC ){
34233    rc = syncJournal(pPager);
34234    if( rc==SQLITE_OK && pPager->fullSync &&
34235      !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
34236      !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
34237    ){
34238      pPager->nRec = 0;
34239      rc = writeJournalHdr(pPager);
34240    }
34241  }
34242
34243  /* If the page number of this page is larger than the current size of
34244  ** the database image, it may need to be written to the sub-journal.
34245  ** This is because the call to pager_write_pagelist() below will not
34246  ** actually write data to the file in this case.
34247  **
34248  ** Consider the following sequence of events:
34249  **
34250  **   BEGIN;
34251  **     <journal page X>
34252  **     <modify page X>
34253  **     SAVEPOINT sp;
34254  **       <shrink database file to Y pages>
34255  **       pagerStress(page X)
34256  **     ROLLBACK TO sp;
34257  **
34258  ** If (X>Y), then when pagerStress is called page X will not be written
34259  ** out to the database file, but will be dropped from the cache. Then,
34260  ** following the "ROLLBACK TO sp" statement, reading page X will read
34261  ** data from the database file. This will be the copy of page X as it
34262  ** was when the transaction started, not as it was when "SAVEPOINT sp"
34263  ** was executed.
34264  **
34265  ** The solution is to write the current data for page X into the
34266  ** sub-journal file now (if it is not already there), so that it will
34267  ** be restored to its current value when the "ROLLBACK TO sp" is
34268  ** executed.
34269  */
34270  if( NEVER(
34271      rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
34272  ) ){
34273    rc = subjournalPage(pPg);
34274  }
34275
34276  /* Write the contents of the page out to the database file. */
34277  if( rc==SQLITE_OK ){
34278    pPg->pDirty = 0;
34279    rc = pager_write_pagelist(pPg);
34280  }
34281
34282  /* Mark the page as clean. */
34283  if( rc==SQLITE_OK ){
34284    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
34285    sqlite3PcacheMakeClean(pPg);
34286  }
34287
34288  return pager_error(pPager, rc);
34289}
34290
34291
34292/*
34293** Allocate and initialize a new Pager object and put a pointer to it
34294** in *ppPager. The pager should eventually be freed by passing it
34295** to sqlite3PagerClose().
34296**
34297** The zFilename argument is the path to the database file to open.
34298** If zFilename is NULL then a randomly-named temporary file is created
34299** and used as the file to be cached. Temporary files are be deleted
34300** automatically when they are closed. If zFilename is ":memory:" then
34301** all information is held in cache. It is never written to disk.
34302** This can be used to implement an in-memory database.
34303**
34304** The nExtra parameter specifies the number of bytes of space allocated
34305** along with each page reference. This space is available to the user
34306** via the sqlite3PagerGetExtra() API.
34307**
34308** The flags argument is used to specify properties that affect the
34309** operation of the pager. It should be passed some bitwise combination
34310** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
34311**
34312** The vfsFlags parameter is a bitmask to pass to the flags parameter
34313** of the xOpen() method of the supplied VFS when opening files.
34314**
34315** If the pager object is allocated and the specified file opened
34316** successfully, SQLITE_OK is returned and *ppPager set to point to
34317** the new pager object. If an error occurs, *ppPager is set to NULL
34318** and error code returned. This function may return SQLITE_NOMEM
34319** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
34320** various SQLITE_IO_XXX errors.
34321*/
34322SQLITE_PRIVATE int sqlite3PagerOpen(
34323  sqlite3_vfs *pVfs,       /* The virtual file system to use */
34324  Pager **ppPager,         /* OUT: Return the Pager structure here */
34325  const char *zFilename,   /* Name of the database file to open */
34326  int nExtra,              /* Extra bytes append to each in-memory page */
34327  int flags,               /* flags controlling this file */
34328  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
34329  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
34330){
34331  u8 *pPtr;
34332  Pager *pPager = 0;       /* Pager object to allocate and return */
34333  int rc = SQLITE_OK;      /* Return code */
34334  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
34335  int memDb = 0;           /* True if this is an in-memory file */
34336  int readOnly = 0;        /* True if this is a read-only file */
34337  int journalFileSize;     /* Bytes to allocate for each journal fd */
34338  char *zPathname = 0;     /* Full path to database file */
34339  int nPathname = 0;       /* Number of bytes in zPathname */
34340  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
34341  int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
34342  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
34343  u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
34344
34345  /* Figure out how much space is required for each journal file-handle
34346  ** (there are two of them, the main journal and the sub-journal). This
34347  ** is the maximum space required for an in-memory journal file handle
34348  ** and a regular journal file-handle. Note that a "regular journal-handle"
34349  ** may be a wrapper capable of caching the first portion of the journal
34350  ** file in memory to implement the atomic-write optimization (see
34351  ** source file journal.c).
34352  */
34353  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
34354    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
34355  }else{
34356    journalFileSize = ROUND8(sqlite3MemJournalSize());
34357  }
34358
34359  /* Set the output variable to NULL in case an error occurs. */
34360  *ppPager = 0;
34361
34362  /* Compute and store the full pathname in an allocated buffer pointed
34363  ** to by zPathname, length nPathname. Or, if this is a temporary file,
34364  ** leave both nPathname and zPathname set to 0.
34365  */
34366  if( zFilename && zFilename[0] ){
34367    nPathname = pVfs->mxPathname+1;
34368    zPathname = sqlite3Malloc(nPathname*2);
34369    if( zPathname==0 ){
34370      return SQLITE_NOMEM;
34371    }
34372#ifndef SQLITE_OMIT_MEMORYDB
34373    if( strcmp(zFilename,":memory:")==0 ){
34374      memDb = 1;
34375      zPathname[0] = 0;
34376    }else
34377#endif
34378    {
34379      zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
34380      rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
34381    }
34382
34383    nPathname = sqlite3Strlen30(zPathname);
34384    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
34385      /* This branch is taken when the journal path required by
34386      ** the database being opened will be more than pVfs->mxPathname
34387      ** bytes in length. This means the database cannot be opened,
34388      ** as it will not be possible to open the journal file or even
34389      ** check for a hot-journal before reading.
34390      */
34391      rc = SQLITE_CANTOPEN;
34392    }
34393    if( rc!=SQLITE_OK ){
34394      sqlite3_free(zPathname);
34395      return rc;
34396    }
34397  }
34398
34399  /* Allocate memory for the Pager structure, PCache object, the
34400  ** three file descriptors, the database file name and the journal
34401  ** file name. The layout in memory is as follows:
34402  **
34403  **     Pager object                    (sizeof(Pager) bytes)
34404  **     PCache object                   (sqlite3PcacheSize() bytes)
34405  **     Database file handle            (pVfs->szOsFile bytes)
34406  **     Sub-journal file handle         (journalFileSize bytes)
34407  **     Main journal file handle        (journalFileSize bytes)
34408  **     Database file name              (nPathname+1 bytes)
34409  **     Journal file name               (nPathname+8+1 bytes)
34410  */
34411  pPtr = (u8 *)sqlite3MallocZero(
34412    ROUND8(sizeof(*pPager)) +      /* Pager structure */
34413    ROUND8(pcacheSize) +           /* PCache object */
34414    ROUND8(pVfs->szOsFile) +       /* The main db file */
34415    journalFileSize * 2 +          /* The two journal files */
34416    nPathname + 1 +                /* zFilename */
34417    nPathname + 8 + 1              /* zJournal */
34418  );
34419  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
34420  if( !pPtr ){
34421    sqlite3_free(zPathname);
34422    return SQLITE_NOMEM;
34423  }
34424  pPager =              (Pager*)(pPtr);
34425  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
34426  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
34427  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
34428  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
34429  pPager->zFilename =    (char*)(pPtr += journalFileSize);
34430  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
34431
34432  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
34433  if( zPathname ){
34434    pPager->zJournal =   (char*)(pPtr += nPathname + 1);
34435    memcpy(pPager->zFilename, zPathname, nPathname);
34436    memcpy(pPager->zJournal, zPathname, nPathname);
34437    memcpy(&pPager->zJournal[nPathname], "-journal", 8);
34438    if( pPager->zFilename[0]==0 ) pPager->zJournal[0] = 0;
34439    sqlite3_free(zPathname);
34440  }
34441  pPager->pVfs = pVfs;
34442  pPager->vfsFlags = vfsFlags;
34443
34444  /* Open the pager file.
34445  */
34446  if( zFilename && zFilename[0] && !memDb ){
34447    int fout = 0;                    /* VFS flags returned by xOpen() */
34448    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
34449    readOnly = (fout&SQLITE_OPEN_READONLY);
34450
34451    /* If the file was successfully opened for read/write access,
34452    ** choose a default page size in case we have to create the
34453    ** database file. The default page size is the maximum of:
34454    **
34455    **    + SQLITE_DEFAULT_PAGE_SIZE,
34456    **    + The value returned by sqlite3OsSectorSize()
34457    **    + The largest page size that can be written atomically.
34458    */
34459    if( rc==SQLITE_OK && !readOnly ){
34460      setSectorSize(pPager);
34461      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
34462      if( szPageDflt<pPager->sectorSize ){
34463        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
34464          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
34465        }else{
34466          szPageDflt = (u16)pPager->sectorSize;
34467        }
34468      }
34469#ifdef SQLITE_ENABLE_ATOMIC_WRITE
34470      {
34471        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
34472        int ii;
34473        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
34474        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
34475        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
34476        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
34477          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
34478            szPageDflt = ii;
34479          }
34480        }
34481      }
34482#endif
34483    }
34484  }else{
34485    /* If a temporary file is requested, it is not opened immediately.
34486    ** In this case we accept the default page size and delay actually
34487    ** opening the file until the first call to OsWrite().
34488    **
34489    ** This branch is also run for an in-memory database. An in-memory
34490    ** database is the same as a temp-file that is never written out to
34491    ** disk and uses an in-memory rollback journal.
34492    */
34493    tempFile = 1;
34494    pPager->state = PAGER_EXCLUSIVE;
34495    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
34496  }
34497
34498  /* The following call to PagerSetPagesize() serves to set the value of
34499  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
34500  */
34501  if( rc==SQLITE_OK ){
34502    assert( pPager->memDb==0 );
34503    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
34504    testcase( rc!=SQLITE_OK );
34505  }
34506
34507  /* If an error occurred in either of the blocks above, free the
34508  ** Pager structure and close the file.
34509  */
34510  if( rc!=SQLITE_OK ){
34511    assert( !pPager->pTmpSpace );
34512    sqlite3OsClose(pPager->fd);
34513    sqlite3_free(pPager);
34514    return rc;
34515  }
34516
34517  /* Initialize the PCache object. */
34518  assert( nExtra<1000 );
34519  nExtra = ROUND8(nExtra);
34520  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
34521                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
34522
34523  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
34524  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
34525
34526  pPager->useJournal = (u8)useJournal;
34527  pPager->noReadlock = (noReadlock && readOnly) ?1:0;
34528  /* pPager->stmtOpen = 0; */
34529  /* pPager->stmtInUse = 0; */
34530  /* pPager->nRef = 0; */
34531  pPager->dbSizeValid = (u8)memDb;
34532  /* pPager->stmtSize = 0; */
34533  /* pPager->stmtJSize = 0; */
34534  /* pPager->nPage = 0; */
34535  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
34536  /* pPager->state = PAGER_UNLOCK; */
34537  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
34538  /* pPager->errMask = 0; */
34539  pPager->tempFile = (u8)tempFile;
34540  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
34541          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
34542  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
34543  pPager->exclusiveMode = (u8)tempFile;
34544  pPager->changeCountDone = pPager->tempFile;
34545  pPager->memDb = (u8)memDb;
34546  pPager->readOnly = (u8)readOnly;
34547  /* pPager->needSync = 0; */
34548  assert( useJournal || pPager->tempFile );
34549  pPager->noSync = pPager->tempFile;
34550  pPager->fullSync = pPager->noSync ?0:1;
34551  pPager->sync_flags = SQLITE_SYNC_NORMAL;
34552  /* pPager->pFirst = 0; */
34553  /* pPager->pFirstSynced = 0; */
34554  /* pPager->pLast = 0; */
34555  pPager->nExtra = (u16)nExtra;
34556  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
34557  assert( isOpen(pPager->fd) || tempFile );
34558  setSectorSize(pPager);
34559  if( !useJournal ){
34560    pPager->journalMode = PAGER_JOURNALMODE_OFF;
34561  }else if( memDb ){
34562    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
34563  }
34564  /* pPager->xBusyHandler = 0; */
34565  /* pPager->pBusyHandlerArg = 0; */
34566  pPager->xReiniter = xReinit;
34567  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
34568  *ppPager = pPager;
34569  return SQLITE_OK;
34570}
34571
34572
34573
34574/*
34575** This function is called after transitioning from PAGER_UNLOCK to
34576** PAGER_SHARED state. It tests if there is a hot journal present in
34577** the file-system for the given pager. A hot journal is one that
34578** needs to be played back. According to this function, a hot-journal
34579** file exists if the following criteria are met:
34580**
34581**   * The journal file exists in the file system, and
34582**   * No process holds a RESERVED or greater lock on the database file, and
34583**   * The database file itself is greater than 0 bytes in size, and
34584**   * The first byte of the journal file exists and is not 0x00.
34585**
34586** If the current size of the database file is 0 but a journal file
34587** exists, that is probably an old journal left over from a prior
34588** database with the same name. In this case the journal file is
34589** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
34590** is returned.
34591**
34592** This routine does not check if there is a master journal filename
34593** at the end of the file. If there is, and that master journal file
34594** does not exist, then the journal file is not really hot. In this
34595** case this routine will return a false-positive. The pager_playback()
34596** routine will discover that the journal file is not really hot and
34597** will not roll it back.
34598**
34599** If a hot-journal file is found to exist, *pExists is set to 1 and
34600** SQLITE_OK returned. If no hot-journal file is present, *pExists is
34601** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
34602** to determine whether or not a hot-journal file exists, the IO error
34603** code is returned and the value of *pExists is undefined.
34604*/
34605static int hasHotJournal(Pager *pPager, int *pExists){
34606  sqlite3_vfs * const pVfs = pPager->pVfs;
34607  int rc;                       /* Return code */
34608  int exists;                   /* True if a journal file is present */
34609
34610  assert( pPager!=0 );
34611  assert( pPager->useJournal );
34612  assert( isOpen(pPager->fd) );
34613  assert( !isOpen(pPager->jfd) );
34614  assert( pPager->state <= PAGER_SHARED );
34615
34616  *pExists = 0;
34617  rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
34618  if( rc==SQLITE_OK && exists ){
34619    int locked;                 /* True if some process holds a RESERVED lock */
34620
34621    /* Race condition here:  Another process might have been holding the
34622    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
34623    ** call above, but then delete the journal and drop the lock before
34624    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
34625    ** is the case, this routine might think there is a hot journal when
34626    ** in fact there is none.  This results in a false-positive which will
34627    ** be dealt with by the playback routine.  Ticket #3883.
34628    */
34629    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
34630    if( rc==SQLITE_OK && !locked ){
34631      int nPage;
34632
34633      /* Check the size of the database file. If it consists of 0 pages,
34634      ** then delete the journal file. See the header comment above for
34635      ** the reasoning here.  Delete the obsolete journal file under
34636      ** a RESERVED lock to avoid race conditions and to avoid violating
34637      ** [H33020].
34638      */
34639      rc = sqlite3PagerPagecount(pPager, &nPage);
34640      if( rc==SQLITE_OK ){
34641        if( nPage==0 ){
34642          sqlite3BeginBenignMalloc();
34643          if( sqlite3OsLock(pPager->fd, RESERVED_LOCK)==SQLITE_OK ){
34644            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
34645            sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
34646          }
34647          sqlite3EndBenignMalloc();
34648        }else{
34649          /* The journal file exists and no other connection has a reserved
34650          ** or greater lock on the database file. Now check that there is
34651          ** at least one non-zero bytes at the start of the journal file.
34652          ** If there is, then we consider this journal to be hot. If not,
34653          ** it can be ignored.
34654          */
34655          int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
34656          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
34657          if( rc==SQLITE_OK ){
34658            u8 first = 0;
34659            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
34660            if( rc==SQLITE_IOERR_SHORT_READ ){
34661              rc = SQLITE_OK;
34662            }
34663            sqlite3OsClose(pPager->jfd);
34664            *pExists = (first!=0);
34665          }else if( rc==SQLITE_CANTOPEN ){
34666            /* If we cannot open the rollback journal file in order to see if
34667            ** its has a zero header, that might be due to an I/O error, or
34668            ** it might be due to the race condition described above and in
34669            ** ticket #3883.  Either way, assume that the journal is hot.
34670            ** This might be a false positive.  But if it is, then the
34671            ** automatic journal playback and recovery mechanism will deal
34672            ** with it under an EXCLUSIVE lock where we do not need to
34673            ** worry so much with race conditions.
34674            */
34675            *pExists = 1;
34676            rc = SQLITE_OK;
34677          }
34678        }
34679      }
34680    }
34681  }
34682
34683  return rc;
34684}
34685
34686/*
34687** Read the content for page pPg out of the database file and into
34688** pPg->pData. A shared lock or greater must be held on the database
34689** file before this function is called.
34690**
34691** If page 1 is read, then the value of Pager.dbFileVers[] is set to
34692** the value read from the database file.
34693**
34694** If an IO error occurs, then the IO error is returned to the caller.
34695** Otherwise, SQLITE_OK is returned.
34696*/
34697static int readDbPage(PgHdr *pPg){
34698  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
34699  Pgno pgno = pPg->pgno;       /* Page number to read */
34700  int rc;                      /* Return code */
34701  i64 iOffset;                 /* Byte offset of file to read from */
34702
34703  assert( pPager->state>=PAGER_SHARED && !MEMDB );
34704  assert( isOpen(pPager->fd) );
34705
34706  if( NEVER(!isOpen(pPager->fd)) ){
34707    assert( pPager->tempFile );
34708    memset(pPg->pData, 0, pPager->pageSize);
34709    return SQLITE_OK;
34710  }
34711  iOffset = (pgno-1)*(i64)pPager->pageSize;
34712  rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
34713  if( rc==SQLITE_IOERR_SHORT_READ ){
34714    rc = SQLITE_OK;
34715  }
34716  if( pgno==1 ){
34717    u8 *dbFileVers = &((u8*)pPg->pData)[24];
34718    memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
34719  }
34720  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
34721
34722  PAGER_INCR(sqlite3_pager_readdb_count);
34723  PAGER_INCR(pPager->nRead);
34724  IOTRACE(("PGIN %p %d\n", pPager, pgno));
34725  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
34726               PAGERID(pPager), pgno, pager_pagehash(pPg)));
34727
34728  return rc;
34729}
34730
34731/*
34732** This function is called to obtain a shared lock on the database file.
34733** It is illegal to call sqlite3PagerAcquire() until after this function
34734** has been successfully called. If a shared-lock is already held when
34735** this function is called, it is a no-op.
34736**
34737** The following operations are also performed by this function.
34738**
34739**   1) If the pager is currently in PAGER_UNLOCK state (no lock held
34740**      on the database file), then an attempt is made to obtain a
34741**      SHARED lock on the database file. Immediately after obtaining
34742**      the SHARED lock, the file-system is checked for a hot-journal,
34743**      which is played back if present. Following any hot-journal
34744**      rollback, the contents of the cache are validated by checking
34745**      the 'change-counter' field of the database file header and
34746**      discarded if they are found to be invalid.
34747**
34748**   2) If the pager is running in exclusive-mode, and there are currently
34749**      no outstanding references to any pages, and is in the error state,
34750**      then an attempt is made to clear the error state by discarding
34751**      the contents of the page cache and rolling back any open journal
34752**      file.
34753**
34754** If the operation described by (2) above is not attempted, and if the
34755** pager is in an error state other than SQLITE_FULL when this is called,
34756** the error state error code is returned. It is permitted to read the
34757** database when in SQLITE_FULL error state.
34758**
34759** Otherwise, if everything is successful, SQLITE_OK is returned. If an
34760** IO error occurs while locking the database, checking for a hot-journal
34761** file or rolling back a journal file, the IO error code is returned.
34762*/
34763SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
34764  int rc = SQLITE_OK;                /* Return code */
34765  int isErrorReset = 0;              /* True if recovering from error state */
34766
34767  /* This routine is only called from b-tree and only when there are no
34768  ** outstanding pages */
34769  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
34770  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
34771
34772  /* If this database is in an error-state, now is a chance to clear
34773  ** the error. Discard the contents of the pager-cache and rollback
34774  ** any hot journal in the file-system.
34775  */
34776  if( pPager->errCode ){
34777    if( isOpen(pPager->jfd) || pPager->zJournal ){
34778      isErrorReset = 1;
34779    }
34780    pPager->errCode = SQLITE_OK;
34781    pager_reset(pPager);
34782  }
34783
34784  if( pPager->state==PAGER_UNLOCK || isErrorReset ){
34785    sqlite3_vfs * const pVfs = pPager->pVfs;
34786    int isHotJournal = 0;
34787    assert( !MEMDB );
34788    assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
34789    if( pPager->noReadlock ){
34790      assert( pPager->readOnly );
34791      pPager->state = PAGER_SHARED;
34792    }else{
34793      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
34794      if( rc!=SQLITE_OK ){
34795        assert( pPager->state==PAGER_UNLOCK );
34796        return pager_error(pPager, rc);
34797      }
34798    }
34799    assert( pPager->state>=SHARED_LOCK );
34800
34801    /* If a journal file exists, and there is no RESERVED lock on the
34802    ** database file, then it either needs to be played back or deleted.
34803    */
34804    if( !isErrorReset ){
34805      assert( pPager->state <= PAGER_SHARED );
34806      rc = hasHotJournal(pPager, &isHotJournal);
34807      if( rc!=SQLITE_OK ){
34808        goto failed;
34809      }
34810    }
34811    if( isErrorReset || isHotJournal ){
34812      /* Get an EXCLUSIVE lock on the database file. At this point it is
34813      ** important that a RESERVED lock is not obtained on the way to the
34814      ** EXCLUSIVE lock. If it were, another process might open the
34815      ** database file, detect the RESERVED lock, and conclude that the
34816      ** database is safe to read while this process is still rolling the
34817      ** hot-journal back.
34818      **
34819      ** Because the intermediate RESERVED lock is not requested, any
34820      ** other process attempting to access the database file will get to
34821      ** this point in the code and fail to obtain its own EXCLUSIVE lock
34822      ** on the database file.
34823      */
34824      if( pPager->state<EXCLUSIVE_LOCK ){
34825        rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
34826        if( rc!=SQLITE_OK ){
34827          rc = pager_error(pPager, rc);
34828          goto failed;
34829        }
34830        pPager->state = PAGER_EXCLUSIVE;
34831      }
34832
34833      /* Open the journal for read/write access. This is because in
34834      ** exclusive-access mode the file descriptor will be kept open and
34835      ** possibly used for a transaction later on. On some systems, the
34836      ** OsTruncate() call used in exclusive-access mode also requires
34837      ** a read/write file handle.
34838      */
34839      if( !isOpen(pPager->jfd) ){
34840        int res;
34841        rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
34842        if( rc==SQLITE_OK ){
34843          if( res ){
34844            int fout = 0;
34845            int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
34846            assert( !pPager->tempFile );
34847            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
34848            assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
34849            if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
34850              rc = SQLITE_CANTOPEN;
34851              sqlite3OsClose(pPager->jfd);
34852            }
34853          }else{
34854            /* If the journal does not exist, it usually means that some
34855            ** other connection managed to get in and roll it back before
34856            ** this connection obtained the exclusive lock above. Or, it
34857            ** may mean that the pager was in the error-state when this
34858            ** function was called and the journal file does not exist.  */
34859            rc = pager_end_transaction(pPager, 0);
34860          }
34861        }
34862      }
34863      if( rc!=SQLITE_OK ){
34864        goto failed;
34865      }
34866
34867      /* TODO: Why are these cleared here? Is it necessary? */
34868      pPager->journalStarted = 0;
34869      pPager->journalOff = 0;
34870      pPager->setMaster = 0;
34871      pPager->journalHdr = 0;
34872
34873      /* Playback and delete the journal.  Drop the database write
34874      ** lock and reacquire the read lock. Purge the cache before
34875      ** playing back the hot-journal so that we don't end up with
34876      ** an inconsistent cache.
34877      */
34878      if( isOpen(pPager->jfd) ){
34879        rc = pager_playback(pPager, 1);
34880        if( rc!=SQLITE_OK ){
34881          rc = pager_error(pPager, rc);
34882          goto failed;
34883        }
34884      }
34885      assert( (pPager->state==PAGER_SHARED)
34886           || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
34887      );
34888    }
34889
34890    if( pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0 ){
34891      /* The shared-lock has just been acquired on the database file
34892      ** and there are already pages in the cache (from a previous
34893      ** read or write transaction).  Check to see if the database
34894      ** has been modified.  If the database has changed, flush the
34895      ** cache.
34896      **
34897      ** Database changes is detected by looking at 15 bytes beginning
34898      ** at offset 24 into the file.  The first 4 of these 16 bytes are
34899      ** a 32-bit counter that is incremented with each change.  The
34900      ** other bytes change randomly with each file change when
34901      ** a codec is in use.
34902      **
34903      ** There is a vanishingly small chance that a change will not be
34904      ** detected.  The chance of an undetected change is so small that
34905      ** it can be neglected.
34906      */
34907      char dbFileVers[sizeof(pPager->dbFileVers)];
34908      sqlite3PagerPagecount(pPager, 0);
34909
34910      if( pPager->errCode ){
34911        rc = pPager->errCode;
34912        goto failed;
34913      }
34914
34915      assert( pPager->dbSizeValid );
34916      if( pPager->dbSize>0 ){
34917        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
34918        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
34919        if( rc!=SQLITE_OK ){
34920          goto failed;
34921        }
34922      }else{
34923        memset(dbFileVers, 0, sizeof(dbFileVers));
34924      }
34925
34926      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
34927        pager_reset(pPager);
34928      }
34929    }
34930    assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
34931  }
34932
34933 failed:
34934  if( rc!=SQLITE_OK ){
34935    /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
34936    pager_unlock(pPager);
34937  }
34938  return rc;
34939}
34940
34941/*
34942** If the reference count has reached zero, rollback any active
34943** transaction and unlock the pager.
34944**
34945** Except, in locking_mode=EXCLUSIVE when there is nothing to in
34946** the rollback journal, the unlock is not performed and there is
34947** nothing to rollback, so this routine is a no-op.
34948*/
34949static void pagerUnlockIfUnused(Pager *pPager){
34950  if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
34951   && (!pPager->exclusiveMode || pPager->journalOff>0)
34952  ){
34953    pagerUnlockAndRollback(pPager);
34954  }
34955}
34956
34957/*
34958** Acquire a reference to page number pgno in pager pPager (a page
34959** reference has type DbPage*). If the requested reference is
34960** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
34961**
34962** If the requested page is already in the cache, it is returned.
34963** Otherwise, a new page object is allocated and populated with data
34964** read from the database file. In some cases, the pcache module may
34965** choose not to allocate a new page object and may reuse an existing
34966** object with no outstanding references.
34967**
34968** The extra data appended to a page is always initialized to zeros the
34969** first time a page is loaded into memory. If the page requested is
34970** already in the cache when this function is called, then the extra
34971** data is left as it was when the page object was last used.
34972**
34973** If the database image is smaller than the requested page or if a
34974** non-zero value is passed as the noContent parameter and the
34975** requested page is not already stored in the cache, then no
34976** actual disk read occurs. In this case the memory image of the
34977** page is initialized to all zeros.
34978**
34979** If noContent is true, it means that we do not care about the contents
34980** of the page. This occurs in two seperate scenarios:
34981**
34982**   a) When reading a free-list leaf page from the database, and
34983**
34984**   b) When a savepoint is being rolled back and we need to load
34985**      a new page into the cache to populate with the data read
34986**      from the savepoint journal.
34987**
34988** If noContent is true, then the data returned is zeroed instead of
34989** being read from the database. Additionally, the bits corresponding
34990** to pgno in Pager.pInJournal (bitvec of pages already written to the
34991** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
34992** savepoints are set. This means if the page is made writable at any
34993** point in the future, using a call to sqlite3PagerWrite(), its contents
34994** will not be journaled. This saves IO.
34995**
34996** The acquisition might fail for several reasons.  In all cases,
34997** an appropriate error code is returned and *ppPage is set to NULL.
34998**
34999** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
35000** to find a page in the in-memory cache first.  If the page is not already
35001** in memory, this routine goes to disk to read it in whereas Lookup()
35002** just returns 0.  This routine acquires a read-lock the first time it
35003** has to go to disk, and could also playback an old journal if necessary.
35004** Since Lookup() never goes to disk, it never has to deal with locks
35005** or journal files.
35006*/
35007SQLITE_PRIVATE int sqlite3PagerAcquire(
35008  Pager *pPager,      /* The pager open on the database file */
35009  Pgno pgno,          /* Page number to fetch */
35010  DbPage **ppPage,    /* Write a pointer to the page here */
35011  int noContent       /* Do not bother reading content from disk if true */
35012){
35013  int rc;
35014  PgHdr *pPg;
35015
35016  assert( assert_pager_state(pPager) );
35017  assert( pPager->state>PAGER_UNLOCK );
35018
35019  if( pgno==0 ){
35020    return SQLITE_CORRUPT_BKPT;
35021  }
35022
35023  /* If the pager is in the error state, return an error immediately.
35024  ** Otherwise, request the page from the PCache layer. */
35025  if( pPager->errCode!=SQLITE_OK && pPager->errCode!=SQLITE_FULL ){
35026    rc = pPager->errCode;
35027  }else{
35028    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
35029  }
35030
35031  if( rc!=SQLITE_OK ){
35032    /* Either the call to sqlite3PcacheFetch() returned an error or the
35033    ** pager was already in the error-state when this function was called.
35034    ** Set pPg to 0 and jump to the exception handler.  */
35035    pPg = 0;
35036    goto pager_acquire_err;
35037  }
35038  assert( (*ppPage)->pgno==pgno );
35039  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
35040
35041  if( (*ppPage)->pPager ){
35042    /* In this case the pcache already contains an initialized copy of
35043    ** the page. Return without further ado.  */
35044    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
35045    PAGER_INCR(pPager->nHit);
35046    return SQLITE_OK;
35047
35048  }else{
35049    /* The pager cache has created a new page. Its content needs to
35050    ** be initialized.  */
35051    int nMax;
35052
35053    PAGER_INCR(pPager->nMiss);
35054    pPg = *ppPage;
35055    pPg->pPager = pPager;
35056
35057    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
35058    ** number greater than this, or the unused locking-page, is requested. */
35059    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
35060      rc = SQLITE_CORRUPT_BKPT;
35061      goto pager_acquire_err;
35062    }
35063
35064    rc = sqlite3PagerPagecount(pPager, &nMax);
35065    if( rc!=SQLITE_OK ){
35066      goto pager_acquire_err;
35067    }
35068
35069    if( MEMDB || nMax<(int)pgno || noContent ){
35070      if( pgno>pPager->mxPgno ){
35071	rc = SQLITE_FULL;
35072	goto pager_acquire_err;
35073      }
35074      if( noContent ){
35075        /* Failure to set the bits in the InJournal bit-vectors is benign.
35076        ** It merely means that we might do some extra work to journal a
35077        ** page that does not need to be journaled.  Nevertheless, be sure
35078        ** to test the case where a malloc error occurs while trying to set
35079        ** a bit in a bit vector.
35080        */
35081        sqlite3BeginBenignMalloc();
35082        if( pgno<=pPager->dbOrigSize ){
35083          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
35084          testcase( rc==SQLITE_NOMEM );
35085        }
35086        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
35087        testcase( rc==SQLITE_NOMEM );
35088        sqlite3EndBenignMalloc();
35089      }
35090      memset(pPg->pData, 0, pPager->pageSize);
35091      IOTRACE(("ZERO %p %d\n", pPager, pgno));
35092    }else{
35093      assert( pPg->pPager==pPager );
35094      rc = readDbPage(pPg);
35095      if( rc!=SQLITE_OK ){
35096        goto pager_acquire_err;
35097      }
35098    }
35099#ifdef SQLITE_CHECK_PAGES
35100    pPg->pageHash = pager_pagehash(pPg);
35101#endif
35102  }
35103
35104  return SQLITE_OK;
35105
35106pager_acquire_err:
35107  assert( rc!=SQLITE_OK );
35108  if( pPg ){
35109    sqlite3PcacheDrop(pPg);
35110  }
35111  pagerUnlockIfUnused(pPager);
35112
35113  *ppPage = 0;
35114  return rc;
35115}
35116
35117/*
35118** Acquire a page if it is already in the in-memory cache.  Do
35119** not read the page from disk.  Return a pointer to the page,
35120** or 0 if the page is not in cache. Also, return 0 if the
35121** pager is in PAGER_UNLOCK state when this function is called,
35122** or if the pager is in an error state other than SQLITE_FULL.
35123**
35124** See also sqlite3PagerGet().  The difference between this routine
35125** and sqlite3PagerGet() is that _get() will go to the disk and read
35126** in the page if the page is not already in cache.  This routine
35127** returns NULL if the page is not in cache or if a disk I/O error
35128** has ever happened.
35129*/
35130SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
35131  PgHdr *pPg = 0;
35132  assert( pPager!=0 );
35133  assert( pgno!=0 );
35134  assert( pPager->pPCache!=0 );
35135  assert( pPager->state > PAGER_UNLOCK );
35136  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
35137  return pPg;
35138}
35139
35140/*
35141** Release a page reference.
35142**
35143** If the number of references to the page drop to zero, then the
35144** page is added to the LRU list.  When all references to all pages
35145** are released, a rollback occurs and the lock on the database is
35146** removed.
35147*/
35148SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
35149  if( pPg ){
35150    Pager *pPager = pPg->pPager;
35151    sqlite3PcacheRelease(pPg);
35152    pagerUnlockIfUnused(pPager);
35153  }
35154}
35155
35156/*
35157** If the main journal file has already been opened, ensure that the
35158** sub-journal file is open too. If the main journal is not open,
35159** this function is a no-op.
35160**
35161** SQLITE_OK is returned if everything goes according to plan.
35162** An SQLITE_IOERR_XXX error code is returned if a call to
35163** sqlite3OsOpen() fails.
35164*/
35165static int openSubJournal(Pager *pPager){
35166  int rc = SQLITE_OK;
35167  if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
35168    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
35169      sqlite3MemJournalOpen(pPager->sjfd);
35170    }else{
35171      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
35172    }
35173  }
35174  return rc;
35175}
35176
35177/*
35178** This function is called at the start of every write transaction.
35179** There must already be a RESERVED or EXCLUSIVE lock on the database
35180** file when this routine is called.
35181**
35182** Open the journal file for pager pPager and write a journal header
35183** to the start of it. If there are active savepoints, open the sub-journal
35184** as well. This function is only used when the journal file is being
35185** opened to write a rollback log for a transaction. It is not used
35186** when opening a hot journal file to roll it back.
35187**
35188** If the journal file is already open (as it may be in exclusive mode),
35189** then this function just writes a journal header to the start of the
35190** already open file.
35191**
35192** Whether or not the journal file is opened by this function, the
35193** Pager.pInJournal bitvec structure is allocated.
35194**
35195** Return SQLITE_OK if everything is successful. Otherwise, return
35196** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
35197** an IO error code if opening or writing the journal file fails.
35198*/
35199static int pager_open_journal(Pager *pPager){
35200  int rc = SQLITE_OK;                        /* Return code */
35201  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
35202
35203  assert( pPager->state>=PAGER_RESERVED );
35204  assert( pPager->useJournal );
35205  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF );
35206  assert( pPager->pInJournal==0 );
35207
35208  /* If already in the error state, this function is a no-op.  But on
35209  ** the other hand, this routine is never called if we are already in
35210  ** an error state. */
35211  if( NEVER(pPager->errCode) ) return pPager->errCode;
35212
35213  /* TODO: Is it really possible to get here with dbSizeValid==0? If not,
35214  ** the call to PagerPagecount() can be removed.
35215  */
35216  testcase( pPager->dbSizeValid==0 );
35217  sqlite3PagerPagecount(pPager, 0);
35218
35219  pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
35220  if( pPager->pInJournal==0 ){
35221    return SQLITE_NOMEM;
35222  }
35223
35224  /* Open the journal file if it is not already open. */
35225  if( !isOpen(pPager->jfd) ){
35226    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
35227      sqlite3MemJournalOpen(pPager->jfd);
35228    }else{
35229      const int flags =                   /* VFS flags to open journal file */
35230        SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
35231        (pPager->tempFile ?
35232          (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
35233          (SQLITE_OPEN_MAIN_JOURNAL)
35234        );
35235#ifdef SQLITE_ENABLE_ATOMIC_WRITE
35236      rc = sqlite3JournalOpen(
35237          pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
35238      );
35239#else
35240      rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
35241#endif
35242    }
35243    assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
35244  }
35245
35246
35247  /* Write the first journal header to the journal file and open
35248  ** the sub-journal if necessary.
35249  */
35250  if( rc==SQLITE_OK ){
35251    /* TODO: Check if all of these are really required. */
35252    pPager->dbOrigSize = pPager->dbSize;
35253    pPager->journalStarted = 0;
35254    pPager->needSync = 0;
35255    pPager->nRec = 0;
35256    pPager->journalOff = 0;
35257    pPager->setMaster = 0;
35258    pPager->journalHdr = 0;
35259    rc = writeJournalHdr(pPager);
35260  }
35261  if( rc==SQLITE_OK && pPager->nSavepoint ){
35262    rc = openSubJournal(pPager);
35263  }
35264
35265  if( rc!=SQLITE_OK ){
35266    sqlite3BitvecDestroy(pPager->pInJournal);
35267    pPager->pInJournal = 0;
35268  }
35269  return rc;
35270}
35271
35272/*
35273** Begin a write-transaction on the specified pager object. If a
35274** write-transaction has already been opened, this function is a no-op.
35275**
35276** If the exFlag argument is false, then acquire at least a RESERVED
35277** lock on the database file. If exFlag is true, then acquire at least
35278** an EXCLUSIVE lock. If such a lock is already held, no locking
35279** functions need be called.
35280**
35281** If this is not a temporary or in-memory file and, the journal file is
35282** opened if it has not been already. For a temporary file, the opening
35283** of the journal file is deferred until there is an actual need to
35284** write to the journal. TODO: Why handle temporary files differently?
35285**
35286** If the journal file is opened (or if it is already open), then a
35287** journal-header is written to the start of it.
35288**
35289** If the subjInMemory argument is non-zero, then any sub-journal opened
35290** within this transaction will be opened as an in-memory file. This
35291** has no effect if the sub-journal is already opened (as it may be when
35292** running in exclusive mode) or if the transaction does not require a
35293** sub-journal. If the subjInMemory argument is zero, then any required
35294** sub-journal is implemented in-memory if pPager is an in-memory database,
35295** or using a temporary file otherwise.
35296*/
35297SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
35298  int rc = SQLITE_OK;
35299  assert( pPager->state!=PAGER_UNLOCK );
35300  pPager->subjInMemory = (u8)subjInMemory;
35301  if( pPager->state==PAGER_SHARED ){
35302    assert( pPager->pInJournal==0 );
35303    assert( !MEMDB && !pPager->tempFile );
35304
35305    /* Obtain a RESERVED lock on the database file. If the exFlag parameter
35306    ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
35307    ** busy-handler callback can be used when upgrading to the EXCLUSIVE
35308    ** lock, but not when obtaining the RESERVED lock.
35309    */
35310    rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
35311    if( rc==SQLITE_OK ){
35312      pPager->state = PAGER_RESERVED;
35313      if( exFlag ){
35314        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
35315      }
35316    }
35317
35318    /* If the required locks were successfully obtained, open the journal
35319    ** file and write the first journal-header to it.
35320    */
35321    if( rc==SQLITE_OK && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
35322      rc = pager_open_journal(pPager);
35323    }
35324  }else if( isOpen(pPager->jfd) && pPager->journalOff==0 ){
35325    /* This happens when the pager was in exclusive-access mode the last
35326    ** time a (read or write) transaction was successfully concluded
35327    ** by this connection. Instead of deleting the journal file it was
35328    ** kept open and either was truncated to 0 bytes or its header was
35329    ** overwritten with zeros.
35330    */
35331    assert( pPager->nRec==0 );
35332    assert( pPager->dbOrigSize==0 );
35333    assert( pPager->pInJournal==0 );
35334    rc = pager_open_journal(pPager);
35335  }
35336
35337  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
35338  assert( !isOpen(pPager->jfd) || pPager->journalOff>0 || rc!=SQLITE_OK );
35339  if( rc!=SQLITE_OK ){
35340    assert( !pPager->dbModified );
35341    /* Ignore any IO error that occurs within pager_end_transaction(). The
35342    ** purpose of this call is to reset the internal state of the pager
35343    ** sub-system. It doesn't matter if the journal-file is not properly
35344    ** finalized at this point (since it is not a valid journal file anyway).
35345    */
35346    pager_end_transaction(pPager, 0);
35347  }
35348  return rc;
35349}
35350
35351/*
35352** Mark a single data page as writeable. The page is written into the
35353** main journal or sub-journal as required. If the page is written into
35354** one of the journals, the corresponding bit is set in the
35355** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
35356** of any open savepoints as appropriate.
35357*/
35358static int pager_write(PgHdr *pPg){
35359  void *pData = pPg->pData;
35360  Pager *pPager = pPg->pPager;
35361  int rc = SQLITE_OK;
35362
35363  /* This routine is not called unless a transaction has already been
35364  ** started.
35365  */
35366  assert( pPager->state>=PAGER_RESERVED );
35367
35368  /* If an error has been previously detected, we should not be
35369  ** calling this routine.  Repeat the error for robustness.
35370  */
35371  if( NEVER(pPager->errCode) )  return pPager->errCode;
35372
35373  /* Higher-level routines never call this function if database is not
35374  ** writable.  But check anyway, just for robustness. */
35375  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
35376
35377  assert( !pPager->setMaster );
35378
35379  CHECK_PAGE(pPg);
35380
35381  /* Mark the page as dirty.  If the page has already been written
35382  ** to the journal then we can return right away.
35383  */
35384  sqlite3PcacheMakeDirty(pPg);
35385  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
35386    pPager->dbModified = 1;
35387  }else{
35388
35389    /* If we get this far, it means that the page needs to be
35390    ** written to the transaction journal or the ckeckpoint journal
35391    ** or both.
35392    **
35393    ** Higher level routines should have already started a transaction,
35394    ** which means they have acquired the necessary locks and opened
35395    ** a rollback journal.  Double-check to makes sure this is the case.
35396    */
35397    rc = sqlite3PagerBegin(pPager, 0, pPager->subjInMemory);
35398    if( NEVER(rc!=SQLITE_OK) ){
35399      return rc;
35400    }
35401    if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
35402      assert( pPager->useJournal );
35403      rc = pager_open_journal(pPager);
35404      if( rc!=SQLITE_OK ) return rc;
35405    }
35406    pPager->dbModified = 1;
35407
35408    /* The transaction journal now exists and we have a RESERVED or an
35409    ** EXCLUSIVE lock on the main database file.  Write the current page to
35410    ** the transaction journal if it is not there already.
35411    */
35412    if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
35413      if( pPg->pgno<=pPager->dbOrigSize ){
35414        u32 cksum;
35415        char *pData2;
35416
35417        /* We should never write to the journal file the page that
35418        ** contains the database locks.  The following assert verifies
35419        ** that we do not. */
35420        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
35421        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
35422        cksum = pager_cksum(pPager, (u8*)pData2);
35423        rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
35424        if( rc==SQLITE_OK ){
35425          rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
35426                              pPager->journalOff + 4);
35427          pPager->journalOff += pPager->pageSize+4;
35428        }
35429        if( rc==SQLITE_OK ){
35430          rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
35431          pPager->journalOff += 4;
35432        }
35433        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
35434                 pPager->journalOff, pPager->pageSize));
35435        PAGER_INCR(sqlite3_pager_writej_count);
35436        PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
35437             PAGERID(pPager), pPg->pgno,
35438             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
35439
35440        /* Even if an IO or diskfull error occurred while journalling the
35441        ** page in the block above, set the need-sync flag for the page.
35442        ** Otherwise, when the transaction is rolled back, the logic in
35443        ** playback_one_page() will think that the page needs to be restored
35444        ** in the database file. And if an IO error occurs while doing so,
35445        ** then corruption may follow.
35446        */
35447        if( !pPager->noSync ){
35448          pPg->flags |= PGHDR_NEED_SYNC;
35449          pPager->needSync = 1;
35450        }
35451
35452        /* An error has occurred writing to the journal file. The
35453        ** transaction will be rolled back by the layer above.
35454        */
35455        if( rc!=SQLITE_OK ){
35456          return rc;
35457        }
35458
35459        pPager->nRec++;
35460        assert( pPager->pInJournal!=0 );
35461        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
35462        testcase( rc==SQLITE_NOMEM );
35463        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
35464        rc |= addToSavepointBitvecs(pPager, pPg->pgno);
35465        if( rc!=SQLITE_OK ){
35466          assert( rc==SQLITE_NOMEM );
35467          return rc;
35468        }
35469      }else{
35470        if( !pPager->journalStarted && !pPager->noSync ){
35471          pPg->flags |= PGHDR_NEED_SYNC;
35472          pPager->needSync = 1;
35473        }
35474        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
35475                PAGERID(pPager), pPg->pgno,
35476               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
35477      }
35478    }
35479
35480    /* If the statement journal is open and the page is not in it,
35481    ** then write the current page to the statement journal.  Note that
35482    ** the statement journal format differs from the standard journal format
35483    ** in that it omits the checksums and the header.
35484    */
35485    if( subjRequiresPage(pPg) ){
35486      rc = subjournalPage(pPg);
35487    }
35488  }
35489
35490  /* Update the database size and return.
35491  */
35492  assert( pPager->state>=PAGER_SHARED );
35493  if( pPager->dbSize<pPg->pgno ){
35494    pPager->dbSize = pPg->pgno;
35495  }
35496  return rc;
35497}
35498
35499/*
35500** Mark a data page as writeable. This routine must be called before
35501** making changes to a page. The caller must check the return value
35502** of this function and be careful not to change any page data unless
35503** this routine returns SQLITE_OK.
35504**
35505** The difference between this function and pager_write() is that this
35506** function also deals with the special case where 2 or more pages
35507** fit on a single disk sector. In this case all co-resident pages
35508** must have been written to the journal file before returning.
35509**
35510** If an error occurs, SQLITE_NOMEM or an IO error code is returned
35511** as appropriate. Otherwise, SQLITE_OK.
35512*/
35513SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
35514  int rc = SQLITE_OK;
35515
35516  PgHdr *pPg = pDbPage;
35517  Pager *pPager = pPg->pPager;
35518  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
35519
35520  if( nPagePerSector>1 ){
35521    Pgno nPageCount;          /* Total number of pages in database file */
35522    Pgno pg1;                 /* First page of the sector pPg is located on. */
35523    int nPage;                /* Number of pages starting at pg1 to journal */
35524    int ii;                   /* Loop counter */
35525    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
35526
35527    /* Set the doNotSync flag to 1. This is because we cannot allow a journal
35528    ** header to be written between the pages journaled by this function.
35529    */
35530    assert( !MEMDB );
35531    assert( pPager->doNotSync==0 );
35532    pPager->doNotSync = 1;
35533
35534    /* This trick assumes that both the page-size and sector-size are
35535    ** an integer power of 2. It sets variable pg1 to the identifier
35536    ** of the first page of the sector pPg is located on.
35537    */
35538    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
35539
35540    sqlite3PagerPagecount(pPager, (int *)&nPageCount);
35541    if( pPg->pgno>nPageCount ){
35542      nPage = (pPg->pgno - pg1)+1;
35543    }else if( (pg1+nPagePerSector-1)>nPageCount ){
35544      nPage = nPageCount+1-pg1;
35545    }else{
35546      nPage = nPagePerSector;
35547    }
35548    assert(nPage>0);
35549    assert(pg1<=pPg->pgno);
35550    assert((pg1+nPage)>pPg->pgno);
35551
35552    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
35553      Pgno pg = pg1+ii;
35554      PgHdr *pPage;
35555      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
35556        if( pg!=PAGER_MJ_PGNO(pPager) ){
35557          rc = sqlite3PagerGet(pPager, pg, &pPage);
35558          if( rc==SQLITE_OK ){
35559            rc = pager_write(pPage);
35560            if( pPage->flags&PGHDR_NEED_SYNC ){
35561              needSync = 1;
35562              assert(pPager->needSync);
35563            }
35564            sqlite3PagerUnref(pPage);
35565          }
35566        }
35567      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
35568        if( pPage->flags&PGHDR_NEED_SYNC ){
35569          needSync = 1;
35570        }
35571        sqlite3PagerUnref(pPage);
35572      }
35573    }
35574
35575    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
35576    ** starting at pg1, then it needs to be set for all of them. Because
35577    ** writing to any of these nPage pages may damage the others, the
35578    ** journal file must contain sync()ed copies of all of them
35579    ** before any of them can be written out to the database file.
35580    */
35581    if( rc==SQLITE_OK && needSync ){
35582      assert( !MEMDB && pPager->noSync==0 );
35583      for(ii=0; ii<nPage; ii++){
35584        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
35585        if( pPage ){
35586          pPage->flags |= PGHDR_NEED_SYNC;
35587          sqlite3PagerUnref(pPage);
35588        }
35589      }
35590      assert(pPager->needSync);
35591    }
35592
35593    assert( pPager->doNotSync==1 );
35594    pPager->doNotSync = 0;
35595  }else{
35596    rc = pager_write(pDbPage);
35597  }
35598  return rc;
35599}
35600
35601/*
35602** Return TRUE if the page given in the argument was previously passed
35603** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
35604** to change the content of the page.
35605*/
35606#ifndef NDEBUG
35607SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
35608  return pPg->flags&PGHDR_DIRTY;
35609}
35610#endif
35611
35612#ifndef SQLITE_SECURE_DELETE
35613/*
35614** A call to this routine tells the pager that it is not necessary to
35615** write the information on page pPg back to the disk, even though
35616** that page might be marked as dirty.  This happens, for example, when
35617** the page has been added as a leaf of the freelist and so its
35618** content no longer matters.
35619**
35620** The overlying software layer calls this routine when all of the data
35621** on the given page is unused. The pager marks the page as clean so
35622** that it does not get written to disk.
35623**
35624** Tests show that this optimization can quadruple the speed of large
35625** DELETE operations.
35626*/
35627SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
35628  Pager *pPager = pPg->pPager;
35629  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
35630    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
35631    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
35632    pPg->flags |= PGHDR_DONT_WRITE;
35633#ifdef SQLITE_CHECK_PAGES
35634    pPg->pageHash = pager_pagehash(pPg);
35635#endif
35636  }
35637}
35638#endif /* !defined(SQLITE_SECURE_DELETE) */
35639
35640/*
35641** This routine is called to increment the value of the database file
35642** change-counter, stored as a 4-byte big-endian integer starting at
35643** byte offset 24 of the pager file.
35644**
35645** If the isDirectMode flag is zero, then this is done by calling
35646** sqlite3PagerWrite() on page 1, then modifying the contents of the
35647** page data. In this case the file will be updated when the current
35648** transaction is committed.
35649**
35650** The isDirectMode flag may only be non-zero if the library was compiled
35651** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
35652** if isDirect is non-zero, then the database file is updated directly
35653** by writing an updated version of page 1 using a call to the
35654** sqlite3OsWrite() function.
35655*/
35656static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
35657  int rc = SQLITE_OK;
35658
35659  /* Declare and initialize constant integer 'isDirect'. If the
35660  ** atomic-write optimization is enabled in this build, then isDirect
35661  ** is initialized to the value passed as the isDirectMode parameter
35662  ** to this function. Otherwise, it is always set to zero.
35663  **
35664  ** The idea is that if the atomic-write optimization is not
35665  ** enabled at compile time, the compiler can omit the tests of
35666  ** 'isDirect' below, as well as the block enclosed in the
35667  ** "if( isDirect )" condition.
35668  */
35669#ifndef SQLITE_ENABLE_ATOMIC_WRITE
35670# define DIRECT_MODE 0
35671  assert( isDirectMode==0 );
35672  UNUSED_PARAMETER(isDirectMode);
35673#else
35674# define DIRECT_MODE isDirectMode
35675#endif
35676
35677  assert( pPager->state>=PAGER_RESERVED );
35678  if( !pPager->changeCountDone && pPager->dbSize>0 ){
35679    PgHdr *pPgHdr;                /* Reference to page 1 */
35680    u32 change_counter;           /* Initial value of change-counter field */
35681
35682    assert( !pPager->tempFile && isOpen(pPager->fd) );
35683
35684    /* Open page 1 of the file for writing. */
35685    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
35686    assert( pPgHdr==0 || rc==SQLITE_OK );
35687
35688    /* If page one was fetched successfully, and this function is not
35689    ** operating in direct-mode, make page 1 writable.  When not in
35690    ** direct mode, page 1 is always held in cache and hence the PagerGet()
35691    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
35692    */
35693    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
35694      rc = sqlite3PagerWrite(pPgHdr);
35695    }
35696
35697    if( rc==SQLITE_OK ){
35698      /* Increment the value just read and write it back to byte 24. */
35699      change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
35700      change_counter++;
35701      put32bits(((char*)pPgHdr->pData)+24, change_counter);
35702
35703      /* If running in direct mode, write the contents of page 1 to the file. */
35704      if( DIRECT_MODE ){
35705        const void *zBuf = pPgHdr->pData;
35706        assert( pPager->dbFileSize>0 );
35707        rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
35708        if( rc==SQLITE_OK ){
35709          pPager->changeCountDone = 1;
35710        }
35711      }else{
35712        pPager->changeCountDone = 1;
35713      }
35714    }
35715
35716    /* Release the page reference. */
35717    sqlite3PagerUnref(pPgHdr);
35718  }
35719  return rc;
35720}
35721
35722/*
35723** Sync the pager file to disk. This is a no-op for in-memory files
35724** or pages with the Pager.noSync flag set.
35725**
35726** If successful, or called on a pager for which it is a no-op, this
35727** function returns SQLITE_OK. Otherwise, an IO error code is returned.
35728*/
35729SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
35730  int rc;                              /* Return code */
35731  assert( !MEMDB );
35732  if( pPager->noSync ){
35733    rc = SQLITE_OK;
35734  }else{
35735    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
35736  }
35737  return rc;
35738}
35739
35740/*
35741** Sync the database file for the pager pPager. zMaster points to the name
35742** of a master journal file that should be written into the individual
35743** journal file. zMaster may be NULL, which is interpreted as no master
35744** journal (a single database transaction).
35745**
35746** This routine ensures that:
35747**
35748**   * The database file change-counter is updated,
35749**   * the journal is synced (unless the atomic-write optimization is used),
35750**   * all dirty pages are written to the database file,
35751**   * the database file is truncated (if required), and
35752**   * the database file synced.
35753**
35754** The only thing that remains to commit the transaction is to finalize
35755** (delete, truncate or zero the first part of) the journal file (or
35756** delete the master journal file if specified).
35757**
35758** Note that if zMaster==NULL, this does not overwrite a previous value
35759** passed to an sqlite3PagerCommitPhaseOne() call.
35760**
35761** If the final parameter - noSync - is true, then the database file itself
35762** is not synced. The caller must call sqlite3PagerSync() directly to
35763** sync the database file before calling CommitPhaseTwo() to delete the
35764** journal file in this case.
35765*/
35766SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
35767  Pager *pPager,                  /* Pager object */
35768  const char *zMaster,            /* If not NULL, the master journal name */
35769  int noSync                      /* True to omit the xSync on the db file */
35770){
35771  int rc = SQLITE_OK;             /* Return code */
35772
35773  /* The dbOrigSize is never set if journal_mode=OFF */
35774  assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF || pPager->dbOrigSize==0 );
35775
35776  /* If a prior error occurred, this routine should not be called.  ROLLBACK
35777  ** is the appropriate response to an error, not COMMIT.  Guard against
35778  ** coding errors by repeating the prior error. */
35779  if( NEVER(pPager->errCode) ) return pPager->errCode;
35780
35781  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
35782      pPager->zFilename, zMaster, pPager->dbSize));
35783
35784  if( MEMDB && pPager->dbModified ){
35785    /* If this is an in-memory db, or no pages have been written to, or this
35786    ** function has already been called, it is mostly a no-op.  However, any
35787    ** backup in progress needs to be restarted.
35788    */
35789    sqlite3BackupRestart(pPager->pBackup);
35790  }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){
35791
35792    /* The following block updates the change-counter. Exactly how it
35793    ** does this depends on whether or not the atomic-update optimization
35794    ** was enabled at compile time, and if this transaction meets the
35795    ** runtime criteria to use the operation:
35796    **
35797    **    * The file-system supports the atomic-write property for
35798    **      blocks of size page-size, and
35799    **    * This commit is not part of a multi-file transaction, and
35800    **    * Exactly one page has been modified and store in the journal file.
35801    **
35802    ** If the optimization was not enabled at compile time, then the
35803    ** pager_incr_changecounter() function is called to update the change
35804    ** counter in 'indirect-mode'. If the optimization is compiled in but
35805    ** is not applicable to this transaction, call sqlite3JournalCreate()
35806    ** to make sure the journal file has actually been created, then call
35807    ** pager_incr_changecounter() to update the change-counter in indirect
35808    ** mode.
35809    **
35810    ** Otherwise, if the optimization is both enabled and applicable,
35811    ** then call pager_incr_changecounter() to update the change-counter
35812    ** in 'direct' mode. In this case the journal file will never be
35813    ** created for this transaction.
35814    */
35815#ifdef SQLITE_ENABLE_ATOMIC_WRITE
35816    PgHdr *pPg;
35817    assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF );
35818    if( !zMaster && isOpen(pPager->jfd)
35819     && pPager->journalOff==jrnlBufferSize(pPager)
35820     && pPager->dbSize>=pPager->dbFileSize
35821     && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
35822    ){
35823      /* Update the db file change counter via the direct-write method. The
35824      ** following call will modify the in-memory representation of page 1
35825      ** to include the updated change counter and then write page 1
35826      ** directly to the database file. Because of the atomic-write
35827      ** property of the host file-system, this is safe.
35828      */
35829      rc = pager_incr_changecounter(pPager, 1);
35830    }else{
35831      rc = sqlite3JournalCreate(pPager->jfd);
35832      if( rc==SQLITE_OK ){
35833        rc = pager_incr_changecounter(pPager, 0);
35834      }
35835    }
35836#else
35837    rc = pager_incr_changecounter(pPager, 0);
35838#endif
35839    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35840
35841    /* If this transaction has made the database smaller, then all pages
35842    ** being discarded by the truncation must be written to the journal
35843    ** file. This can only happen in auto-vacuum mode.
35844    **
35845    ** Before reading the pages with page numbers larger than the
35846    ** current value of Pager.dbSize, set dbSize back to the value
35847    ** that it took at the start of the transaction. Otherwise, the
35848    ** calls to sqlite3PagerGet() return zeroed pages instead of
35849    ** reading data from the database file.
35850    **
35851    ** When journal_mode==OFF the dbOrigSize is always zero, so this
35852    ** block never runs if journal_mode=OFF.
35853    */
35854#ifndef SQLITE_OMIT_AUTOVACUUM
35855    if( pPager->dbSize<pPager->dbOrigSize
35856     && ALWAYS(pPager->journalMode!=PAGER_JOURNALMODE_OFF)
35857    ){
35858      Pgno i;                                   /* Iterator variable */
35859      const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
35860      const Pgno dbSize = pPager->dbSize;       /* Database image size */
35861      pPager->dbSize = pPager->dbOrigSize;
35862      for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
35863        if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
35864          PgHdr *pPage;             /* Page to journal */
35865          rc = sqlite3PagerGet(pPager, i, &pPage);
35866          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35867          rc = sqlite3PagerWrite(pPage);
35868          sqlite3PagerUnref(pPage);
35869          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35870        }
35871      }
35872      pPager->dbSize = dbSize;
35873    }
35874#endif
35875
35876    /* Write the master journal name into the journal file. If a master
35877    ** journal file name has already been written to the journal file,
35878    ** or if zMaster is NULL (no master journal), then this call is a no-op.
35879    */
35880    rc = writeMasterJournal(pPager, zMaster);
35881    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35882
35883    /* Sync the journal file. If the atomic-update optimization is being
35884    ** used, this call will not create the journal file or perform any
35885    ** real IO.
35886    */
35887    rc = syncJournal(pPager);
35888    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35889
35890    /* Write all dirty pages to the database file. */
35891    rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager->pPCache));
35892    if( rc!=SQLITE_OK ){
35893      assert( rc!=SQLITE_IOERR_BLOCKED );
35894      goto commit_phase_one_exit;
35895    }
35896    sqlite3PcacheCleanAll(pPager->pPCache);
35897
35898    /* If the file on disk is not the same size as the database image,
35899    ** then use pager_truncate to grow or shrink the file here.
35900    */
35901    if( pPager->dbSize!=pPager->dbFileSize ){
35902      Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
35903      assert( pPager->state>=PAGER_EXCLUSIVE );
35904      rc = pager_truncate(pPager, nNew);
35905      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
35906    }
35907
35908    /* Finally, sync the database file. */
35909    if( !pPager->noSync && !noSync ){
35910      rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
35911    }
35912    IOTRACE(("DBSYNC %p\n", pPager))
35913
35914    pPager->state = PAGER_SYNCED;
35915  }
35916
35917commit_phase_one_exit:
35918  return rc;
35919}
35920
35921
35922/*
35923** When this function is called, the database file has been completely
35924** updated to reflect the changes made by the current transaction and
35925** synced to disk. The journal file still exists in the file-system
35926** though, and if a failure occurs at this point it will eventually
35927** be used as a hot-journal and the current transaction rolled back.
35928**
35929** This function finalizes the journal file, either by deleting,
35930** truncating or partially zeroing it, so that it cannot be used
35931** for hot-journal rollback. Once this is done the transaction is
35932** irrevocably committed.
35933**
35934** If an error occurs, an IO error code is returned and the pager
35935** moves into the error state. Otherwise, SQLITE_OK is returned.
35936*/
35937SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
35938  int rc = SQLITE_OK;                  /* Return code */
35939
35940  /* This routine should not be called if a prior error has occurred.
35941  ** But if (due to a coding error elsewhere in the system) it does get
35942  ** called, just return the same error code without doing anything. */
35943  if( NEVER(pPager->errCode) ) return pPager->errCode;
35944
35945  /* This function should not be called if the pager is not in at least
35946  ** PAGER_RESERVED state. And indeed SQLite never does this. But it is
35947  ** nice to have this defensive test here anyway.
35948  */
35949  if( NEVER(pPager->state<PAGER_RESERVED) ) return SQLITE_ERROR;
35950
35951  /* An optimization. If the database was not actually modified during
35952  ** this transaction, the pager is running in exclusive-mode and is
35953  ** using persistent journals, then this function is a no-op.
35954  **
35955  ** The start of the journal file currently contains a single journal
35956  ** header with the nRec field set to 0. If such a journal is used as
35957  ** a hot-journal during hot-journal rollback, 0 changes will be made
35958  ** to the database file. So there is no need to zero the journal
35959  ** header. Since the pager is in exclusive mode, there is no need
35960  ** to drop any locks either.
35961  */
35962  if( pPager->dbModified==0 && pPager->exclusiveMode
35963   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
35964  ){
35965    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
35966    return SQLITE_OK;
35967  }
35968
35969  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
35970  assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
35971  rc = pager_end_transaction(pPager, pPager->setMaster);
35972  return pager_error(pPager, rc);
35973}
35974
35975/*
35976** Rollback all changes. The database falls back to PAGER_SHARED mode.
35977**
35978** This function performs two tasks:
35979**
35980**   1) It rolls back the journal file, restoring all database file and
35981**      in-memory cache pages to the state they were in when the transaction
35982**      was opened, and
35983**   2) It finalizes the journal file, so that it is not used for hot
35984**      rollback at any point in the future.
35985**
35986** subject to the following qualifications:
35987**
35988** * If the journal file is not yet open when this function is called,
35989**   then only (2) is performed. In this case there is no journal file
35990**   to roll back.
35991**
35992** * If in an error state other than SQLITE_FULL, then task (1) is
35993**   performed. If successful, task (2). Regardless of the outcome
35994**   of either, the error state error code is returned to the caller
35995**   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
35996**
35997** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
35998**   or not (1) is succussful, also attempt (2). If successful, return
35999**   SQLITE_OK. Otherwise, enter the error state and return the first
36000**   error code encountered.
36001**
36002**   In this case there is no chance that the database was written to.
36003**   So is safe to finalize the journal file even if the playback
36004**   (operation 1) failed. However the pager must enter the error state
36005**   as the contents of the in-memory cache are now suspect.
36006**
36007** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
36008**   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
36009**   otherwise enter the error state and return the error code from the
36010**   failing operation.
36011**
36012**   In this case the database file may have been written to. So if the
36013**   playback operation did not succeed it would not be safe to finalize
36014**   the journal file. It needs to be left in the file-system so that
36015**   some other process can use it to restore the database state (by
36016**   hot-journal rollback).
36017*/
36018SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
36019  int rc = SQLITE_OK;                  /* Return code */
36020  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
36021  if( !pPager->dbModified || !isOpen(pPager->jfd) ){
36022    rc = pager_end_transaction(pPager, pPager->setMaster);
36023  }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
36024    if( pPager->state>=PAGER_EXCLUSIVE ){
36025      pager_playback(pPager, 0);
36026    }
36027    rc = pPager->errCode;
36028  }else{
36029    if( pPager->state==PAGER_RESERVED ){
36030      int rc2;
36031      rc = pager_playback(pPager, 0);
36032      rc2 = pager_end_transaction(pPager, pPager->setMaster);
36033      if( rc==SQLITE_OK ){
36034        rc = rc2;
36035      }
36036    }else{
36037      rc = pager_playback(pPager, 0);
36038    }
36039
36040    if( !MEMDB ){
36041      pPager->dbSizeValid = 0;
36042    }
36043
36044    /* If an error occurs during a ROLLBACK, we can no longer trust the pager
36045    ** cache. So call pager_error() on the way out to make any error
36046    ** persistent.
36047    */
36048    rc = pager_error(pPager, rc);
36049  }
36050  return rc;
36051}
36052
36053/*
36054** Return TRUE if the database file is opened read-only.  Return FALSE
36055** if the database is (in theory) writable.
36056*/
36057SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
36058  return pPager->readOnly;
36059}
36060
36061/*
36062** Return the number of references to the pager.
36063*/
36064SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
36065  return sqlite3PcacheRefCount(pPager->pPCache);
36066}
36067
36068/*
36069** Return the number of references to the specified page.
36070*/
36071SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
36072  return sqlite3PcachePageRefcount(pPage);
36073}
36074
36075#ifdef SQLITE_TEST
36076/*
36077** This routine is used for testing and analysis only.
36078*/
36079SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
36080  static int a[11];
36081  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
36082  a[1] = sqlite3PcachePagecount(pPager->pPCache);
36083  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
36084  a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
36085  a[4] = pPager->state;
36086  a[5] = pPager->errCode;
36087  a[6] = pPager->nHit;
36088  a[7] = pPager->nMiss;
36089  a[8] = 0;  /* Used to be pPager->nOvfl */
36090  a[9] = pPager->nRead;
36091  a[10] = pPager->nWrite;
36092  return a;
36093}
36094#endif
36095
36096/*
36097** Return true if this is an in-memory pager.
36098*/
36099SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
36100  return MEMDB;
36101}
36102
36103/*
36104** Check that there are at least nSavepoint savepoints open. If there are
36105** currently less than nSavepoints open, then open one or more savepoints
36106** to make up the difference. If the number of savepoints is already
36107** equal to nSavepoint, then this function is a no-op.
36108**
36109** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
36110** occurs while opening the sub-journal file, then an IO error code is
36111** returned. Otherwise, SQLITE_OK.
36112*/
36113SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
36114  int rc = SQLITE_OK;                       /* Return code */
36115  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
36116
36117  if( nSavepoint>nCurrent && pPager->useJournal ){
36118    int ii;                                 /* Iterator variable */
36119    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
36120
36121    /* Either there is no active journal or the sub-journal is open or
36122    ** the journal is always stored in memory */
36123    assert( pPager->nSavepoint==0 || isOpen(pPager->sjfd) ||
36124            pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
36125
36126    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
36127    ** if the allocation fails. Otherwise, zero the new portion in case a
36128    ** malloc failure occurs while populating it in the for(...) loop below.
36129    */
36130    aNew = (PagerSavepoint *)sqlite3Realloc(
36131        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
36132    );
36133    if( !aNew ){
36134      return SQLITE_NOMEM;
36135    }
36136    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
36137    pPager->aSavepoint = aNew;
36138    pPager->nSavepoint = nSavepoint;
36139
36140    /* Populate the PagerSavepoint structures just allocated. */
36141    for(ii=nCurrent; ii<nSavepoint; ii++){
36142      assert( pPager->dbSizeValid );
36143      aNew[ii].nOrig = pPager->dbSize;
36144      if( isOpen(pPager->jfd) && ALWAYS(pPager->journalOff>0) ){
36145        aNew[ii].iOffset = pPager->journalOff;
36146      }else{
36147        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
36148      }
36149      aNew[ii].iSubRec = pPager->nSubRec;
36150      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
36151      if( !aNew[ii].pInSavepoint ){
36152        return SQLITE_NOMEM;
36153      }
36154    }
36155
36156    /* Open the sub-journal, if it is not already opened. */
36157    rc = openSubJournal(pPager);
36158    assertTruncateConstraint(pPager);
36159  }
36160
36161  return rc;
36162}
36163
36164/*
36165** This function is called to rollback or release (commit) a savepoint.
36166** The savepoint to release or rollback need not be the most recently
36167** created savepoint.
36168**
36169** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
36170** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
36171** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
36172** that have occurred since the specified savepoint was created.
36173**
36174** The savepoint to rollback or release is identified by parameter
36175** iSavepoint. A value of 0 means to operate on the outermost savepoint
36176** (the first created). A value of (Pager.nSavepoint-1) means operate
36177** on the most recently created savepoint. If iSavepoint is greater than
36178** (Pager.nSavepoint-1), then this function is a no-op.
36179**
36180** If a negative value is passed to this function, then the current
36181** transaction is rolled back. This is different to calling
36182** sqlite3PagerRollback() because this function does not terminate
36183** the transaction or unlock the database, it just restores the
36184** contents of the database to its original state.
36185**
36186** In any case, all savepoints with an index greater than iSavepoint
36187** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
36188** then savepoint iSavepoint is also destroyed.
36189**
36190** This function may return SQLITE_NOMEM if a memory allocation fails,
36191** or an IO error code if an IO error occurs while rolling back a
36192** savepoint. If no errors occur, SQLITE_OK is returned.
36193*/
36194SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
36195  int rc = SQLITE_OK;
36196
36197  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
36198  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
36199
36200  if( iSavepoint<pPager->nSavepoint ){
36201    int ii;            /* Iterator variable */
36202    int nNew;          /* Number of remaining savepoints after this op. */
36203
36204    /* Figure out how many savepoints will still be active after this
36205    ** operation. Store this value in nNew. Then free resources associated
36206    ** with any savepoints that are destroyed by this operation.
36207    */
36208    nNew = iSavepoint + (op==SAVEPOINT_ROLLBACK);
36209    for(ii=nNew; ii<pPager->nSavepoint; ii++){
36210      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
36211    }
36212    pPager->nSavepoint = nNew;
36213
36214    /* If this is a rollback operation, playback the specified savepoint.
36215    ** If this is a temp-file, it is possible that the journal file has
36216    ** not yet been opened. In this case there have been no changes to
36217    ** the database file, so the playback operation can be skipped.
36218    */
36219    if( op==SAVEPOINT_ROLLBACK && isOpen(pPager->jfd) ){
36220      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
36221      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
36222      assert(rc!=SQLITE_DONE);
36223    }
36224
36225    /* If this is a release of the outermost savepoint, truncate
36226    ** the sub-journal to zero bytes in size. */
36227    if( nNew==0 && op==SAVEPOINT_RELEASE && isOpen(pPager->sjfd) ){
36228      assert( rc==SQLITE_OK );
36229      rc = sqlite3OsTruncate(pPager->sjfd, 0);
36230      pPager->nSubRec = 0;
36231    }
36232  }
36233  return rc;
36234}
36235
36236/*
36237** Return the full pathname of the database file.
36238*/
36239SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
36240  return pPager->zFilename;
36241}
36242
36243/*
36244** Return the VFS structure for the pager.
36245*/
36246SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
36247  return pPager->pVfs;
36248}
36249
36250/*
36251** Return the file handle for the database file associated
36252** with the pager.  This might return NULL if the file has
36253** not yet been opened.
36254*/
36255SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
36256  return pPager->fd;
36257}
36258
36259/*
36260** Return the full pathname of the journal file.
36261*/
36262SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
36263  return pPager->zJournal;
36264}
36265
36266/*
36267** Return true if fsync() calls are disabled for this pager.  Return FALSE
36268** if fsync()s are executed normally.
36269*/
36270SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
36271  return pPager->noSync;
36272}
36273
36274#ifdef SQLITE_HAS_CODEC
36275/*
36276** Set or retrieve the codec for this pager
36277*/
36278static void sqlite3PagerSetCodec(
36279  Pager *pPager,
36280  void *(*xCodec)(void*,void*,Pgno,int),
36281  void (*xCodecSizeChng)(void*,int,int),
36282  void (*xCodecFree)(void*),
36283  void *pCodec
36284){
36285  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
36286  pPager->xCodec = pPager->memDb ? 0 : xCodec;
36287  pPager->xCodecSizeChng = xCodecSizeChng;
36288  pPager->xCodecFree = xCodecFree;
36289  pPager->pCodec = pCodec;
36290  pagerReportSize(pPager);
36291}
36292static void *sqlite3PagerGetCodec(Pager *pPager){
36293  return pPager->pCodec;
36294}
36295#endif
36296
36297#ifndef SQLITE_OMIT_AUTOVACUUM
36298/*
36299** Move the page pPg to location pgno in the file.
36300**
36301** There must be no references to the page previously located at
36302** pgno (which we call pPgOld) though that page is allowed to be
36303** in cache.  If the page previously located at pgno is not already
36304** in the rollback journal, it is not put there by by this routine.
36305**
36306** References to the page pPg remain valid. Updating any
36307** meta-data associated with pPg (i.e. data stored in the nExtra bytes
36308** allocated along with the page) is the responsibility of the caller.
36309**
36310** A transaction must be active when this routine is called. It used to be
36311** required that a statement transaction was not active, but this restriction
36312** has been removed (CREATE INDEX needs to move a page when a statement
36313** transaction is active).
36314**
36315** If the fourth argument, isCommit, is non-zero, then this page is being
36316** moved as part of a database reorganization just before the transaction
36317** is being committed. In this case, it is guaranteed that the database page
36318** pPg refers to will not be written to again within this transaction.
36319**
36320** This function may return SQLITE_NOMEM or an IO error code if an error
36321** occurs. Otherwise, it returns SQLITE_OK.
36322*/
36323SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
36324  PgHdr *pPgOld;               /* The page being overwritten. */
36325  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
36326  int rc;                      /* Return code */
36327  Pgno origPgno;               /* The original page number */
36328
36329  assert( pPg->nRef>0 );
36330
36331  /* In order to be able to rollback, an in-memory database must journal
36332  ** the page we are moving from.
36333  */
36334  if( MEMDB ){
36335    rc = sqlite3PagerWrite(pPg);
36336    if( rc ) return rc;
36337  }
36338
36339  /* If the page being moved is dirty and has not been saved by the latest
36340  ** savepoint, then save the current contents of the page into the
36341  ** sub-journal now. This is required to handle the following scenario:
36342  **
36343  **   BEGIN;
36344  **     <journal page X, then modify it in memory>
36345  **     SAVEPOINT one;
36346  **       <Move page X to location Y>
36347  **     ROLLBACK TO one;
36348  **
36349  ** If page X were not written to the sub-journal here, it would not
36350  ** be possible to restore its contents when the "ROLLBACK TO one"
36351  ** statement were is processed.
36352  **
36353  ** subjournalPage() may need to allocate space to store pPg->pgno into
36354  ** one or more savepoint bitvecs. This is the reason this function
36355  ** may return SQLITE_NOMEM.
36356  */
36357  if( pPg->flags&PGHDR_DIRTY
36358   && subjRequiresPage(pPg)
36359   && SQLITE_OK!=(rc = subjournalPage(pPg))
36360  ){
36361    return rc;
36362  }
36363
36364  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
36365      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
36366  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
36367
36368  /* If the journal needs to be sync()ed before page pPg->pgno can
36369  ** be written to, store pPg->pgno in local variable needSyncPgno.
36370  **
36371  ** If the isCommit flag is set, there is no need to remember that
36372  ** the journal needs to be sync()ed before database page pPg->pgno
36373  ** can be written to. The caller has already promised not to write to it.
36374  */
36375  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
36376    needSyncPgno = pPg->pgno;
36377    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
36378    assert( pPg->flags&PGHDR_DIRTY );
36379    assert( pPager->needSync );
36380  }
36381
36382  /* If the cache contains a page with page-number pgno, remove it
36383  ** from its hash chain. Also, if the PgHdr.needSync was set for
36384  ** page pgno before the 'move' operation, it needs to be retained
36385  ** for the page moved there.
36386  */
36387  pPg->flags &= ~PGHDR_NEED_SYNC;
36388  pPgOld = pager_lookup(pPager, pgno);
36389  assert( !pPgOld || pPgOld->nRef==1 );
36390  if( pPgOld ){
36391    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
36392    if( MEMDB ){
36393      /* Do not discard pages from an in-memory database since we might
36394      ** need to rollback later.  Just move the page out of the way. */
36395      assert( pPager->dbSizeValid );
36396      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
36397    }else{
36398      sqlite3PcacheDrop(pPgOld);
36399    }
36400  }
36401
36402  origPgno = pPg->pgno;
36403  sqlite3PcacheMove(pPg, pgno);
36404  sqlite3PcacheMakeDirty(pPg);
36405  pPager->dbModified = 1;
36406
36407  if( needSyncPgno ){
36408    /* If needSyncPgno is non-zero, then the journal file needs to be
36409    ** sync()ed before any data is written to database file page needSyncPgno.
36410    ** Currently, no such page exists in the page-cache and the
36411    ** "is journaled" bitvec flag has been set. This needs to be remedied by
36412    ** loading the page into the pager-cache and setting the PgHdr.needSync
36413    ** flag.
36414    **
36415    ** If the attempt to load the page into the page-cache fails, (due
36416    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
36417    ** array. Otherwise, if the page is loaded and written again in
36418    ** this transaction, it may be written to the database file before
36419    ** it is synced into the journal file. This way, it may end up in
36420    ** the journal file twice, but that is not a problem.
36421    **
36422    ** The sqlite3PagerGet() call may cause the journal to sync. So make
36423    ** sure the Pager.needSync flag is set too.
36424    */
36425    PgHdr *pPgHdr;
36426    assert( pPager->needSync );
36427    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
36428    if( rc!=SQLITE_OK ){
36429      if( needSyncPgno<=pPager->dbOrigSize ){
36430        assert( pPager->pTmpSpace!=0 );
36431        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
36432      }
36433      return rc;
36434    }
36435    pPager->needSync = 1;
36436    assert( pPager->noSync==0 && !MEMDB );
36437    pPgHdr->flags |= PGHDR_NEED_SYNC;
36438    sqlite3PcacheMakeDirty(pPgHdr);
36439    sqlite3PagerUnref(pPgHdr);
36440  }
36441
36442  /*
36443  ** For an in-memory database, make sure the original page continues
36444  ** to exist, in case the transaction needs to roll back.  Use pPgOld
36445  ** as the original page since it has already been allocated.
36446  */
36447  if( MEMDB ){
36448    sqlite3PcacheMove(pPgOld, origPgno);
36449    sqlite3PagerUnref(pPgOld);
36450  }
36451
36452  return SQLITE_OK;
36453}
36454#endif
36455
36456/*
36457** Return a pointer to the data for the specified page.
36458*/
36459SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
36460  assert( pPg->nRef>0 || pPg->pPager->memDb );
36461  return pPg->pData;
36462}
36463
36464/*
36465** Return a pointer to the Pager.nExtra bytes of "extra" space
36466** allocated along with the specified page.
36467*/
36468SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
36469  return pPg->pExtra;
36470}
36471
36472/*
36473** Get/set the locking-mode for this pager. Parameter eMode must be one
36474** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
36475** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
36476** the locking-mode is set to the value specified.
36477**
36478** The returned value is either PAGER_LOCKINGMODE_NORMAL or
36479** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
36480** locking-mode.
36481*/
36482SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
36483  assert( eMode==PAGER_LOCKINGMODE_QUERY
36484            || eMode==PAGER_LOCKINGMODE_NORMAL
36485            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
36486  assert( PAGER_LOCKINGMODE_QUERY<0 );
36487  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
36488  if( eMode>=0 && !pPager->tempFile ){
36489    pPager->exclusiveMode = (u8)eMode;
36490  }
36491  return (int)pPager->exclusiveMode;
36492}
36493
36494/*
36495** Get/set the journal-mode for this pager. Parameter eMode must be one of:
36496**
36497**    PAGER_JOURNALMODE_QUERY
36498**    PAGER_JOURNALMODE_DELETE
36499**    PAGER_JOURNALMODE_TRUNCATE
36500**    PAGER_JOURNALMODE_PERSIST
36501**    PAGER_JOURNALMODE_OFF
36502**    PAGER_JOURNALMODE_MEMORY
36503**
36504** If the parameter is not _QUERY, then the journal_mode is set to the
36505** value specified if the change is allowed.  The change is disallowed
36506** for the following reasons:
36507**
36508**   *  An in-memory database can only have its journal_mode set to _OFF
36509**      or _MEMORY.
36510**
36511**   *  The journal mode may not be changed while a transaction is active.
36512**
36513** The returned indicate the current (possibly updated) journal-mode.
36514*/
36515SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
36516  assert( eMode==PAGER_JOURNALMODE_QUERY
36517            || eMode==PAGER_JOURNALMODE_DELETE
36518            || eMode==PAGER_JOURNALMODE_TRUNCATE
36519            || eMode==PAGER_JOURNALMODE_PERSIST
36520            || eMode==PAGER_JOURNALMODE_OFF
36521            || eMode==PAGER_JOURNALMODE_MEMORY );
36522  assert( PAGER_JOURNALMODE_QUERY<0 );
36523  if( eMode>=0
36524   && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY
36525              || eMode==PAGER_JOURNALMODE_OFF)
36526   && !pPager->dbModified
36527   && (!isOpen(pPager->jfd) || 0==pPager->journalOff)
36528  ){
36529    if( isOpen(pPager->jfd) ){
36530      sqlite3OsClose(pPager->jfd);
36531    }
36532    pPager->journalMode = (u8)eMode;
36533  }
36534  return (int)pPager->journalMode;
36535}
36536
36537/*
36538** Get/set the size-limit used for persistent journal files.
36539**
36540** Setting the size limit to -1 means no limit is enforced.
36541** An attempt to set a limit smaller than -1 is a no-op.
36542*/
36543SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
36544  if( iLimit>=-1 ){
36545    pPager->journalSizeLimit = iLimit;
36546  }
36547  return pPager->journalSizeLimit;
36548}
36549
36550/*
36551** Return a pointer to the pPager->pBackup variable. The backup module
36552** in backup.c maintains the content of this variable. This module
36553** uses it opaquely as an argument to sqlite3BackupRestart() and
36554** sqlite3BackupUpdate() only.
36555*/
36556SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
36557  return &pPager->pBackup;
36558}
36559
36560#endif /* SQLITE_OMIT_DISKIO */
36561
36562/************** End of pager.c ***********************************************/
36563/************** Begin file btmutex.c *****************************************/
36564/*
36565** 2007 August 27
36566**
36567** The author disclaims copyright to this source code.  In place of
36568** a legal notice, here is a blessing:
36569**
36570**    May you do good and not evil.
36571**    May you find forgiveness for yourself and forgive others.
36572**    May you share freely, never taking more than you give.
36573**
36574*************************************************************************
36575**
36576** This file contains code used to implement mutexes on Btree objects.
36577** This code really belongs in btree.c.  But btree.c is getting too
36578** big and we want to break it down some.  This packaged seemed like
36579** a good breakout.
36580*/
36581/************** Include btreeInt.h in the middle of btmutex.c ****************/
36582/************** Begin file btreeInt.h ****************************************/
36583/*
36584** 2004 April 6
36585**
36586** The author disclaims copyright to this source code.  In place of
36587** a legal notice, here is a blessing:
36588**
36589**    May you do good and not evil.
36590**    May you find forgiveness for yourself and forgive others.
36591**    May you share freely, never taking more than you give.
36592**
36593*************************************************************************
36594** This file implements a external (disk-based) database using BTrees.
36595** For a detailed discussion of BTrees, refer to
36596**
36597**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
36598**     "Sorting And Searching", pages 473-480. Addison-Wesley
36599**     Publishing Company, Reading, Massachusetts.
36600**
36601** The basic idea is that each page of the file contains N database
36602** entries and N+1 pointers to subpages.
36603**
36604**   ----------------------------------------------------------------
36605**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
36606**   ----------------------------------------------------------------
36607**
36608** All of the keys on the page that Ptr(0) points to have values less
36609** than Key(0).  All of the keys on page Ptr(1) and its subpages have
36610** values greater than Key(0) and less than Key(1).  All of the keys
36611** on Ptr(N) and its subpages have values greater than Key(N-1).  And
36612** so forth.
36613**
36614** Finding a particular key requires reading O(log(M)) pages from the
36615** disk where M is the number of entries in the tree.
36616**
36617** In this implementation, a single file can hold one or more separate
36618** BTrees.  Each BTree is identified by the index of its root page.  The
36619** key and data for any entry are combined to form the "payload".  A
36620** fixed amount of payload can be carried directly on the database
36621** page.  If the payload is larger than the preset amount then surplus
36622** bytes are stored on overflow pages.  The payload for an entry
36623** and the preceding pointer are combined to form a "Cell".  Each
36624** page has a small header which contains the Ptr(N) pointer and other
36625** information such as the size of key and data.
36626**
36627** FORMAT DETAILS
36628**
36629** The file is divided into pages.  The first page is called page 1,
36630** the second is page 2, and so forth.  A page number of zero indicates
36631** "no such page".  The page size can be any power of 2 between 512 and 32768.
36632** Each page can be either a btree page, a freelist page, an overflow
36633** page, or a pointer-map page.
36634**
36635** The first page is always a btree page.  The first 100 bytes of the first
36636** page contain a special header (the "file header") that describes the file.
36637** The format of the file header is as follows:
36638**
36639**   OFFSET   SIZE    DESCRIPTION
36640**      0      16     Header string: "SQLite format 3\000"
36641**     16       2     Page size in bytes.
36642**     18       1     File format write version
36643**     19       1     File format read version
36644**     20       1     Bytes of unused space at the end of each page
36645**     21       1     Max embedded payload fraction
36646**     22       1     Min embedded payload fraction
36647**     23       1     Min leaf payload fraction
36648**     24       4     File change counter
36649**     28       4     Reserved for future use
36650**     32       4     First freelist page
36651**     36       4     Number of freelist pages in the file
36652**     40      60     15 4-byte meta values passed to higher layers
36653**
36654**     40       4     Schema cookie
36655**     44       4     File format of schema layer
36656**     48       4     Size of page cache
36657**     52       4     Largest root-page (auto/incr_vacuum)
36658**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
36659**     60       4     User version
36660**     64       4     Incremental vacuum mode
36661**     68       4     unused
36662**     72       4     unused
36663**     76       4     unused
36664**
36665** All of the integer values are big-endian (most significant byte first).
36666**
36667** The file change counter is incremented when the database is changed
36668** This counter allows other processes to know when the file has changed
36669** and thus when they need to flush their cache.
36670**
36671** The max embedded payload fraction is the amount of the total usable
36672** space in a page that can be consumed by a single cell for standard
36673** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
36674** is to limit the maximum cell size so that at least 4 cells will fit
36675** on one page.  Thus the default max embedded payload fraction is 64.
36676**
36677** If the payload for a cell is larger than the max payload, then extra
36678** payload is spilled to overflow pages.  Once an overflow page is allocated,
36679** as many bytes as possible are moved into the overflow pages without letting
36680** the cell size drop below the min embedded payload fraction.
36681**
36682** The min leaf payload fraction is like the min embedded payload fraction
36683** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
36684** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
36685** not specified in the header.
36686**
36687** Each btree pages is divided into three sections:  The header, the
36688** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
36689** file header that occurs before the page header.
36690**
36691**      |----------------|
36692**      | file header    |   100 bytes.  Page 1 only.
36693**      |----------------|
36694**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
36695**      |----------------|
36696**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
36697**      | array          |   |  Grows downward
36698**      |                |   v
36699**      |----------------|
36700**      | unallocated    |
36701**      | space          |
36702**      |----------------|   ^  Grows upwards
36703**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
36704**      | area           |   |  and free space fragments.
36705**      |----------------|
36706**
36707** The page headers looks like this:
36708**
36709**   OFFSET   SIZE     DESCRIPTION
36710**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
36711**      1       2      byte offset to the first freeblock
36712**      3       2      number of cells on this page
36713**      5       2      first byte of the cell content area
36714**      7       1      number of fragmented free bytes
36715**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
36716**
36717** The flags define the format of this btree page.  The leaf flag means that
36718** this page has no children.  The zerodata flag means that this page carries
36719** only keys and no data.  The intkey flag means that the key is a integer
36720** which is stored in the key size entry of the cell header rather than in
36721** the payload area.
36722**
36723** The cell pointer array begins on the first byte after the page header.
36724** The cell pointer array contains zero or more 2-byte numbers which are
36725** offsets from the beginning of the page to the cell content in the cell
36726** content area.  The cell pointers occur in sorted order.  The system strives
36727** to keep free space after the last cell pointer so that new cells can
36728** be easily added without having to defragment the page.
36729**
36730** Cell content is stored at the very end of the page and grows toward the
36731** beginning of the page.
36732**
36733** Unused space within the cell content area is collected into a linked list of
36734** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
36735** to the first freeblock is given in the header.  Freeblocks occur in
36736** increasing order.  Because a freeblock must be at least 4 bytes in size,
36737** any group of 3 or fewer unused bytes in the cell content area cannot
36738** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
36739** a fragment.  The total number of bytes in all fragments is recorded.
36740** in the page header at offset 7.
36741**
36742**    SIZE    DESCRIPTION
36743**      2     Byte offset of the next freeblock
36744**      2     Bytes in this freeblock
36745**
36746** Cells are of variable length.  Cells are stored in the cell content area at
36747** the end of the page.  Pointers to the cells are in the cell pointer array
36748** that immediately follows the page header.  Cells is not necessarily
36749** contiguous or in order, but cell pointers are contiguous and in order.
36750**
36751** Cell content makes use of variable length integers.  A variable
36752** length integer is 1 to 9 bytes where the lower 7 bits of each
36753** byte are used.  The integer consists of all bytes that have bit 8 set and
36754** the first byte with bit 8 clear.  The most significant byte of the integer
36755** appears first.  A variable-length integer may not be more than 9 bytes long.
36756** As a special case, all 8 bytes of the 9th byte are used as data.  This
36757** allows a 64-bit integer to be encoded in 9 bytes.
36758**
36759**    0x00                      becomes  0x00000000
36760**    0x7f                      becomes  0x0000007f
36761**    0x81 0x00                 becomes  0x00000080
36762**    0x82 0x00                 becomes  0x00000100
36763**    0x80 0x7f                 becomes  0x0000007f
36764**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
36765**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
36766**
36767** Variable length integers are used for rowids and to hold the number of
36768** bytes of key and data in a btree cell.
36769**
36770** The content of a cell looks like this:
36771**
36772**    SIZE    DESCRIPTION
36773**      4     Page number of the left child. Omitted if leaf flag is set.
36774**     var    Number of bytes of data. Omitted if the zerodata flag is set.
36775**     var    Number of bytes of key. Or the key itself if intkey flag is set.
36776**      *     Payload
36777**      4     First page of the overflow chain.  Omitted if no overflow
36778**
36779** Overflow pages form a linked list.  Each page except the last is completely
36780** filled with data (pagesize - 4 bytes).  The last page can have as little
36781** as 1 byte of data.
36782**
36783**    SIZE    DESCRIPTION
36784**      4     Page number of next overflow page
36785**      *     Data
36786**
36787** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
36788** file header points to the first in a linked list of trunk page.  Each trunk
36789** page points to multiple leaf pages.  The content of a leaf page is
36790** unspecified.  A trunk page looks like this:
36791**
36792**    SIZE    DESCRIPTION
36793**      4     Page number of next trunk page
36794**      4     Number of leaf pointers on this page
36795**      *     zero or more pages numbers of leaves
36796*/
36797
36798
36799/* The following value is the maximum cell size assuming a maximum page
36800** size give above.
36801*/
36802#define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
36803
36804/* The maximum number of cells on a single page of the database.  This
36805** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
36806** plus 2 bytes for the index to the cell in the page header).  Such
36807** small cells will be rare, but they are possible.
36808*/
36809#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
36810
36811/* Forward declarations */
36812typedef struct MemPage MemPage;
36813typedef struct BtLock BtLock;
36814
36815/*
36816** This is a magic string that appears at the beginning of every
36817** SQLite database in order to identify the file as a real database.
36818**
36819** You can change this value at compile-time by specifying a
36820** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
36821** header must be exactly 16 bytes including the zero-terminator so
36822** the string itself should be 15 characters long.  If you change
36823** the header, then your custom library will not be able to read
36824** databases generated by the standard tools and the standard tools
36825** will not be able to read databases created by your custom library.
36826*/
36827#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
36828#  define SQLITE_FILE_HEADER "SQLite format 3"
36829#endif
36830
36831/*
36832** Page type flags.  An ORed combination of these flags appear as the
36833** first byte of on-disk image of every BTree page.
36834*/
36835#define PTF_INTKEY    0x01
36836#define PTF_ZERODATA  0x02
36837#define PTF_LEAFDATA  0x04
36838#define PTF_LEAF      0x08
36839
36840/*
36841** As each page of the file is loaded into memory, an instance of the following
36842** structure is appended and initialized to zero.  This structure stores
36843** information about the page that is decoded from the raw file page.
36844**
36845** The pParent field points back to the parent page.  This allows us to
36846** walk up the BTree from any leaf to the root.  Care must be taken to
36847** unref() the parent page pointer when this page is no longer referenced.
36848** The pageDestructor() routine handles that chore.
36849**
36850** Access to all fields of this structure is controlled by the mutex
36851** stored in MemPage.pBt->mutex.
36852*/
36853struct MemPage {
36854  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
36855  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
36856  u8 intKey;           /* True if intkey flag is set */
36857  u8 leaf;             /* True if leaf flag is set */
36858  u8 hasData;          /* True if this page stores data */
36859  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
36860  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
36861  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
36862  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
36863  u16 cellOffset;      /* Index in aData of first cell pointer */
36864  u16 nFree;           /* Number of free bytes on the page */
36865  u16 nCell;           /* Number of cells on this page, local and ovfl */
36866  u16 maskPage;        /* Mask for page offset */
36867  struct _OvflCell {   /* Cells that will not fit on aData[] */
36868    u8 *pCell;          /* Pointers to the body of the overflow cell */
36869    u16 idx;            /* Insert this cell before idx-th non-overflow cell */
36870  } aOvfl[5];
36871  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
36872  u8 *aData;           /* Pointer to disk image of the page data */
36873  DbPage *pDbPage;     /* Pager page handle */
36874  Pgno pgno;           /* Page number for this page */
36875};
36876
36877/*
36878** The in-memory image of a disk page has the auxiliary information appended
36879** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
36880** that extra information.
36881*/
36882#define EXTRA_SIZE sizeof(MemPage)
36883
36884/*
36885** A linked list of the following structures is stored at BtShared.pLock.
36886** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
36887** is opened on the table with root page BtShared.iTable. Locks are removed
36888** from this list when a transaction is committed or rolled back, or when
36889** a btree handle is closed.
36890*/
36891struct BtLock {
36892  Btree *pBtree;        /* Btree handle holding this lock */
36893  Pgno iTable;          /* Root page of table */
36894  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
36895  BtLock *pNext;        /* Next in BtShared.pLock list */
36896};
36897
36898/* Candidate values for BtLock.eLock */
36899#define READ_LOCK     1
36900#define WRITE_LOCK    2
36901
36902/* A Btree handle
36903**
36904** A database connection contains a pointer to an instance of
36905** this object for every database file that it has open.  This structure
36906** is opaque to the database connection.  The database connection cannot
36907** see the internals of this structure and only deals with pointers to
36908** this structure.
36909**
36910** For some database files, the same underlying database cache might be
36911** shared between multiple connections.  In that case, each connection
36912** has it own instance of this object.  But each instance of this object
36913** points to the same BtShared object.  The database cache and the
36914** schema associated with the database file are all contained within
36915** the BtShared object.
36916**
36917** All fields in this structure are accessed under sqlite3.mutex.
36918** The pBt pointer itself may not be changed while there exists cursors
36919** in the referenced BtShared that point back to this Btree since those
36920** cursors have to do go through this Btree to find their BtShared and
36921** they often do so without holding sqlite3.mutex.
36922*/
36923struct Btree {
36924  sqlite3 *db;       /* The database connection holding this btree */
36925  BtShared *pBt;     /* Sharable content of this btree */
36926  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
36927  u8 sharable;       /* True if we can share pBt with another db */
36928  u8 locked;         /* True if db currently has pBt locked */
36929  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
36930  int nBackup;       /* Number of backup operations reading this btree */
36931  Btree *pNext;      /* List of other sharable Btrees from the same db */
36932  Btree *pPrev;      /* Back pointer of the same list */
36933#ifndef SQLITE_OMIT_SHARED_CACHE
36934  BtLock lock;       /* Object used to lock page 1 */
36935#endif
36936};
36937
36938/*
36939** Btree.inTrans may take one of the following values.
36940**
36941** If the shared-data extension is enabled, there may be multiple users
36942** of the Btree structure. At most one of these may open a write transaction,
36943** but any number may have active read transactions.
36944*/
36945#define TRANS_NONE  0
36946#define TRANS_READ  1
36947#define TRANS_WRITE 2
36948
36949/*
36950** An instance of this object represents a single database file.
36951**
36952** A single database file can be in use as the same time by two
36953** or more database connections.  When two or more connections are
36954** sharing the same database file, each connection has it own
36955** private Btree object for the file and each of those Btrees points
36956** to this one BtShared object.  BtShared.nRef is the number of
36957** connections currently sharing this database file.
36958**
36959** Fields in this structure are accessed under the BtShared.mutex
36960** mutex, except for nRef and pNext which are accessed under the
36961** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
36962** may not be modified once it is initially set as long as nRef>0.
36963** The pSchema field may be set once under BtShared.mutex and
36964** thereafter is unchanged as long as nRef>0.
36965**
36966** isPending:
36967**
36968**   If a BtShared client fails to obtain a write-lock on a database
36969**   table (because there exists one or more read-locks on the table),
36970**   the shared-cache enters 'pending-lock' state and isPending is
36971**   set to true.
36972**
36973**   The shared-cache leaves the 'pending lock' state when either of
36974**   the following occur:
36975**
36976**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
36977**     2) The number of locks held by other connections drops to zero.
36978**
36979**   while in the 'pending-lock' state, no connection may start a new
36980**   transaction.
36981**
36982**   This feature is included to help prevent writer-starvation.
36983*/
36984struct BtShared {
36985  Pager *pPager;        /* The page cache */
36986  sqlite3 *db;          /* Database connection currently using this Btree */
36987  BtCursor *pCursor;    /* A list of all open cursors */
36988  MemPage *pPage1;      /* First page of the database */
36989  u8 readOnly;          /* True if the underlying file is readonly */
36990  u8 pageSizeFixed;     /* True if the page size can no longer be changed */
36991#ifndef SQLITE_OMIT_AUTOVACUUM
36992  u8 autoVacuum;        /* True if auto-vacuum is enabled */
36993  u8 incrVacuum;        /* True if incr-vacuum is enabled */
36994#endif
36995  u16 pageSize;         /* Total number of bytes on a page */
36996  u16 usableSize;       /* Number of usable bytes on each page */
36997  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
36998  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
36999  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
37000  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
37001  u8 inTransaction;     /* Transaction state */
37002  int nTransaction;     /* Number of open transactions (read + write) */
37003  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
37004  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
37005  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
37006  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
37007#ifndef SQLITE_OMIT_SHARED_CACHE
37008  int nRef;             /* Number of references to this structure */
37009  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
37010  BtLock *pLock;        /* List of locks held on this shared-btree struct */
37011  Btree *pWriter;       /* Btree with currently open write transaction */
37012  u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
37013  u8 isPending;         /* If waiting for read-locks to clear */
37014#endif
37015  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
37016};
37017
37018/*
37019** An instance of the following structure is used to hold information
37020** about a cell.  The parseCellPtr() function fills in this structure
37021** based on information extract from the raw disk page.
37022*/
37023typedef struct CellInfo CellInfo;
37024struct CellInfo {
37025  u8 *pCell;     /* Pointer to the start of cell content */
37026  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
37027  u32 nData;     /* Number of bytes of data */
37028  u32 nPayload;  /* Total amount of payload */
37029  u16 nHeader;   /* Size of the cell content header in bytes */
37030  u16 nLocal;    /* Amount of payload held locally */
37031  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
37032  u16 nSize;     /* Size of the cell content on the main b-tree page */
37033};
37034
37035/*
37036** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
37037** this will be declared corrupt. This value is calculated based on a
37038** maximum database size of 2^31 pages a minimum fanout of 2 for a
37039** root-node and 3 for all other internal nodes.
37040**
37041** If a tree that appears to be taller than this is encountered, it is
37042** assumed that the database is corrupt.
37043*/
37044#define BTCURSOR_MAX_DEPTH 20
37045
37046/*
37047** A cursor is a pointer to a particular entry within a particular
37048** b-tree within a database file.
37049**
37050** The entry is identified by its MemPage and the index in
37051** MemPage.aCell[] of the entry.
37052**
37053** A single database file can shared by two more database connections,
37054** but cursors cannot be shared.  Each cursor is associated with a
37055** particular database connection identified BtCursor.pBtree.db.
37056**
37057** Fields in this structure are accessed under the BtShared.mutex
37058** found at self->pBt->mutex.
37059*/
37060struct BtCursor {
37061  Btree *pBtree;            /* The Btree to which this cursor belongs */
37062  BtShared *pBt;            /* The BtShared this cursor points to */
37063  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
37064  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
37065  Pgno pgnoRoot;            /* The root page of this tree */
37066  sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
37067  CellInfo info;            /* A parse of the cell we are pointing at */
37068  u8 wrFlag;                /* True if writable */
37069  u8 atLast;                /* Cursor pointing to the last entry */
37070  u8 validNKey;             /* True if info.nKey is valid */
37071  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
37072  void *pKey;      /* Saved key that was cursor's last known position */
37073  i64 nKey;        /* Size of pKey, or last integer key */
37074  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
37075#ifndef SQLITE_OMIT_INCRBLOB
37076  u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
37077  Pgno *aOverflow;          /* Cache of overflow page locations */
37078#endif
37079  i16 iPage;                            /* Index of current page in apPage */
37080  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
37081  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
37082};
37083
37084/*
37085** Potential values for BtCursor.eState.
37086**
37087** CURSOR_VALID:
37088**   Cursor points to a valid entry. getPayload() etc. may be called.
37089**
37090** CURSOR_INVALID:
37091**   Cursor does not point to a valid entry. This can happen (for example)
37092**   because the table is empty or because BtreeCursorFirst() has not been
37093**   called.
37094**
37095** CURSOR_REQUIRESEEK:
37096**   The table that this cursor was opened on still exists, but has been
37097**   modified since the cursor was last used. The cursor position is saved
37098**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
37099**   this state, restoreCursorPosition() can be called to attempt to
37100**   seek the cursor to the saved position.
37101**
37102** CURSOR_FAULT:
37103**   A unrecoverable error (an I/O error or a malloc failure) has occurred
37104**   on a different connection that shares the BtShared cache with this
37105**   cursor.  The error has left the cache in an inconsistent state.
37106**   Do nothing else with this cursor.  Any attempt to use the cursor
37107**   should return the error code stored in BtCursor.skip
37108*/
37109#define CURSOR_INVALID           0
37110#define CURSOR_VALID             1
37111#define CURSOR_REQUIRESEEK       2
37112#define CURSOR_FAULT             3
37113
37114/*
37115** The database page the PENDING_BYTE occupies. This page is never used.
37116*/
37117# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
37118
37119/*
37120** These macros define the location of the pointer-map entry for a
37121** database page. The first argument to each is the number of usable
37122** bytes on each page of the database (often 1024). The second is the
37123** page number to look up in the pointer map.
37124**
37125** PTRMAP_PAGENO returns the database page number of the pointer-map
37126** page that stores the required pointer. PTRMAP_PTROFFSET returns
37127** the offset of the requested map entry.
37128**
37129** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
37130** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
37131** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
37132** this test.
37133*/
37134#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
37135#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
37136#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
37137
37138/*
37139** The pointer map is a lookup table that identifies the parent page for
37140** each child page in the database file.  The parent page is the page that
37141** contains a pointer to the child.  Every page in the database contains
37142** 0 or 1 parent pages.  (In this context 'database page' refers
37143** to any page that is not part of the pointer map itself.)  Each pointer map
37144** entry consists of a single byte 'type' and a 4 byte parent page number.
37145** The PTRMAP_XXX identifiers below are the valid types.
37146**
37147** The purpose of the pointer map is to facility moving pages from one
37148** position in the file to another as part of autovacuum.  When a page
37149** is moved, the pointer in its parent must be updated to point to the
37150** new location.  The pointer map is used to locate the parent page quickly.
37151**
37152** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
37153**                  used in this case.
37154**
37155** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
37156**                  is not used in this case.
37157**
37158** PTRMAP_OVERFLOW1: The database page is the first page in a list of
37159**                   overflow pages. The page number identifies the page that
37160**                   contains the cell with a pointer to this overflow page.
37161**
37162** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
37163**                   overflow pages. The page-number identifies the previous
37164**                   page in the overflow page list.
37165**
37166** PTRMAP_BTREE: The database page is a non-root btree page. The page number
37167**               identifies the parent page in the btree.
37168*/
37169#define PTRMAP_ROOTPAGE 1
37170#define PTRMAP_FREEPAGE 2
37171#define PTRMAP_OVERFLOW1 3
37172#define PTRMAP_OVERFLOW2 4
37173#define PTRMAP_BTREE 5
37174
37175/* A bunch of assert() statements to check the transaction state variables
37176** of handle p (type Btree*) are internally consistent.
37177*/
37178#define btreeIntegrity(p) \
37179  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
37180  assert( p->pBt->inTransaction>=p->inTrans );
37181
37182
37183/*
37184** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
37185** if the database supports auto-vacuum or not. Because it is used
37186** within an expression that is an argument to another macro
37187** (sqliteMallocRaw), it is not possible to use conditional compilation.
37188** So, this macro is defined instead.
37189*/
37190#ifndef SQLITE_OMIT_AUTOVACUUM
37191#define ISAUTOVACUUM (pBt->autoVacuum)
37192#else
37193#define ISAUTOVACUUM 0
37194#endif
37195
37196
37197/*
37198** This structure is passed around through all the sanity checking routines
37199** in order to keep track of some global state information.
37200*/
37201typedef struct IntegrityCk IntegrityCk;
37202struct IntegrityCk {
37203  BtShared *pBt;    /* The tree being checked out */
37204  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
37205  Pgno nPage;       /* Number of pages in the database */
37206  int *anRef;       /* Number of times each page is referenced */
37207  int mxErr;        /* Stop accumulating errors when this reaches zero */
37208  int nErr;         /* Number of messages written to zErrMsg so far */
37209  int mallocFailed; /* A memory allocation error has occurred */
37210  StrAccum errMsg;  /* Accumulate the error message text here */
37211};
37212
37213/*
37214** Read or write a two- and four-byte big-endian integer values.
37215*/
37216#define get2byte(x)   ((x)[0]<<8 | (x)[1])
37217#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
37218#define get4byte sqlite3Get4byte
37219#define put4byte sqlite3Put4byte
37220
37221/************** End of btreeInt.h ********************************************/
37222/************** Continuing where we left off in btmutex.c ********************/
37223#ifndef SQLITE_OMIT_SHARED_CACHE
37224#if SQLITE_THREADSAFE
37225
37226/*
37227** Obtain the BtShared mutex associated with B-Tree handle p. Also,
37228** set BtShared.db to the database handle associated with p and the
37229** p->locked boolean to true.
37230*/
37231static void lockBtreeMutex(Btree *p){
37232  assert( p->locked==0 );
37233  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
37234  assert( sqlite3_mutex_held(p->db->mutex) );
37235
37236  sqlite3_mutex_enter(p->pBt->mutex);
37237  p->pBt->db = p->db;
37238  p->locked = 1;
37239}
37240
37241/*
37242** Release the BtShared mutex associated with B-Tree handle p and
37243** clear the p->locked boolean.
37244*/
37245static void unlockBtreeMutex(Btree *p){
37246  assert( p->locked==1 );
37247  assert( sqlite3_mutex_held(p->pBt->mutex) );
37248  assert( sqlite3_mutex_held(p->db->mutex) );
37249  assert( p->db==p->pBt->db );
37250
37251  sqlite3_mutex_leave(p->pBt->mutex);
37252  p->locked = 0;
37253}
37254
37255/*
37256** Enter a mutex on the given BTree object.
37257**
37258** If the object is not sharable, then no mutex is ever required
37259** and this routine is a no-op.  The underlying mutex is non-recursive.
37260** But we keep a reference count in Btree.wantToLock so the behavior
37261** of this interface is recursive.
37262**
37263** To avoid deadlocks, multiple Btrees are locked in the same order
37264** by all database connections.  The p->pNext is a list of other
37265** Btrees belonging to the same database connection as the p Btree
37266** which need to be locked after p.  If we cannot get a lock on
37267** p, then first unlock all of the others on p->pNext, then wait
37268** for the lock to become available on p, then relock all of the
37269** subsequent Btrees that desire a lock.
37270*/
37271SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
37272  Btree *pLater;
37273
37274  /* Some basic sanity checking on the Btree.  The list of Btrees
37275  ** connected by pNext and pPrev should be in sorted order by
37276  ** Btree.pBt value. All elements of the list should belong to
37277  ** the same connection. Only shared Btrees are on the list. */
37278  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
37279  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
37280  assert( p->pNext==0 || p->pNext->db==p->db );
37281  assert( p->pPrev==0 || p->pPrev->db==p->db );
37282  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
37283
37284  /* Check for locking consistency */
37285  assert( !p->locked || p->wantToLock>0 );
37286  assert( p->sharable || p->wantToLock==0 );
37287
37288  /* We should already hold a lock on the database connection */
37289  assert( sqlite3_mutex_held(p->db->mutex) );
37290
37291  /* Unless the database is sharable and unlocked, then BtShared.db
37292  ** should already be set correctly. */
37293  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
37294
37295  if( !p->sharable ) return;
37296  p->wantToLock++;
37297  if( p->locked ) return;
37298
37299  /* In most cases, we should be able to acquire the lock we
37300  ** want without having to go throught the ascending lock
37301  ** procedure that follows.  Just be sure not to block.
37302  */
37303  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
37304    p->pBt->db = p->db;
37305    p->locked = 1;
37306    return;
37307  }
37308
37309  /* To avoid deadlock, first release all locks with a larger
37310  ** BtShared address.  Then acquire our lock.  Then reacquire
37311  ** the other BtShared locks that we used to hold in ascending
37312  ** order.
37313  */
37314  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
37315    assert( pLater->sharable );
37316    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
37317    assert( !pLater->locked || pLater->wantToLock>0 );
37318    if( pLater->locked ){
37319      unlockBtreeMutex(pLater);
37320    }
37321  }
37322  lockBtreeMutex(p);
37323  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
37324    if( pLater->wantToLock ){
37325      lockBtreeMutex(pLater);
37326    }
37327  }
37328}
37329
37330/*
37331** Exit the recursive mutex on a Btree.
37332*/
37333SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
37334  if( p->sharable ){
37335    assert( p->wantToLock>0 );
37336    p->wantToLock--;
37337    if( p->wantToLock==0 ){
37338      unlockBtreeMutex(p);
37339    }
37340  }
37341}
37342
37343#ifndef NDEBUG
37344/*
37345** Return true if the BtShared mutex is held on the btree, or if the
37346** B-Tree is not marked as sharable.
37347**
37348** This routine is used only from within assert() statements.
37349*/
37350SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
37351  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
37352  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
37353  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
37354  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
37355
37356  return (p->sharable==0 || p->locked);
37357}
37358#endif
37359
37360
37361#ifndef SQLITE_OMIT_INCRBLOB
37362/*
37363** Enter and leave a mutex on a Btree given a cursor owned by that
37364** Btree.  These entry points are used by incremental I/O and can be
37365** omitted if that module is not used.
37366*/
37367SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
37368  sqlite3BtreeEnter(pCur->pBtree);
37369}
37370SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
37371  sqlite3BtreeLeave(pCur->pBtree);
37372}
37373#endif /* SQLITE_OMIT_INCRBLOB */
37374
37375
37376/*
37377** Enter the mutex on every Btree associated with a database
37378** connection.  This is needed (for example) prior to parsing
37379** a statement since we will be comparing table and column names
37380** against all schemas and we do not want those schemas being
37381** reset out from under us.
37382**
37383** There is a corresponding leave-all procedures.
37384**
37385** Enter the mutexes in accending order by BtShared pointer address
37386** to avoid the possibility of deadlock when two threads with
37387** two or more btrees in common both try to lock all their btrees
37388** at the same instant.
37389*/
37390SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
37391  int i;
37392  Btree *p, *pLater;
37393  assert( sqlite3_mutex_held(db->mutex) );
37394  for(i=0; i<db->nDb; i++){
37395    p = db->aDb[i].pBt;
37396    assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
37397    if( p && p->sharable ){
37398      p->wantToLock++;
37399      if( !p->locked ){
37400        assert( p->wantToLock==1 );
37401        while( p->pPrev ) p = p->pPrev;
37402        /* Reason for ALWAYS:  There must be at least on unlocked Btree in
37403        ** the chain.  Otherwise the !p->locked test above would have failed */
37404        while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
37405        for(pLater = p->pNext; pLater; pLater=pLater->pNext){
37406          if( pLater->locked ){
37407            unlockBtreeMutex(pLater);
37408          }
37409        }
37410        while( p ){
37411          lockBtreeMutex(p);
37412          p = p->pNext;
37413        }
37414      }
37415    }
37416  }
37417}
37418SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
37419  int i;
37420  Btree *p;
37421  assert( sqlite3_mutex_held(db->mutex) );
37422  for(i=0; i<db->nDb; i++){
37423    p = db->aDb[i].pBt;
37424    if( p && p->sharable ){
37425      assert( p->wantToLock>0 );
37426      p->wantToLock--;
37427      if( p->wantToLock==0 ){
37428        unlockBtreeMutex(p);
37429      }
37430    }
37431  }
37432}
37433
37434#ifndef NDEBUG
37435/*
37436** Return true if the current thread holds the database connection
37437** mutex and all required BtShared mutexes.
37438**
37439** This routine is used inside assert() statements only.
37440*/
37441SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
37442  int i;
37443  if( !sqlite3_mutex_held(db->mutex) ){
37444    return 0;
37445  }
37446  for(i=0; i<db->nDb; i++){
37447    Btree *p;
37448    p = db->aDb[i].pBt;
37449    if( p && p->sharable &&
37450         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
37451      return 0;
37452    }
37453  }
37454  return 1;
37455}
37456#endif /* NDEBUG */
37457
37458/*
37459** Add a new Btree pointer to a BtreeMutexArray.
37460** if the pointer can possibly be shared with
37461** another database connection.
37462**
37463** The pointers are kept in sorted order by pBtree->pBt.  That
37464** way when we go to enter all the mutexes, we can enter them
37465** in order without every having to backup and retry and without
37466** worrying about deadlock.
37467**
37468** The number of shared btrees will always be small (usually 0 or 1)
37469** so an insertion sort is an adequate algorithm here.
37470*/
37471SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
37472  int i, j;
37473  BtShared *pBt;
37474  if( pBtree==0 || pBtree->sharable==0 ) return;
37475#ifndef NDEBUG
37476  {
37477    for(i=0; i<pArray->nMutex; i++){
37478      assert( pArray->aBtree[i]!=pBtree );
37479    }
37480  }
37481#endif
37482  assert( pArray->nMutex>=0 );
37483  assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
37484  pBt = pBtree->pBt;
37485  for(i=0; i<pArray->nMutex; i++){
37486    assert( pArray->aBtree[i]!=pBtree );
37487    if( pArray->aBtree[i]->pBt>pBt ){
37488      for(j=pArray->nMutex; j>i; j--){
37489        pArray->aBtree[j] = pArray->aBtree[j-1];
37490      }
37491      pArray->aBtree[i] = pBtree;
37492      pArray->nMutex++;
37493      return;
37494    }
37495  }
37496  pArray->aBtree[pArray->nMutex++] = pBtree;
37497}
37498
37499/*
37500** Enter the mutex of every btree in the array.  This routine is
37501** called at the beginning of sqlite3VdbeExec().  The mutexes are
37502** exited at the end of the same function.
37503*/
37504SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
37505  int i;
37506  for(i=0; i<pArray->nMutex; i++){
37507    Btree *p = pArray->aBtree[i];
37508    /* Some basic sanity checking */
37509    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
37510    assert( !p->locked || p->wantToLock>0 );
37511
37512    /* We should already hold a lock on the database connection */
37513    assert( sqlite3_mutex_held(p->db->mutex) );
37514
37515    /* The Btree is sharable because only sharable Btrees are entered
37516    ** into the array in the first place. */
37517    assert( p->sharable );
37518
37519    p->wantToLock++;
37520    if( !p->locked ){
37521      lockBtreeMutex(p);
37522    }
37523  }
37524}
37525
37526/*
37527** Leave the mutex of every btree in the group.
37528*/
37529SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
37530  int i;
37531  for(i=0; i<pArray->nMutex; i++){
37532    Btree *p = pArray->aBtree[i];
37533    /* Some basic sanity checking */
37534    assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
37535    assert( p->locked );
37536    assert( p->wantToLock>0 );
37537
37538    /* We should already hold a lock on the database connection */
37539    assert( sqlite3_mutex_held(p->db->mutex) );
37540
37541    p->wantToLock--;
37542    if( p->wantToLock==0 ){
37543      unlockBtreeMutex(p);
37544    }
37545  }
37546}
37547
37548#else
37549SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
37550  p->pBt->db = p->db;
37551}
37552SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
37553  int i;
37554  for(i=0; i<db->nDb; i++){
37555    Btree *p = db->aDb[i].pBt;
37556    if( p ){
37557      p->pBt->db = p->db;
37558    }
37559  }
37560}
37561#endif /* if SQLITE_THREADSAFE */
37562#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
37563
37564/************** End of btmutex.c *********************************************/
37565/************** Begin file btree.c *******************************************/
37566/*
37567** 2004 April 6
37568**
37569** The author disclaims copyright to this source code.  In place of
37570** a legal notice, here is a blessing:
37571**
37572**    May you do good and not evil.
37573**    May you find forgiveness for yourself and forgive others.
37574**    May you share freely, never taking more than you give.
37575**
37576*************************************************************************
37577** This file implements a external (disk-based) database using BTrees.
37578** See the header comment on "btreeInt.h" for additional information.
37579** Including a description of file format and an overview of operation.
37580*/
37581
37582/*
37583** The header string that appears at the beginning of every
37584** SQLite database.
37585*/
37586static const char zMagicHeader[] = SQLITE_FILE_HEADER;
37587
37588/*
37589** Set this global variable to 1 to enable tracing using the TRACE
37590** macro.
37591*/
37592#if 0
37593int sqlite3BtreeTrace=1;  /* True to enable tracing */
37594# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
37595#else
37596# define TRACE(X)
37597#endif
37598
37599
37600
37601#ifndef SQLITE_OMIT_SHARED_CACHE
37602/*
37603** A list of BtShared objects that are eligible for participation
37604** in shared cache.  This variable has file scope during normal builds,
37605** but the test harness needs to access it so we make it global for
37606** test builds.
37607**
37608** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
37609*/
37610#ifdef SQLITE_TEST
37611SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
37612#else
37613static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
37614#endif
37615#endif /* SQLITE_OMIT_SHARED_CACHE */
37616
37617#ifndef SQLITE_OMIT_SHARED_CACHE
37618/*
37619** Enable or disable the shared pager and schema features.
37620**
37621** This routine has no effect on existing database connections.
37622** The shared cache setting effects only future calls to
37623** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
37624*/
37625SQLITE_API int sqlite3_enable_shared_cache(int enable){
37626  sqlite3GlobalConfig.sharedCacheEnabled = enable;
37627  return SQLITE_OK;
37628}
37629#endif
37630
37631
37632
37633#ifdef SQLITE_OMIT_SHARED_CACHE
37634  /*
37635  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
37636  ** and clearAllSharedCacheTableLocks()
37637  ** manipulate entries in the BtShared.pLock linked list used to store
37638  ** shared-cache table level locks. If the library is compiled with the
37639  ** shared-cache feature disabled, then there is only ever one user
37640  ** of each BtShared structure and so this locking is not necessary.
37641  ** So define the lock related functions as no-ops.
37642  */
37643  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
37644  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
37645  #define clearAllSharedCacheTableLocks(a)
37646  #define downgradeAllSharedCacheTableLocks(a)
37647  #define hasSharedCacheTableLock(a,b,c,d) 1
37648  #define hasReadConflicts(a, b) 0
37649#endif
37650
37651#ifndef SQLITE_OMIT_SHARED_CACHE
37652
37653#ifdef SQLITE_DEBUG
37654/*
37655**** This function is only used as part of an assert() statement. ***
37656**
37657** Check to see if pBtree holds the required locks to read or write to the
37658** table with root page iRoot.   Return 1 if it does and 0 if not.
37659**
37660** For example, when writing to a table with root-page iRoot via
37661** Btree connection pBtree:
37662**
37663**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
37664**
37665** When writing to an index that resides in a sharable database, the
37666** caller should have first obtained a lock specifying the root page of
37667** the corresponding table. This makes things a bit more complicated,
37668** as this module treats each table as a separate structure. To determine
37669** the table corresponding to the index being written, this
37670** function has to search through the database schema.
37671**
37672** Instead of a lock on the table/index rooted at page iRoot, the caller may
37673** hold a write-lock on the schema table (root page 1). This is also
37674** acceptable.
37675*/
37676static int hasSharedCacheTableLock(
37677  Btree *pBtree,         /* Handle that must hold lock */
37678  Pgno iRoot,            /* Root page of b-tree */
37679  int isIndex,           /* True if iRoot is the root of an index b-tree */
37680  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
37681){
37682  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
37683  Pgno iTab = 0;
37684  BtLock *pLock;
37685
37686  /* If this database is not shareable, or if the client is reading
37687  ** and has the read-uncommitted flag set, then no lock is required.
37688  ** Return true immediately.
37689  */
37690  if( (pBtree->sharable==0)
37691   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
37692  ){
37693    return 1;
37694  }
37695
37696  /* If the client is reading  or writing an index and the schema is
37697  ** not loaded, then it is too difficult to actually check to see if
37698  ** the correct locks are held.  So do not bother - just return true.
37699  ** This case does not come up very often anyhow.
37700  */
37701  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
37702    return 1;
37703  }
37704
37705  /* Figure out the root-page that the lock should be held on. For table
37706  ** b-trees, this is just the root page of the b-tree being read or
37707  ** written. For index b-trees, it is the root page of the associated
37708  ** table.  */
37709  if( isIndex ){
37710    HashElem *p;
37711    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
37712      Index *pIdx = (Index *)sqliteHashData(p);
37713      if( pIdx->tnum==(int)iRoot ){
37714        iTab = pIdx->pTable->tnum;
37715      }
37716    }
37717  }else{
37718    iTab = iRoot;
37719  }
37720
37721  /* Search for the required lock. Either a write-lock on root-page iTab, a
37722  ** write-lock on the schema table, or (if the client is reading) a
37723  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
37724  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
37725    if( pLock->pBtree==pBtree
37726     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
37727     && pLock->eLock>=eLockType
37728    ){
37729      return 1;
37730    }
37731  }
37732
37733  /* Failed to find the required lock. */
37734  return 0;
37735}
37736#endif /* SQLITE_DEBUG */
37737
37738#ifdef SQLITE_DEBUG
37739/*
37740**** This function may be used as part of assert() statements only. ****
37741**
37742** Return true if it would be illegal for pBtree to write into the
37743** table or index rooted at iRoot because other shared connections are
37744** simultaneously reading that same table or index.
37745**
37746** It is illegal for pBtree to write if some other Btree object that
37747** shares the same BtShared object is currently reading or writing
37748** the iRoot table.  Except, if the other Btree object has the
37749** read-uncommitted flag set, then it is OK for the other object to
37750** have a read cursor.
37751**
37752** For example, before writing to any part of the table or index
37753** rooted at page iRoot, one should call:
37754**
37755**    assert( !hasReadConflicts(pBtree, iRoot) );
37756*/
37757static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
37758  BtCursor *p;
37759  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
37760    if( p->pgnoRoot==iRoot
37761     && p->pBtree!=pBtree
37762     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
37763    ){
37764      return 1;
37765    }
37766  }
37767  return 0;
37768}
37769#endif    /* #ifdef SQLITE_DEBUG */
37770
37771/*
37772** Query to see if Btree handle p may obtain a lock of type eLock
37773** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
37774** SQLITE_OK if the lock may be obtained (by calling
37775** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
37776*/
37777static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
37778  BtShared *pBt = p->pBt;
37779  BtLock *pIter;
37780
37781  assert( sqlite3BtreeHoldsMutex(p) );
37782  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
37783  assert( p->db!=0 );
37784  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
37785
37786  /* If requesting a write-lock, then the Btree must have an open write
37787  ** transaction on this file. And, obviously, for this to be so there
37788  ** must be an open write transaction on the file itself.
37789  */
37790  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
37791  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
37792
37793  /* This routine is a no-op if the shared-cache is not enabled */
37794  if( !p->sharable ){
37795    return SQLITE_OK;
37796  }
37797
37798  /* If some other connection is holding an exclusive lock, the
37799  ** requested lock may not be obtained.
37800  */
37801  if( pBt->pWriter!=p && pBt->isExclusive ){
37802    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
37803    return SQLITE_LOCKED_SHAREDCACHE;
37804  }
37805
37806  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
37807    /* The condition (pIter->eLock!=eLock) in the following if(...)
37808    ** statement is a simplification of:
37809    **
37810    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
37811    **
37812    ** since we know that if eLock==WRITE_LOCK, then no other connection
37813    ** may hold a WRITE_LOCK on any table in this file (since there can
37814    ** only be a single writer).
37815    */
37816    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
37817    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
37818    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
37819      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
37820      if( eLock==WRITE_LOCK ){
37821        assert( p==pBt->pWriter );
37822        pBt->isPending = 1;
37823      }
37824      return SQLITE_LOCKED_SHAREDCACHE;
37825    }
37826  }
37827  return SQLITE_OK;
37828}
37829#endif /* !SQLITE_OMIT_SHARED_CACHE */
37830
37831#ifndef SQLITE_OMIT_SHARED_CACHE
37832/*
37833** Add a lock on the table with root-page iTable to the shared-btree used
37834** by Btree handle p. Parameter eLock must be either READ_LOCK or
37835** WRITE_LOCK.
37836**
37837** This function assumes the following:
37838**
37839**   (a) The specified Btree object p is connected to a sharable
37840**       database (one with the BtShared.sharable flag set), and
37841**
37842**   (b) No other Btree objects hold a lock that conflicts
37843**       with the requested lock (i.e. querySharedCacheTableLock() has
37844**       already been called and returned SQLITE_OK).
37845**
37846** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
37847** is returned if a malloc attempt fails.
37848*/
37849static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
37850  BtShared *pBt = p->pBt;
37851  BtLock *pLock = 0;
37852  BtLock *pIter;
37853
37854  assert( sqlite3BtreeHoldsMutex(p) );
37855  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
37856  assert( p->db!=0 );
37857
37858  /* A connection with the read-uncommitted flag set will never try to
37859  ** obtain a read-lock using this function. The only read-lock obtained
37860  ** by a connection in read-uncommitted mode is on the sqlite_master
37861  ** table, and that lock is obtained in BtreeBeginTrans().  */
37862  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
37863
37864  /* This function should only be called on a sharable b-tree after it
37865  ** has been determined that no other b-tree holds a conflicting lock.  */
37866  assert( p->sharable );
37867  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
37868
37869  /* First search the list for an existing lock on this table. */
37870  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
37871    if( pIter->iTable==iTable && pIter->pBtree==p ){
37872      pLock = pIter;
37873      break;
37874    }
37875  }
37876
37877  /* If the above search did not find a BtLock struct associating Btree p
37878  ** with table iTable, allocate one and link it into the list.
37879  */
37880  if( !pLock ){
37881    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
37882    if( !pLock ){
37883      return SQLITE_NOMEM;
37884    }
37885    pLock->iTable = iTable;
37886    pLock->pBtree = p;
37887    pLock->pNext = pBt->pLock;
37888    pBt->pLock = pLock;
37889  }
37890
37891  /* Set the BtLock.eLock variable to the maximum of the current lock
37892  ** and the requested lock. This means if a write-lock was already held
37893  ** and a read-lock requested, we don't incorrectly downgrade the lock.
37894  */
37895  assert( WRITE_LOCK>READ_LOCK );
37896  if( eLock>pLock->eLock ){
37897    pLock->eLock = eLock;
37898  }
37899
37900  return SQLITE_OK;
37901}
37902#endif /* !SQLITE_OMIT_SHARED_CACHE */
37903
37904#ifndef SQLITE_OMIT_SHARED_CACHE
37905/*
37906** Release all the table locks (locks obtained via calls to
37907** the setSharedCacheTableLock() procedure) held by Btree object p.
37908**
37909** This function assumes that Btree p has an open read or write
37910** transaction. If it does not, then the BtShared.isPending variable
37911** may be incorrectly cleared.
37912*/
37913static void clearAllSharedCacheTableLocks(Btree *p){
37914  BtShared *pBt = p->pBt;
37915  BtLock **ppIter = &pBt->pLock;
37916
37917  assert( sqlite3BtreeHoldsMutex(p) );
37918  assert( p->sharable || 0==*ppIter );
37919  assert( p->inTrans>0 );
37920
37921  while( *ppIter ){
37922    BtLock *pLock = *ppIter;
37923    assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
37924    assert( pLock->pBtree->inTrans>=pLock->eLock );
37925    if( pLock->pBtree==p ){
37926      *ppIter = pLock->pNext;
37927      assert( pLock->iTable!=1 || pLock==&p->lock );
37928      if( pLock->iTable!=1 ){
37929        sqlite3_free(pLock);
37930      }
37931    }else{
37932      ppIter = &pLock->pNext;
37933    }
37934  }
37935
37936  assert( pBt->isPending==0 || pBt->pWriter );
37937  if( pBt->pWriter==p ){
37938    pBt->pWriter = 0;
37939    pBt->isExclusive = 0;
37940    pBt->isPending = 0;
37941  }else if( pBt->nTransaction==2 ){
37942    /* This function is called when Btree p is concluding its
37943    ** transaction. If there currently exists a writer, and p is not
37944    ** that writer, then the number of locks held by connections other
37945    ** than the writer must be about to drop to zero. In this case
37946    ** set the isPending flag to 0.
37947    **
37948    ** If there is not currently a writer, then BtShared.isPending must
37949    ** be zero already. So this next line is harmless in that case.
37950    */
37951    pBt->isPending = 0;
37952  }
37953}
37954
37955/*
37956** This function changes all write-locks held by Btree p into read-locks.
37957*/
37958static void downgradeAllSharedCacheTableLocks(Btree *p){
37959  BtShared *pBt = p->pBt;
37960  if( pBt->pWriter==p ){
37961    BtLock *pLock;
37962    pBt->pWriter = 0;
37963    pBt->isExclusive = 0;
37964    pBt->isPending = 0;
37965    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
37966      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
37967      pLock->eLock = READ_LOCK;
37968    }
37969  }
37970}
37971
37972#endif /* SQLITE_OMIT_SHARED_CACHE */
37973
37974static void releasePage(MemPage *pPage);  /* Forward reference */
37975
37976/*
37977***** This routine is used inside of assert() only ****
37978**
37979** Verify that the cursor holds the mutex on its BtShared
37980*/
37981#ifdef SQLITE_DEBUG
37982static int cursorHoldsMutex(BtCursor *p){
37983  return sqlite3_mutex_held(p->pBt->mutex);
37984}
37985#endif
37986
37987
37988#ifndef SQLITE_OMIT_INCRBLOB
37989/*
37990** Invalidate the overflow page-list cache for cursor pCur, if any.
37991*/
37992static void invalidateOverflowCache(BtCursor *pCur){
37993  assert( cursorHoldsMutex(pCur) );
37994  sqlite3_free(pCur->aOverflow);
37995  pCur->aOverflow = 0;
37996}
37997
37998/*
37999** Invalidate the overflow page-list cache for all cursors opened
38000** on the shared btree structure pBt.
38001*/
38002static void invalidateAllOverflowCache(BtShared *pBt){
38003  BtCursor *p;
38004  assert( sqlite3_mutex_held(pBt->mutex) );
38005  for(p=pBt->pCursor; p; p=p->pNext){
38006    invalidateOverflowCache(p);
38007  }
38008}
38009
38010/*
38011** This function is called before modifying the contents of a table
38012** to invalidate any incrblob cursors that are open on the
38013** row or one of the rows being modified.
38014**
38015** If argument isClearTable is true, then the entire contents of the
38016** table is about to be deleted. In this case invalidate all incrblob
38017** cursors open on any row within the table with root-page pgnoRoot.
38018**
38019** Otherwise, if argument isClearTable is false, then the row with
38020** rowid iRow is being replaced or deleted. In this case invalidate
38021** only those incrblob cursors open on that specific row.
38022*/
38023static void invalidateIncrblobCursors(
38024  Btree *pBtree,          /* The database file to check */
38025  i64 iRow,               /* The rowid that might be changing */
38026  int isClearTable        /* True if all rows are being deleted */
38027){
38028  BtCursor *p;
38029  BtShared *pBt = pBtree->pBt;
38030  assert( sqlite3BtreeHoldsMutex(pBtree) );
38031  for(p=pBt->pCursor; p; p=p->pNext){
38032    if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
38033      p->eState = CURSOR_INVALID;
38034    }
38035  }
38036}
38037
38038#else
38039  /* Stub functions when INCRBLOB is omitted */
38040  #define invalidateOverflowCache(x)
38041  #define invalidateAllOverflowCache(x)
38042  #define invalidateIncrblobCursors(x,y,z)
38043#endif /* SQLITE_OMIT_INCRBLOB */
38044
38045/*
38046** Set bit pgno of the BtShared.pHasContent bitvec. This is called
38047** when a page that previously contained data becomes a free-list leaf
38048** page.
38049**
38050** The BtShared.pHasContent bitvec exists to work around an obscure
38051** bug caused by the interaction of two useful IO optimizations surrounding
38052** free-list leaf pages:
38053**
38054**   1) When all data is deleted from a page and the page becomes
38055**      a free-list leaf page, the page is not written to the database
38056**      (as free-list leaf pages contain no meaningful data). Sometimes
38057**      such a page is not even journalled (as it will not be modified,
38058**      why bother journalling it?).
38059**
38060**   2) When a free-list leaf page is reused, its content is not read
38061**      from the database or written to the journal file (why should it
38062**      be, if it is not at all meaningful?).
38063**
38064** By themselves, these optimizations work fine and provide a handy
38065** performance boost to bulk delete or insert operations. However, if
38066** a page is moved to the free-list and then reused within the same
38067** transaction, a problem comes up. If the page is not journalled when
38068** it is moved to the free-list and it is also not journalled when it
38069** is extracted from the free-list and reused, then the original data
38070** may be lost. In the event of a rollback, it may not be possible
38071** to restore the database to its original configuration.
38072**
38073** The solution is the BtShared.pHasContent bitvec. Whenever a page is
38074** moved to become a free-list leaf page, the corresponding bit is
38075** set in the bitvec. Whenever a leaf page is extracted from the free-list,
38076** optimization 2 above is omitted if the corresponding bit is already
38077** set in BtShared.pHasContent. The contents of the bitvec are cleared
38078** at the end of every transaction.
38079*/
38080static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
38081  int rc = SQLITE_OK;
38082  if( !pBt->pHasContent ){
38083    int nPage = 100;
38084    sqlite3PagerPagecount(pBt->pPager, &nPage);
38085    /* If sqlite3PagerPagecount() fails there is no harm because the
38086    ** nPage variable is unchanged from its default value of 100 */
38087    pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
38088    if( !pBt->pHasContent ){
38089      rc = SQLITE_NOMEM;
38090    }
38091  }
38092  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
38093    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
38094  }
38095  return rc;
38096}
38097
38098/*
38099** Query the BtShared.pHasContent vector.
38100**
38101** This function is called when a free-list leaf page is removed from the
38102** free-list for reuse. It returns false if it is safe to retrieve the
38103** page from the pager layer with the 'no-content' flag set. True otherwise.
38104*/
38105static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
38106  Bitvec *p = pBt->pHasContent;
38107  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
38108}
38109
38110/*
38111** Clear (destroy) the BtShared.pHasContent bitvec. This should be
38112** invoked at the conclusion of each write-transaction.
38113*/
38114static void btreeClearHasContent(BtShared *pBt){
38115  sqlite3BitvecDestroy(pBt->pHasContent);
38116  pBt->pHasContent = 0;
38117}
38118
38119/*
38120** Save the current cursor position in the variables BtCursor.nKey
38121** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
38122**
38123** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
38124** prior to calling this routine.
38125*/
38126static int saveCursorPosition(BtCursor *pCur){
38127  int rc;
38128
38129  assert( CURSOR_VALID==pCur->eState );
38130  assert( 0==pCur->pKey );
38131  assert( cursorHoldsMutex(pCur) );
38132
38133  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
38134  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
38135
38136  /* If this is an intKey table, then the above call to BtreeKeySize()
38137  ** stores the integer key in pCur->nKey. In this case this value is
38138  ** all that is required. Otherwise, if pCur is not open on an intKey
38139  ** table, then malloc space for and store the pCur->nKey bytes of key
38140  ** data.
38141  */
38142  if( 0==pCur->apPage[0]->intKey ){
38143    void *pKey = sqlite3Malloc( (int)pCur->nKey );
38144    if( pKey ){
38145      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
38146      if( rc==SQLITE_OK ){
38147        pCur->pKey = pKey;
38148      }else{
38149        sqlite3_free(pKey);
38150      }
38151    }else{
38152      rc = SQLITE_NOMEM;
38153    }
38154  }
38155  assert( !pCur->apPage[0]->intKey || !pCur->pKey );
38156
38157  if( rc==SQLITE_OK ){
38158    int i;
38159    for(i=0; i<=pCur->iPage; i++){
38160      releasePage(pCur->apPage[i]);
38161      pCur->apPage[i] = 0;
38162    }
38163    pCur->iPage = -1;
38164    pCur->eState = CURSOR_REQUIRESEEK;
38165  }
38166
38167  invalidateOverflowCache(pCur);
38168  return rc;
38169}
38170
38171/*
38172** Save the positions of all cursors (except pExcept) that are open on
38173** the table  with root-page iRoot. Usually, this is called just before cursor
38174** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
38175*/
38176static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
38177  BtCursor *p;
38178  assert( sqlite3_mutex_held(pBt->mutex) );
38179  assert( pExcept==0 || pExcept->pBt==pBt );
38180  for(p=pBt->pCursor; p; p=p->pNext){
38181    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
38182        p->eState==CURSOR_VALID ){
38183      int rc = saveCursorPosition(p);
38184      if( SQLITE_OK!=rc ){
38185        return rc;
38186      }
38187    }
38188  }
38189  return SQLITE_OK;
38190}
38191
38192/*
38193** Clear the current cursor position.
38194*/
38195SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
38196  assert( cursorHoldsMutex(pCur) );
38197  sqlite3_free(pCur->pKey);
38198  pCur->pKey = 0;
38199  pCur->eState = CURSOR_INVALID;
38200}
38201
38202/*
38203** In this version of BtreeMoveto, pKey is a packed index record
38204** such as is generated by the OP_MakeRecord opcode.  Unpack the
38205** record and then call BtreeMovetoUnpacked() to do the work.
38206*/
38207static int btreeMoveto(
38208  BtCursor *pCur,     /* Cursor open on the btree to be searched */
38209  const void *pKey,   /* Packed key if the btree is an index */
38210  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
38211  int bias,           /* Bias search to the high end */
38212  int *pRes           /* Write search results here */
38213){
38214  int rc;                    /* Status code */
38215  UnpackedRecord *pIdxKey;   /* Unpacked index key */
38216  char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
38217
38218  if( pKey ){
38219    assert( nKey==(i64)(int)nKey );
38220    pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
38221                                      aSpace, sizeof(aSpace));
38222    if( pIdxKey==0 ) return SQLITE_NOMEM;
38223  }else{
38224    pIdxKey = 0;
38225  }
38226  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
38227  if( pKey ){
38228    sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
38229  }
38230  return rc;
38231}
38232
38233/*
38234** Restore the cursor to the position it was in (or as close to as possible)
38235** when saveCursorPosition() was called. Note that this call deletes the
38236** saved position info stored by saveCursorPosition(), so there can be
38237** at most one effective restoreCursorPosition() call after each
38238** saveCursorPosition().
38239*/
38240static int btreeRestoreCursorPosition(BtCursor *pCur){
38241  int rc;
38242  assert( cursorHoldsMutex(pCur) );
38243  assert( pCur->eState>=CURSOR_REQUIRESEEK );
38244  if( pCur->eState==CURSOR_FAULT ){
38245    return pCur->skipNext;
38246  }
38247  pCur->eState = CURSOR_INVALID;
38248  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
38249  if( rc==SQLITE_OK ){
38250    sqlite3_free(pCur->pKey);
38251    pCur->pKey = 0;
38252    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
38253  }
38254  return rc;
38255}
38256
38257#define restoreCursorPosition(p) \
38258  (p->eState>=CURSOR_REQUIRESEEK ? \
38259         btreeRestoreCursorPosition(p) : \
38260         SQLITE_OK)
38261
38262/*
38263** Determine whether or not a cursor has moved from the position it
38264** was last placed at.  Cursors can move when the row they are pointing
38265** at is deleted out from under them.
38266**
38267** This routine returns an error code if something goes wrong.  The
38268** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
38269*/
38270SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
38271  int rc;
38272
38273  rc = restoreCursorPosition(pCur);
38274  if( rc ){
38275    *pHasMoved = 1;
38276    return rc;
38277  }
38278  if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
38279    *pHasMoved = 1;
38280  }else{
38281    *pHasMoved = 0;
38282  }
38283  return SQLITE_OK;
38284}
38285
38286#ifndef SQLITE_OMIT_AUTOVACUUM
38287/*
38288** Given a page number of a regular database page, return the page
38289** number for the pointer-map page that contains the entry for the
38290** input page number.
38291*/
38292static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
38293  int nPagesPerMapPage;
38294  Pgno iPtrMap, ret;
38295  assert( sqlite3_mutex_held(pBt->mutex) );
38296  nPagesPerMapPage = (pBt->usableSize/5)+1;
38297  iPtrMap = (pgno-2)/nPagesPerMapPage;
38298  ret = (iPtrMap*nPagesPerMapPage) + 2;
38299  if( ret==PENDING_BYTE_PAGE(pBt) ){
38300    ret++;
38301  }
38302  return ret;
38303}
38304
38305/*
38306** Write an entry into the pointer map.
38307**
38308** This routine updates the pointer map entry for page number 'key'
38309** so that it maps to type 'eType' and parent page number 'pgno'.
38310**
38311** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
38312** a no-op.  If an error occurs, the appropriate error code is written
38313** into *pRC.
38314*/
38315static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
38316  DbPage *pDbPage;  /* The pointer map page */
38317  u8 *pPtrmap;      /* The pointer map data */
38318  Pgno iPtrmap;     /* The pointer map page number */
38319  int offset;       /* Offset in pointer map page */
38320  int rc;           /* Return code from subfunctions */
38321
38322  if( *pRC ) return;
38323
38324  assert( sqlite3_mutex_held(pBt->mutex) );
38325  /* The master-journal page number must never be used as a pointer map page */
38326  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
38327
38328  assert( pBt->autoVacuum );
38329  if( key==0 ){
38330    *pRC = SQLITE_CORRUPT_BKPT;
38331    return;
38332  }
38333  iPtrmap = PTRMAP_PAGENO(pBt, key);
38334  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
38335  if( rc!=SQLITE_OK ){
38336    *pRC = rc;
38337    return;
38338  }
38339  offset = PTRMAP_PTROFFSET(iPtrmap, key);
38340  if( offset<0 ){
38341    *pRC = SQLITE_CORRUPT_BKPT;
38342    goto ptrmap_exit;
38343  }
38344  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
38345
38346  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
38347    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
38348    *pRC= rc = sqlite3PagerWrite(pDbPage);
38349    if( rc==SQLITE_OK ){
38350      pPtrmap[offset] = eType;
38351      put4byte(&pPtrmap[offset+1], parent);
38352    }
38353  }
38354
38355ptrmap_exit:
38356  sqlite3PagerUnref(pDbPage);
38357}
38358
38359/*
38360** Read an entry from the pointer map.
38361**
38362** This routine retrieves the pointer map entry for page 'key', writing
38363** the type and parent page number to *pEType and *pPgno respectively.
38364** An error code is returned if something goes wrong, otherwise SQLITE_OK.
38365*/
38366static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
38367  DbPage *pDbPage;   /* The pointer map page */
38368  int iPtrmap;       /* Pointer map page index */
38369  u8 *pPtrmap;       /* Pointer map page data */
38370  int offset;        /* Offset of entry in pointer map */
38371  int rc;
38372
38373  assert( sqlite3_mutex_held(pBt->mutex) );
38374
38375  iPtrmap = PTRMAP_PAGENO(pBt, key);
38376  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
38377  if( rc!=0 ){
38378    return rc;
38379  }
38380  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
38381
38382  offset = PTRMAP_PTROFFSET(iPtrmap, key);
38383  assert( pEType!=0 );
38384  *pEType = pPtrmap[offset];
38385  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
38386
38387  sqlite3PagerUnref(pDbPage);
38388  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
38389  return SQLITE_OK;
38390}
38391
38392#else /* if defined SQLITE_OMIT_AUTOVACUUM */
38393  #define ptrmapPut(w,x,y,z,rc)
38394  #define ptrmapGet(w,x,y,z) SQLITE_OK
38395  #define ptrmapPutOvflPtr(x, y, rc)
38396#endif
38397
38398/*
38399** Given a btree page and a cell index (0 means the first cell on
38400** the page, 1 means the second cell, and so forth) return a pointer
38401** to the cell content.
38402**
38403** This routine works only for pages that do not contain overflow cells.
38404*/
38405#define findCell(P,I) \
38406  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
38407
38408/*
38409** This a more complex version of findCell() that works for
38410** pages that do contain overflow cells.
38411*/
38412static u8 *findOverflowCell(MemPage *pPage, int iCell){
38413  int i;
38414  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38415  for(i=pPage->nOverflow-1; i>=0; i--){
38416    int k;
38417    struct _OvflCell *pOvfl;
38418    pOvfl = &pPage->aOvfl[i];
38419    k = pOvfl->idx;
38420    if( k<=iCell ){
38421      if( k==iCell ){
38422        return pOvfl->pCell;
38423      }
38424      iCell--;
38425    }
38426  }
38427  return findCell(pPage, iCell);
38428}
38429
38430/*
38431** Parse a cell content block and fill in the CellInfo structure.  There
38432** are two versions of this function.  btreeParseCell() takes a
38433** cell index as the second argument and btreeParseCellPtr()
38434** takes a pointer to the body of the cell as its second argument.
38435**
38436** Within this file, the parseCell() macro can be called instead of
38437** btreeParseCellPtr(). Using some compilers, this will be faster.
38438*/
38439static void btreeParseCellPtr(
38440  MemPage *pPage,         /* Page containing the cell */
38441  u8 *pCell,              /* Pointer to the cell text. */
38442  CellInfo *pInfo         /* Fill in this structure */
38443){
38444  u16 n;                  /* Number bytes in cell content header */
38445  u32 nPayload;           /* Number of bytes of cell payload */
38446
38447  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38448
38449  pInfo->pCell = pCell;
38450  assert( pPage->leaf==0 || pPage->leaf==1 );
38451  n = pPage->childPtrSize;
38452  assert( n==4-4*pPage->leaf );
38453  if( pPage->intKey ){
38454    if( pPage->hasData ){
38455      n += getVarint32(&pCell[n], nPayload);
38456    }else{
38457      nPayload = 0;
38458    }
38459    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
38460    pInfo->nData = nPayload;
38461  }else{
38462    pInfo->nData = 0;
38463    n += getVarint32(&pCell[n], nPayload);
38464    pInfo->nKey = nPayload;
38465  }
38466  pInfo->nPayload = nPayload;
38467  pInfo->nHeader = n;
38468  testcase( nPayload==pPage->maxLocal );
38469  testcase( nPayload==pPage->maxLocal+1 );
38470  if( likely(nPayload<=pPage->maxLocal) ){
38471    /* This is the (easy) common case where the entire payload fits
38472    ** on the local page.  No overflow is required.
38473    */
38474    int nSize;          /* Total size of cell content in bytes */
38475    nSize = nPayload + n;
38476    pInfo->nLocal = (u16)nPayload;
38477    pInfo->iOverflow = 0;
38478    if( (nSize & ~3)==0 ){
38479      nSize = 4;        /* Minimum cell size is 4 */
38480    }
38481    pInfo->nSize = (u16)nSize;
38482  }else{
38483    /* If the payload will not fit completely on the local page, we have
38484    ** to decide how much to store locally and how much to spill onto
38485    ** overflow pages.  The strategy is to minimize the amount of unused
38486    ** space on overflow pages while keeping the amount of local storage
38487    ** in between minLocal and maxLocal.
38488    **
38489    ** Warning:  changing the way overflow payload is distributed in any
38490    ** way will result in an incompatible file format.
38491    */
38492    int minLocal;  /* Minimum amount of payload held locally */
38493    int maxLocal;  /* Maximum amount of payload held locally */
38494    int surplus;   /* Overflow payload available for local storage */
38495
38496    minLocal = pPage->minLocal;
38497    maxLocal = pPage->maxLocal;
38498    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
38499    testcase( surplus==maxLocal );
38500    testcase( surplus==maxLocal+1 );
38501    if( surplus <= maxLocal ){
38502      pInfo->nLocal = (u16)surplus;
38503    }else{
38504      pInfo->nLocal = (u16)minLocal;
38505    }
38506    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
38507    pInfo->nSize = pInfo->iOverflow + 4;
38508  }
38509}
38510#define parseCell(pPage, iCell, pInfo) \
38511  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
38512static void btreeParseCell(
38513  MemPage *pPage,         /* Page containing the cell */
38514  int iCell,              /* The cell index.  First cell is 0 */
38515  CellInfo *pInfo         /* Fill in this structure */
38516){
38517  parseCell(pPage, iCell, pInfo);
38518}
38519
38520/*
38521** Compute the total number of bytes that a Cell needs in the cell
38522** data area of the btree-page.  The return number includes the cell
38523** data header and the local payload, but not any overflow page or
38524** the space used by the cell pointer.
38525*/
38526static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
38527  u8 *pIter = &pCell[pPage->childPtrSize];
38528  u32 nSize;
38529
38530#ifdef SQLITE_DEBUG
38531  /* The value returned by this function should always be the same as
38532  ** the (CellInfo.nSize) value found by doing a full parse of the
38533  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
38534  ** this function verifies that this invariant is not violated. */
38535  CellInfo debuginfo;
38536  btreeParseCellPtr(pPage, pCell, &debuginfo);
38537#endif
38538
38539  if( pPage->intKey ){
38540    u8 *pEnd;
38541    if( pPage->hasData ){
38542      pIter += getVarint32(pIter, nSize);
38543    }else{
38544      nSize = 0;
38545    }
38546
38547    /* pIter now points at the 64-bit integer key value, a variable length
38548    ** integer. The following block moves pIter to point at the first byte
38549    ** past the end of the key value. */
38550    pEnd = &pIter[9];
38551    while( (*pIter++)&0x80 && pIter<pEnd );
38552  }else{
38553    pIter += getVarint32(pIter, nSize);
38554  }
38555
38556  testcase( nSize==pPage->maxLocal );
38557  testcase( nSize==pPage->maxLocal+1 );
38558  if( nSize>pPage->maxLocal ){
38559    int minLocal = pPage->minLocal;
38560    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
38561    testcase( nSize==pPage->maxLocal );
38562    testcase( nSize==pPage->maxLocal+1 );
38563    if( nSize>pPage->maxLocal ){
38564      nSize = minLocal;
38565    }
38566    nSize += 4;
38567  }
38568  nSize += (u32)(pIter - pCell);
38569
38570  /* The minimum size of any cell is 4 bytes. */
38571  if( nSize<4 ){
38572    nSize = 4;
38573  }
38574
38575  assert( nSize==debuginfo.nSize );
38576  return (u16)nSize;
38577}
38578
38579#ifdef SQLITE_DEBUG
38580/* This variation on cellSizePtr() is used inside of assert() statements
38581** only. */
38582static u16 cellSize(MemPage *pPage, int iCell){
38583  return cellSizePtr(pPage, findCell(pPage, iCell));
38584}
38585#endif
38586
38587#ifndef SQLITE_OMIT_AUTOVACUUM
38588/*
38589** If the cell pCell, part of page pPage contains a pointer
38590** to an overflow page, insert an entry into the pointer-map
38591** for the overflow page.
38592*/
38593static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
38594  CellInfo info;
38595  if( *pRC ) return;
38596  assert( pCell!=0 );
38597  btreeParseCellPtr(pPage, pCell, &info);
38598  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
38599  if( info.iOverflow ){
38600    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
38601    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
38602  }
38603}
38604#endif
38605
38606
38607/*
38608** Defragment the page given.  All Cells are moved to the
38609** end of the page and all free space is collected into one
38610** big FreeBlk that occurs in between the header and cell
38611** pointer array and the cell content area.
38612*/
38613static int defragmentPage(MemPage *pPage){
38614  int i;                     /* Loop counter */
38615  int pc;                    /* Address of a i-th cell */
38616  int hdr;                   /* Offset to the page header */
38617  int size;                  /* Size of a cell */
38618  int usableSize;            /* Number of usable bytes on a page */
38619  int cellOffset;            /* Offset to the cell pointer array */
38620  int cbrk;                  /* Offset to the cell content area */
38621  int nCell;                 /* Number of cells on the page */
38622  unsigned char *data;       /* The page data */
38623  unsigned char *temp;       /* Temp area for cell content */
38624  int iCellFirst;            /* First allowable cell index */
38625  int iCellLast;             /* Last possible cell index */
38626
38627
38628  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38629  assert( pPage->pBt!=0 );
38630  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
38631  assert( pPage->nOverflow==0 );
38632  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38633  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
38634  data = pPage->aData;
38635  hdr = pPage->hdrOffset;
38636  cellOffset = pPage->cellOffset;
38637  nCell = pPage->nCell;
38638  assert( nCell==get2byte(&data[hdr+3]) );
38639  usableSize = pPage->pBt->usableSize;
38640  cbrk = get2byte(&data[hdr+5]);
38641  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
38642  cbrk = usableSize;
38643  iCellFirst = cellOffset + 2*nCell;
38644  iCellLast = usableSize - 4;
38645  for(i=0; i<nCell; i++){
38646    u8 *pAddr;     /* The i-th cell pointer */
38647    pAddr = &data[cellOffset + i*2];
38648    pc = get2byte(pAddr);
38649    testcase( pc==iCellFirst );
38650    testcase( pc==iCellLast );
38651#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
38652    /* These conditions have already been verified in btreeInitPage()
38653    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
38654    */
38655    if( pc<iCellFirst || pc>iCellLast ){
38656      return SQLITE_CORRUPT_BKPT;
38657    }
38658#endif
38659    assert( pc>=iCellFirst && pc<=iCellLast );
38660    size = cellSizePtr(pPage, &temp[pc]);
38661    cbrk -= size;
38662#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
38663    if( cbrk<iCellFirst ){
38664      return SQLITE_CORRUPT_BKPT;
38665    }
38666#else
38667    if( cbrk<iCellFirst || pc+size>usableSize ){
38668      return SQLITE_CORRUPT_BKPT;
38669    }
38670#endif
38671    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
38672    testcase( cbrk+size==usableSize );
38673    testcase( pc+size==usableSize );
38674    memcpy(&data[cbrk], &temp[pc], size);
38675    put2byte(pAddr, cbrk);
38676  }
38677  assert( cbrk>=iCellFirst );
38678  put2byte(&data[hdr+5], cbrk);
38679  data[hdr+1] = 0;
38680  data[hdr+2] = 0;
38681  data[hdr+7] = 0;
38682  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
38683  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38684  if( cbrk-iCellFirst!=pPage->nFree ){
38685    return SQLITE_CORRUPT_BKPT;
38686  }
38687  return SQLITE_OK;
38688}
38689
38690/*
38691** Allocate nByte bytes of space from within the B-Tree page passed
38692** as the first argument. Write into *pIdx the index into pPage->aData[]
38693** of the first byte of allocated space. Return either SQLITE_OK or
38694** an error code (usually SQLITE_CORRUPT).
38695**
38696** The caller guarantees that there is sufficient space to make the
38697** allocation.  This routine might need to defragment in order to bring
38698** all the space together, however.  This routine will avoid using
38699** the first two bytes past the cell pointer area since presumably this
38700** allocation is being made in order to insert a new cell, so we will
38701** also end up needing a new cell pointer.
38702*/
38703static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
38704  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
38705  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
38706  int nFrag;                           /* Number of fragmented bytes on pPage */
38707  int top;                             /* First byte of cell content area */
38708  int gap;        /* First byte of gap between cell pointers and cell content */
38709  int rc;         /* Integer return code */
38710  int usableSize; /* Usable size of the page */
38711
38712  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38713  assert( pPage->pBt );
38714  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38715  assert( nByte>=0 );  /* Minimum cell size is 4 */
38716  assert( pPage->nFree>=nByte );
38717  assert( pPage->nOverflow==0 );
38718  usableSize = pPage->pBt->usableSize;
38719  assert( nByte < usableSize-8 );
38720
38721  nFrag = data[hdr+7];
38722  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
38723  gap = pPage->cellOffset + 2*pPage->nCell;
38724  top = get2byte(&data[hdr+5]);
38725  if( gap>top ) return SQLITE_CORRUPT_BKPT;
38726  testcase( gap+2==top );
38727  testcase( gap+1==top );
38728  testcase( gap==top );
38729
38730  if( nFrag>=60 ){
38731    /* Always defragment highly fragmented pages */
38732    rc = defragmentPage(pPage);
38733    if( rc ) return rc;
38734    top = get2byte(&data[hdr+5]);
38735  }else if( gap+2<=top ){
38736    /* Search the freelist looking for a free slot big enough to satisfy
38737    ** the request. The allocation is made from the first free slot in
38738    ** the list that is large enough to accomadate it.
38739    */
38740    int pc, addr;
38741    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
38742      int size;            /* Size of the free slot */
38743      if( pc>usableSize-4 || pc<addr+4 ){
38744        return SQLITE_CORRUPT_BKPT;
38745      }
38746      size = get2byte(&data[pc+2]);
38747      if( size>=nByte ){
38748        int x = size - nByte;
38749        testcase( x==4 );
38750        testcase( x==3 );
38751        if( x<4 ){
38752          /* Remove the slot from the free-list. Update the number of
38753          ** fragmented bytes within the page. */
38754          memcpy(&data[addr], &data[pc], 2);
38755          data[hdr+7] = (u8)(nFrag + x);
38756        }else if( size+pc > usableSize ){
38757          return SQLITE_CORRUPT_BKPT;
38758        }else{
38759          /* The slot remains on the free-list. Reduce its size to account
38760          ** for the portion used by the new allocation. */
38761          put2byte(&data[pc+2], x);
38762        }
38763        *pIdx = pc + x;
38764        return SQLITE_OK;
38765      }
38766    }
38767  }
38768
38769  /* Check to make sure there is enough space in the gap to satisfy
38770  ** the allocation.  If not, defragment.
38771  */
38772  testcase( gap+2+nByte==top );
38773  if( gap+2+nByte>top ){
38774    rc = defragmentPage(pPage);
38775    if( rc ) return rc;
38776    top = get2byte(&data[hdr+5]);
38777    assert( gap+nByte<=top );
38778  }
38779
38780
38781  /* Allocate memory from the gap in between the cell pointer array
38782  ** and the cell content area.  The btreeInitPage() call has already
38783  ** validated the freelist.  Given that the freelist is valid, there
38784  ** is no way that the allocation can extend off the end of the page.
38785  ** The assert() below verifies the previous sentence.
38786  */
38787  top -= nByte;
38788  put2byte(&data[hdr+5], top);
38789  assert( top+nByte <= pPage->pBt->usableSize );
38790  *pIdx = top;
38791  return SQLITE_OK;
38792}
38793
38794/*
38795** Return a section of the pPage->aData to the freelist.
38796** The first byte of the new free block is pPage->aDisk[start]
38797** and the size of the block is "size" bytes.
38798**
38799** Most of the effort here is involved in coalesing adjacent
38800** free blocks into a single big free block.
38801*/
38802static int freeSpace(MemPage *pPage, int start, int size){
38803  int addr, pbegin, hdr;
38804  int iLast;                        /* Largest possible freeblock offset */
38805  unsigned char *data = pPage->aData;
38806
38807  assert( pPage->pBt!=0 );
38808  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38809  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
38810  assert( (start + size)<=pPage->pBt->usableSize );
38811  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38812  assert( size>=0 );   /* Minimum cell size is 4 */
38813
38814#ifdef SQLITE_SECURE_DELETE
38815  /* Overwrite deleted information with zeros when the SECURE_DELETE
38816  ** option is enabled at compile-time */
38817  memset(&data[start], 0, size);
38818#endif
38819
38820  /* Add the space back into the linked list of freeblocks.  Note that
38821  ** even though the freeblock list was checked by btreeInitPage(),
38822  ** btreeInitPage() did not detect overlapping cells or
38823  ** freeblocks that overlapped cells.   Nor does it detect when the
38824  ** cell content area exceeds the value in the page header.  If these
38825  ** situations arise, then subsequent insert operations might corrupt
38826  ** the freelist.  So we do need to check for corruption while scanning
38827  ** the freelist.
38828  */
38829  hdr = pPage->hdrOffset;
38830  addr = hdr + 1;
38831  iLast = pPage->pBt->usableSize - 4;
38832  assert( start<=iLast );
38833  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
38834    if( pbegin<addr+4 ){
38835      return SQLITE_CORRUPT_BKPT;
38836    }
38837    addr = pbegin;
38838  }
38839  if( pbegin>iLast ){
38840    return SQLITE_CORRUPT_BKPT;
38841  }
38842  assert( pbegin>addr || pbegin==0 );
38843  put2byte(&data[addr], start);
38844  put2byte(&data[start], pbegin);
38845  put2byte(&data[start+2], size);
38846  pPage->nFree = pPage->nFree + (u16)size;
38847
38848  /* Coalesce adjacent free blocks */
38849  addr = hdr + 1;
38850  while( (pbegin = get2byte(&data[addr]))>0 ){
38851    int pnext, psize, x;
38852    assert( pbegin>addr );
38853    assert( pbegin<=pPage->pBt->usableSize-4 );
38854    pnext = get2byte(&data[pbegin]);
38855    psize = get2byte(&data[pbegin+2]);
38856    if( pbegin + psize + 3 >= pnext && pnext>0 ){
38857      int frag = pnext - (pbegin+psize);
38858      if( (frag<0) || (frag>(int)data[hdr+7]) ){
38859        return SQLITE_CORRUPT_BKPT;
38860      }
38861      data[hdr+7] -= (u8)frag;
38862      x = get2byte(&data[pnext]);
38863      put2byte(&data[pbegin], x);
38864      x = pnext + get2byte(&data[pnext+2]) - pbegin;
38865      put2byte(&data[pbegin+2], x);
38866    }else{
38867      addr = pbegin;
38868    }
38869  }
38870
38871  /* If the cell content area begins with a freeblock, remove it. */
38872  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
38873    int top;
38874    pbegin = get2byte(&data[hdr+1]);
38875    memcpy(&data[hdr+1], &data[pbegin], 2);
38876    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
38877    put2byte(&data[hdr+5], top);
38878  }
38879  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
38880  return SQLITE_OK;
38881}
38882
38883/*
38884** Decode the flags byte (the first byte of the header) for a page
38885** and initialize fields of the MemPage structure accordingly.
38886**
38887** Only the following combinations are supported.  Anything different
38888** indicates a corrupt database files:
38889**
38890**         PTF_ZERODATA
38891**         PTF_ZERODATA | PTF_LEAF
38892**         PTF_LEAFDATA | PTF_INTKEY
38893**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
38894*/
38895static int decodeFlags(MemPage *pPage, int flagByte){
38896  BtShared *pBt;     /* A copy of pPage->pBt */
38897
38898  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
38899  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38900  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
38901  flagByte &= ~PTF_LEAF;
38902  pPage->childPtrSize = 4-4*pPage->leaf;
38903  pBt = pPage->pBt;
38904  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
38905    pPage->intKey = 1;
38906    pPage->hasData = pPage->leaf;
38907    pPage->maxLocal = pBt->maxLeaf;
38908    pPage->minLocal = pBt->minLeaf;
38909  }else if( flagByte==PTF_ZERODATA ){
38910    pPage->intKey = 0;
38911    pPage->hasData = 0;
38912    pPage->maxLocal = pBt->maxLocal;
38913    pPage->minLocal = pBt->minLocal;
38914  }else{
38915    return SQLITE_CORRUPT_BKPT;
38916  }
38917  return SQLITE_OK;
38918}
38919
38920/*
38921** Initialize the auxiliary information for a disk block.
38922**
38923** Return SQLITE_OK on success.  If we see that the page does
38924** not contain a well-formed database page, then return
38925** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
38926** guarantee that the page is well-formed.  It only shows that
38927** we failed to detect any corruption.
38928*/
38929static int btreeInitPage(MemPage *pPage){
38930
38931  assert( pPage->pBt!=0 );
38932  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
38933  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
38934  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
38935  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
38936
38937  if( !pPage->isInit ){
38938    u16 pc;            /* Address of a freeblock within pPage->aData[] */
38939    u8 hdr;            /* Offset to beginning of page header */
38940    u8 *data;          /* Equal to pPage->aData */
38941    BtShared *pBt;        /* The main btree structure */
38942    u16 usableSize;    /* Amount of usable space on each page */
38943    u16 cellOffset;    /* Offset from start of page to first cell pointer */
38944    u16 nFree;         /* Number of unused bytes on the page */
38945    u16 top;           /* First byte of the cell content area */
38946    int iCellFirst;    /* First allowable cell or freeblock offset */
38947    int iCellLast;     /* Last possible cell or freeblock offset */
38948
38949    pBt = pPage->pBt;
38950
38951    hdr = pPage->hdrOffset;
38952    data = pPage->aData;
38953    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
38954    assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
38955    pPage->maskPage = pBt->pageSize - 1;
38956    pPage->nOverflow = 0;
38957    usableSize = pBt->usableSize;
38958    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
38959    top = get2byte(&data[hdr+5]);
38960    pPage->nCell = get2byte(&data[hdr+3]);
38961    if( pPage->nCell>MX_CELL(pBt) ){
38962      /* To many cells for a single page.  The page must be corrupt */
38963      return SQLITE_CORRUPT_BKPT;
38964    }
38965    testcase( pPage->nCell==MX_CELL(pBt) );
38966
38967    /* A malformed database page might cause us to read past the end
38968    ** of page when parsing a cell.
38969    **
38970    ** The following block of code checks early to see if a cell extends
38971    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
38972    ** returned if it does.
38973    */
38974    iCellFirst = cellOffset + 2*pPage->nCell;
38975    iCellLast = usableSize - 4;
38976#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
38977    {
38978      int i;            /* Index into the cell pointer array */
38979      int sz;           /* Size of a cell */
38980
38981      if( !pPage->leaf ) iCellLast--;
38982      for(i=0; i<pPage->nCell; i++){
38983        pc = get2byte(&data[cellOffset+i*2]);
38984        testcase( pc==iCellFirst );
38985        testcase( pc==iCellLast );
38986        if( pc<iCellFirst || pc>iCellLast ){
38987          return SQLITE_CORRUPT_BKPT;
38988        }
38989        sz = cellSizePtr(pPage, &data[pc]);
38990        testcase( pc+sz==usableSize );
38991        if( pc+sz>usableSize ){
38992          return SQLITE_CORRUPT_BKPT;
38993        }
38994      }
38995      if( !pPage->leaf ) iCellLast++;
38996    }
38997#endif
38998
38999    /* Compute the total free space on the page */
39000    pc = get2byte(&data[hdr+1]);
39001    nFree = data[hdr+7] + top;
39002    while( pc>0 ){
39003      u16 next, size;
39004      if( pc<iCellFirst || pc>iCellLast ){
39005        /* Start of free block is off the page */
39006        return SQLITE_CORRUPT_BKPT;
39007      }
39008      next = get2byte(&data[pc]);
39009      size = get2byte(&data[pc+2]);
39010      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
39011        /* Free blocks must be in ascending order. And the last byte of
39012	** the free-block must lie on the database page.  */
39013        return SQLITE_CORRUPT_BKPT;
39014      }
39015      nFree = nFree + size;
39016      pc = next;
39017    }
39018
39019    /* At this point, nFree contains the sum of the offset to the start
39020    ** of the cell-content area plus the number of free bytes within
39021    ** the cell-content area. If this is greater than the usable-size
39022    ** of the page, then the page must be corrupted. This check also
39023    ** serves to verify that the offset to the start of the cell-content
39024    ** area, according to the page header, lies within the page.
39025    */
39026    if( nFree>usableSize ){
39027      return SQLITE_CORRUPT_BKPT;
39028    }
39029    pPage->nFree = (u16)(nFree - iCellFirst);
39030    pPage->isInit = 1;
39031  }
39032  return SQLITE_OK;
39033}
39034
39035/*
39036** Set up a raw page so that it looks like a database page holding
39037** no entries.
39038*/
39039static void zeroPage(MemPage *pPage, int flags){
39040  unsigned char *data = pPage->aData;
39041  BtShared *pBt = pPage->pBt;
39042  u8 hdr = pPage->hdrOffset;
39043  u16 first;
39044
39045  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
39046  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
39047  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
39048  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39049  assert( sqlite3_mutex_held(pBt->mutex) );
39050#ifdef SQLITE_SECURE_DELETE
39051  memset(&data[hdr], 0, pBt->usableSize - hdr);
39052#endif
39053  data[hdr] = (char)flags;
39054  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
39055  memset(&data[hdr+1], 0, 4);
39056  data[hdr+7] = 0;
39057  put2byte(&data[hdr+5], pBt->usableSize);
39058  pPage->nFree = pBt->usableSize - first;
39059  decodeFlags(pPage, flags);
39060  pPage->hdrOffset = hdr;
39061  pPage->cellOffset = first;
39062  pPage->nOverflow = 0;
39063  assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
39064  pPage->maskPage = pBt->pageSize - 1;
39065  pPage->nCell = 0;
39066  pPage->isInit = 1;
39067}
39068
39069
39070/*
39071** Convert a DbPage obtained from the pager into a MemPage used by
39072** the btree layer.
39073*/
39074static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
39075  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
39076  pPage->aData = sqlite3PagerGetData(pDbPage);
39077  pPage->pDbPage = pDbPage;
39078  pPage->pBt = pBt;
39079  pPage->pgno = pgno;
39080  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
39081  return pPage;
39082}
39083
39084/*
39085** Get a page from the pager.  Initialize the MemPage.pBt and
39086** MemPage.aData elements if needed.
39087**
39088** If the noContent flag is set, it means that we do not care about
39089** the content of the page at this time.  So do not go to the disk
39090** to fetch the content.  Just fill in the content with zeros for now.
39091** If in the future we call sqlite3PagerWrite() on this page, that
39092** means we have started to be concerned about content and the disk
39093** read should occur at that point.
39094*/
39095static int btreeGetPage(
39096  BtShared *pBt,       /* The btree */
39097  Pgno pgno,           /* Number of the page to fetch */
39098  MemPage **ppPage,    /* Return the page in this parameter */
39099  int noContent        /* Do not load page content if true */
39100){
39101  int rc;
39102  DbPage *pDbPage;
39103
39104  assert( sqlite3_mutex_held(pBt->mutex) );
39105  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
39106  if( rc ) return rc;
39107  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
39108  return SQLITE_OK;
39109}
39110
39111/*
39112** Retrieve a page from the pager cache. If the requested page is not
39113** already in the pager cache return NULL. Initialize the MemPage.pBt and
39114** MemPage.aData elements if needed.
39115*/
39116static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
39117  DbPage *pDbPage;
39118  assert( sqlite3_mutex_held(pBt->mutex) );
39119  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
39120  if( pDbPage ){
39121    return btreePageFromDbPage(pDbPage, pgno, pBt);
39122  }
39123  return 0;
39124}
39125
39126/*
39127** Return the size of the database file in pages. If there is any kind of
39128** error, return ((unsigned int)-1).
39129*/
39130static Pgno pagerPagecount(BtShared *pBt){
39131  int nPage = -1;
39132  int rc;
39133  assert( pBt->pPage1 );
39134  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
39135  assert( rc==SQLITE_OK || nPage==-1 );
39136  return (Pgno)nPage;
39137}
39138
39139/*
39140** Get a page from the pager and initialize it.  This routine is just a
39141** convenience wrapper around separate calls to btreeGetPage() and
39142** btreeInitPage().
39143**
39144** If an error occurs, then the value *ppPage is set to is undefined. It
39145** may remain unchanged, or it may be set to an invalid value.
39146*/
39147static int getAndInitPage(
39148  BtShared *pBt,          /* The database file */
39149  Pgno pgno,           /* Number of the page to get */
39150  MemPage **ppPage     /* Write the page pointer here */
39151){
39152  int rc;
39153  TESTONLY( Pgno iLastPg = pagerPagecount(pBt); )
39154  assert( sqlite3_mutex_held(pBt->mutex) );
39155
39156  rc = btreeGetPage(pBt, pgno, ppPage, 0);
39157  if( rc==SQLITE_OK ){
39158    rc = btreeInitPage(*ppPage);
39159    if( rc!=SQLITE_OK ){
39160      releasePage(*ppPage);
39161    }
39162  }
39163
39164  /* If the requested page number was either 0 or greater than the page
39165  ** number of the last page in the database, this function should return
39166  ** SQLITE_CORRUPT or some other error (i.e. SQLITE_FULL). Check that this
39167  ** is the case.  */
39168  assert( (pgno>0 && pgno<=iLastPg) || rc!=SQLITE_OK );
39169  testcase( pgno==0 );
39170  testcase( pgno==iLastPg );
39171
39172  return rc;
39173}
39174
39175/*
39176** Release a MemPage.  This should be called once for each prior
39177** call to btreeGetPage.
39178*/
39179static void releasePage(MemPage *pPage){
39180  if( pPage ){
39181    assert( pPage->aData );
39182    assert( pPage->pBt );
39183    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
39184    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
39185    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39186    sqlite3PagerUnref(pPage->pDbPage);
39187  }
39188}
39189
39190/*
39191** During a rollback, when the pager reloads information into the cache
39192** so that the cache is restored to its original state at the start of
39193** the transaction, for each page restored this routine is called.
39194**
39195** This routine needs to reset the extra data section at the end of the
39196** page to agree with the restored data.
39197*/
39198static void pageReinit(DbPage *pData){
39199  MemPage *pPage;
39200  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
39201  assert( sqlite3PagerPageRefcount(pData)>0 );
39202  if( pPage->isInit ){
39203    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39204    pPage->isInit = 0;
39205    if( sqlite3PagerPageRefcount(pData)>1 ){
39206      /* pPage might not be a btree page;  it might be an overflow page
39207      ** or ptrmap page or a free page.  In those cases, the following
39208      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
39209      ** But no harm is done by this.  And it is very important that
39210      ** btreeInitPage() be called on every btree page so we make
39211      ** the call for every page that comes in for re-initing. */
39212      btreeInitPage(pPage);
39213    }
39214  }
39215}
39216
39217/*
39218** Invoke the busy handler for a btree.
39219*/
39220static int btreeInvokeBusyHandler(void *pArg){
39221  BtShared *pBt = (BtShared*)pArg;
39222  assert( pBt->db );
39223  assert( sqlite3_mutex_held(pBt->db->mutex) );
39224  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
39225}
39226
39227/*
39228** Open a database file.
39229**
39230** zFilename is the name of the database file.  If zFilename is NULL
39231** a new database with a random name is created.  This randomly named
39232** database file will be deleted when sqlite3BtreeClose() is called.
39233** If zFilename is ":memory:" then an in-memory database is created
39234** that is automatically destroyed when it is closed.
39235**
39236** If the database is already opened in the same database connection
39237** and we are in shared cache mode, then the open will fail with an
39238** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
39239** objects in the same database connection since doing so will lead
39240** to problems with locking.
39241*/
39242SQLITE_PRIVATE int sqlite3BtreeOpen(
39243  const char *zFilename,  /* Name of the file containing the BTree database */
39244  sqlite3 *db,            /* Associated database handle */
39245  Btree **ppBtree,        /* Pointer to new Btree object written here */
39246  int flags,              /* Options */
39247  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
39248){
39249  sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
39250  BtShared *pBt = 0;             /* Shared part of btree structure */
39251  Btree *p;                      /* Handle to return */
39252  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
39253  int rc = SQLITE_OK;            /* Result code from this function */
39254  u8 nReserve;                   /* Byte of unused space on each page */
39255  unsigned char zDbHeader[100];  /* Database header content */
39256
39257  /* Set the variable isMemdb to true for an in-memory database, or
39258  ** false for a file-based database. This symbol is only required if
39259  ** either of the shared-data or autovacuum features are compiled
39260  ** into the library.
39261  */
39262#if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
39263  #ifdef SQLITE_OMIT_MEMORYDB
39264    const int isMemdb = 0;
39265  #else
39266    const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
39267  #endif
39268#endif
39269
39270  assert( db!=0 );
39271  assert( sqlite3_mutex_held(db->mutex) );
39272
39273  pVfs = db->pVfs;
39274  p = sqlite3MallocZero(sizeof(Btree));
39275  if( !p ){
39276    return SQLITE_NOMEM;
39277  }
39278  p->inTrans = TRANS_NONE;
39279  p->db = db;
39280#ifndef SQLITE_OMIT_SHARED_CACHE
39281  p->lock.pBtree = p;
39282  p->lock.iTable = 1;
39283#endif
39284
39285#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39286  /*
39287  ** If this Btree is a candidate for shared cache, try to find an
39288  ** existing BtShared object that we can share with
39289  */
39290  if( isMemdb==0 && zFilename && zFilename[0] ){
39291    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
39292      int nFullPathname = pVfs->mxPathname+1;
39293      char *zFullPathname = sqlite3Malloc(nFullPathname);
39294      sqlite3_mutex *mutexShared;
39295      p->sharable = 1;
39296      if( !zFullPathname ){
39297        sqlite3_free(p);
39298        return SQLITE_NOMEM;
39299      }
39300      sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
39301      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
39302      sqlite3_mutex_enter(mutexOpen);
39303      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39304      sqlite3_mutex_enter(mutexShared);
39305      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
39306        assert( pBt->nRef>0 );
39307        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
39308                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
39309          int iDb;
39310          for(iDb=db->nDb-1; iDb>=0; iDb--){
39311            Btree *pExisting = db->aDb[iDb].pBt;
39312            if( pExisting && pExisting->pBt==pBt ){
39313              sqlite3_mutex_leave(mutexShared);
39314              sqlite3_mutex_leave(mutexOpen);
39315              sqlite3_free(zFullPathname);
39316              sqlite3_free(p);
39317              return SQLITE_CONSTRAINT;
39318            }
39319          }
39320          p->pBt = pBt;
39321          pBt->nRef++;
39322          break;
39323        }
39324      }
39325      sqlite3_mutex_leave(mutexShared);
39326      sqlite3_free(zFullPathname);
39327    }
39328#ifdef SQLITE_DEBUG
39329    else{
39330      /* In debug mode, we mark all persistent databases as sharable
39331      ** even when they are not.  This exercises the locking code and
39332      ** gives more opportunity for asserts(sqlite3_mutex_held())
39333      ** statements to find locking problems.
39334      */
39335      p->sharable = 1;
39336    }
39337#endif
39338  }
39339#endif
39340  if( pBt==0 ){
39341    /*
39342    ** The following asserts make sure that structures used by the btree are
39343    ** the right size.  This is to guard against size changes that result
39344    ** when compiling on a different architecture.
39345    */
39346    assert( sizeof(i64)==8 || sizeof(i64)==4 );
39347    assert( sizeof(u64)==8 || sizeof(u64)==4 );
39348    assert( sizeof(u32)==4 );
39349    assert( sizeof(u16)==2 );
39350    assert( sizeof(Pgno)==4 );
39351
39352    pBt = sqlite3MallocZero( sizeof(*pBt) );
39353    if( pBt==0 ){
39354      rc = SQLITE_NOMEM;
39355      goto btree_open_out;
39356    }
39357    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
39358                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
39359    if( rc==SQLITE_OK ){
39360      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
39361    }
39362    if( rc!=SQLITE_OK ){
39363      goto btree_open_out;
39364    }
39365    pBt->db = db;
39366    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
39367    p->pBt = pBt;
39368
39369    pBt->pCursor = 0;
39370    pBt->pPage1 = 0;
39371    pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
39372    pBt->pageSize = get2byte(&zDbHeader[16]);
39373    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
39374         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
39375      pBt->pageSize = 0;
39376#ifndef SQLITE_OMIT_AUTOVACUUM
39377      /* If the magic name ":memory:" will create an in-memory database, then
39378      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
39379      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
39380      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
39381      ** regular file-name. In this case the auto-vacuum applies as per normal.
39382      */
39383      if( zFilename && !isMemdb ){
39384        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
39385        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
39386      }
39387#endif
39388      nReserve = 0;
39389    }else{
39390      nReserve = zDbHeader[20];
39391      pBt->pageSizeFixed = 1;
39392#ifndef SQLITE_OMIT_AUTOVACUUM
39393      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
39394      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
39395#endif
39396    }
39397    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
39398    if( rc ) goto btree_open_out;
39399    pBt->usableSize = pBt->pageSize - nReserve;
39400    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
39401
39402#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39403    /* Add the new BtShared object to the linked list sharable BtShareds.
39404    */
39405    if( p->sharable ){
39406      sqlite3_mutex *mutexShared;
39407      pBt->nRef = 1;
39408      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39409      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
39410        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
39411        if( pBt->mutex==0 ){
39412          rc = SQLITE_NOMEM;
39413          db->mallocFailed = 0;
39414          goto btree_open_out;
39415        }
39416      }
39417      sqlite3_mutex_enter(mutexShared);
39418      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
39419      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
39420      sqlite3_mutex_leave(mutexShared);
39421    }
39422#endif
39423  }
39424
39425#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
39426  /* If the new Btree uses a sharable pBtShared, then link the new
39427  ** Btree into the list of all sharable Btrees for the same connection.
39428  ** The list is kept in ascending order by pBt address.
39429  */
39430  if( p->sharable ){
39431    int i;
39432    Btree *pSib;
39433    for(i=0; i<db->nDb; i++){
39434      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
39435        while( pSib->pPrev ){ pSib = pSib->pPrev; }
39436        if( p->pBt<pSib->pBt ){
39437          p->pNext = pSib;
39438          p->pPrev = 0;
39439          pSib->pPrev = p;
39440        }else{
39441          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
39442            pSib = pSib->pNext;
39443          }
39444          p->pNext = pSib->pNext;
39445          p->pPrev = pSib;
39446          if( p->pNext ){
39447            p->pNext->pPrev = p;
39448          }
39449          pSib->pNext = p;
39450        }
39451        break;
39452      }
39453    }
39454  }
39455#endif
39456  *ppBtree = p;
39457
39458btree_open_out:
39459  if( rc!=SQLITE_OK ){
39460    if( pBt && pBt->pPager ){
39461      sqlite3PagerClose(pBt->pPager);
39462    }
39463    sqlite3_free(pBt);
39464    sqlite3_free(p);
39465    *ppBtree = 0;
39466  }
39467  if( mutexOpen ){
39468    assert( sqlite3_mutex_held(mutexOpen) );
39469    sqlite3_mutex_leave(mutexOpen);
39470  }
39471  return rc;
39472}
39473
39474/*
39475** Decrement the BtShared.nRef counter.  When it reaches zero,
39476** remove the BtShared structure from the sharing list.  Return
39477** true if the BtShared.nRef counter reaches zero and return
39478** false if it is still positive.
39479*/
39480static int removeFromSharingList(BtShared *pBt){
39481#ifndef SQLITE_OMIT_SHARED_CACHE
39482  sqlite3_mutex *pMaster;
39483  BtShared *pList;
39484  int removed = 0;
39485
39486  assert( sqlite3_mutex_notheld(pBt->mutex) );
39487  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
39488  sqlite3_mutex_enter(pMaster);
39489  pBt->nRef--;
39490  if( pBt->nRef<=0 ){
39491    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
39492      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
39493    }else{
39494      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
39495      while( ALWAYS(pList) && pList->pNext!=pBt ){
39496        pList=pList->pNext;
39497      }
39498      if( ALWAYS(pList) ){
39499        pList->pNext = pBt->pNext;
39500      }
39501    }
39502    if( SQLITE_THREADSAFE ){
39503      sqlite3_mutex_free(pBt->mutex);
39504    }
39505    removed = 1;
39506  }
39507  sqlite3_mutex_leave(pMaster);
39508  return removed;
39509#else
39510  return 1;
39511#endif
39512}
39513
39514/*
39515** Make sure pBt->pTmpSpace points to an allocation of
39516** MX_CELL_SIZE(pBt) bytes.
39517*/
39518static void allocateTempSpace(BtShared *pBt){
39519  if( !pBt->pTmpSpace ){
39520    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
39521  }
39522}
39523
39524/*
39525** Free the pBt->pTmpSpace allocation
39526*/
39527static void freeTempSpace(BtShared *pBt){
39528  sqlite3PageFree( pBt->pTmpSpace);
39529  pBt->pTmpSpace = 0;
39530}
39531
39532/*
39533** Close an open database and invalidate all cursors.
39534*/
39535SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
39536  BtShared *pBt = p->pBt;
39537  BtCursor *pCur;
39538
39539  /* Close all cursors opened via this handle.  */
39540  assert( sqlite3_mutex_held(p->db->mutex) );
39541  sqlite3BtreeEnter(p);
39542  pCur = pBt->pCursor;
39543  while( pCur ){
39544    BtCursor *pTmp = pCur;
39545    pCur = pCur->pNext;
39546    if( pTmp->pBtree==p ){
39547      sqlite3BtreeCloseCursor(pTmp);
39548    }
39549  }
39550
39551  /* Rollback any active transaction and free the handle structure.
39552  ** The call to sqlite3BtreeRollback() drops any table-locks held by
39553  ** this handle.
39554  */
39555  sqlite3BtreeRollback(p);
39556  sqlite3BtreeLeave(p);
39557
39558  /* If there are still other outstanding references to the shared-btree
39559  ** structure, return now. The remainder of this procedure cleans
39560  ** up the shared-btree.
39561  */
39562  assert( p->wantToLock==0 && p->locked==0 );
39563  if( !p->sharable || removeFromSharingList(pBt) ){
39564    /* The pBt is no longer on the sharing list, so we can access
39565    ** it without having to hold the mutex.
39566    **
39567    ** Clean out and delete the BtShared object.
39568    */
39569    assert( !pBt->pCursor );
39570    sqlite3PagerClose(pBt->pPager);
39571    if( pBt->xFreeSchema && pBt->pSchema ){
39572      pBt->xFreeSchema(pBt->pSchema);
39573    }
39574    sqlite3_free(pBt->pSchema);
39575    freeTempSpace(pBt);
39576    sqlite3_free(pBt);
39577  }
39578
39579#ifndef SQLITE_OMIT_SHARED_CACHE
39580  assert( p->wantToLock==0 );
39581  assert( p->locked==0 );
39582  if( p->pPrev ) p->pPrev->pNext = p->pNext;
39583  if( p->pNext ) p->pNext->pPrev = p->pPrev;
39584#endif
39585
39586  sqlite3_free(p);
39587  return SQLITE_OK;
39588}
39589
39590/*
39591** Change the limit on the number of pages allowed in the cache.
39592**
39593** The maximum number of cache pages is set to the absolute
39594** value of mxPage.  If mxPage is negative, the pager will
39595** operate asynchronously - it will not stop to do fsync()s
39596** to insure data is written to the disk surface before
39597** continuing.  Transactions still work if synchronous is off,
39598** and the database cannot be corrupted if this program
39599** crashes.  But if the operating system crashes or there is
39600** an abrupt power failure when synchronous is off, the database
39601** could be left in an inconsistent and unrecoverable state.
39602** Synchronous is on by default so database corruption is not
39603** normally a worry.
39604*/
39605SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
39606  BtShared *pBt = p->pBt;
39607  assert( sqlite3_mutex_held(p->db->mutex) );
39608  sqlite3BtreeEnter(p);
39609  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
39610  sqlite3BtreeLeave(p);
39611  return SQLITE_OK;
39612}
39613
39614/*
39615** Change the way data is synced to disk in order to increase or decrease
39616** how well the database resists damage due to OS crashes and power
39617** failures.  Level 1 is the same as asynchronous (no syncs() occur and
39618** there is a high probability of damage)  Level 2 is the default.  There
39619** is a very low but non-zero probability of damage.  Level 3 reduces the
39620** probability of damage to near zero but with a write performance reduction.
39621*/
39622#ifndef SQLITE_OMIT_PAGER_PRAGMAS
39623SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
39624  BtShared *pBt = p->pBt;
39625  assert( sqlite3_mutex_held(p->db->mutex) );
39626  sqlite3BtreeEnter(p);
39627  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
39628  sqlite3BtreeLeave(p);
39629  return SQLITE_OK;
39630}
39631#endif
39632
39633/*
39634** Return TRUE if the given btree is set to safety level 1.  In other
39635** words, return TRUE if no sync() occurs on the disk files.
39636*/
39637SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
39638  BtShared *pBt = p->pBt;
39639  int rc;
39640  assert( sqlite3_mutex_held(p->db->mutex) );
39641  sqlite3BtreeEnter(p);
39642  assert( pBt && pBt->pPager );
39643  rc = sqlite3PagerNosync(pBt->pPager);
39644  sqlite3BtreeLeave(p);
39645  return rc;
39646}
39647
39648#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
39649/*
39650** Change the default pages size and the number of reserved bytes per page.
39651** Or, if the page size has already been fixed, return SQLITE_READONLY
39652** without changing anything.
39653**
39654** The page size must be a power of 2 between 512 and 65536.  If the page
39655** size supplied does not meet this constraint then the page size is not
39656** changed.
39657**
39658** Page sizes are constrained to be a power of two so that the region
39659** of the database file used for locking (beginning at PENDING_BYTE,
39660** the first byte past the 1GB boundary, 0x40000000) needs to occur
39661** at the beginning of a page.
39662**
39663** If parameter nReserve is less than zero, then the number of reserved
39664** bytes per page is left unchanged.
39665**
39666** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
39667** and autovacuum mode can no longer be changed.
39668*/
39669SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
39670  int rc = SQLITE_OK;
39671  BtShared *pBt = p->pBt;
39672  assert( nReserve>=-1 && nReserve<=255 );
39673  sqlite3BtreeEnter(p);
39674  if( pBt->pageSizeFixed ){
39675    sqlite3BtreeLeave(p);
39676    return SQLITE_READONLY;
39677  }
39678  if( nReserve<0 ){
39679    nReserve = pBt->pageSize - pBt->usableSize;
39680  }
39681  assert( nReserve>=0 && nReserve<=255 );
39682  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
39683        ((pageSize-1)&pageSize)==0 ){
39684    assert( (pageSize & 7)==0 );
39685    assert( !pBt->pPage1 && !pBt->pCursor );
39686    pBt->pageSize = (u16)pageSize;
39687    freeTempSpace(pBt);
39688  }
39689  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
39690  pBt->usableSize = pBt->pageSize - (u16)nReserve;
39691  if( iFix ) pBt->pageSizeFixed = 1;
39692  sqlite3BtreeLeave(p);
39693  return rc;
39694}
39695
39696/*
39697** Return the currently defined page size
39698*/
39699SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
39700  return p->pBt->pageSize;
39701}
39702
39703/*
39704** Return the number of bytes of space at the end of every page that
39705** are intentually left unused.  This is the "reserved" space that is
39706** sometimes used by extensions.
39707*/
39708SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
39709  int n;
39710  sqlite3BtreeEnter(p);
39711  n = p->pBt->pageSize - p->pBt->usableSize;
39712  sqlite3BtreeLeave(p);
39713  return n;
39714}
39715
39716/*
39717** Set the maximum page count for a database if mxPage is positive.
39718** No changes are made if mxPage is 0 or negative.
39719** Regardless of the value of mxPage, return the maximum page count.
39720*/
39721SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
39722  int n;
39723  sqlite3BtreeEnter(p);
39724  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
39725  sqlite3BtreeLeave(p);
39726  return n;
39727}
39728#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
39729
39730/*
39731** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
39732** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
39733** is disabled. The default value for the auto-vacuum property is
39734** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
39735*/
39736SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
39737#ifdef SQLITE_OMIT_AUTOVACUUM
39738  return SQLITE_READONLY;
39739#else
39740  BtShared *pBt = p->pBt;
39741  int rc = SQLITE_OK;
39742  u8 av = (u8)autoVacuum;
39743
39744  sqlite3BtreeEnter(p);
39745  if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
39746    rc = SQLITE_READONLY;
39747  }else{
39748    pBt->autoVacuum = av ?1:0;
39749    pBt->incrVacuum = av==2 ?1:0;
39750  }
39751  sqlite3BtreeLeave(p);
39752  return rc;
39753#endif
39754}
39755
39756/*
39757** Return the value of the 'auto-vacuum' property. If auto-vacuum is
39758** enabled 1 is returned. Otherwise 0.
39759*/
39760SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
39761#ifdef SQLITE_OMIT_AUTOVACUUM
39762  return BTREE_AUTOVACUUM_NONE;
39763#else
39764  int rc;
39765  sqlite3BtreeEnter(p);
39766  rc = (
39767    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
39768    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
39769    BTREE_AUTOVACUUM_INCR
39770  );
39771  sqlite3BtreeLeave(p);
39772  return rc;
39773#endif
39774}
39775
39776
39777/*
39778** Get a reference to pPage1 of the database file.  This will
39779** also acquire a readlock on that file.
39780**
39781** SQLITE_OK is returned on success.  If the file is not a
39782** well-formed database file, then SQLITE_CORRUPT is returned.
39783** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
39784** is returned if we run out of memory.
39785*/
39786static int lockBtree(BtShared *pBt){
39787  int rc;
39788  MemPage *pPage1;
39789  int nPage;
39790
39791  assert( sqlite3_mutex_held(pBt->mutex) );
39792  assert( pBt->pPage1==0 );
39793  rc = sqlite3PagerSharedLock(pBt->pPager);
39794  if( rc!=SQLITE_OK ) return rc;
39795  rc = btreeGetPage(pBt, 1, &pPage1, 0);
39796  if( rc!=SQLITE_OK ) return rc;
39797
39798  /* Do some checking to help insure the file we opened really is
39799  ** a valid database file.
39800  */
39801  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
39802  if( rc!=SQLITE_OK ){
39803    goto page1_init_failed;
39804  }else if( nPage>0 ){
39805    int pageSize;
39806    int usableSize;
39807    u8 *page1 = pPage1->aData;
39808    rc = SQLITE_NOTADB;
39809    if( memcmp(page1, zMagicHeader, 16)!=0 ){
39810      goto page1_init_failed;
39811    }
39812    if( page1[18]>1 ){
39813      pBt->readOnly = 1;
39814    }
39815    if( page1[19]>1 ){
39816      goto page1_init_failed;
39817    }
39818
39819    /* The maximum embedded fraction must be exactly 25%.  And the minimum
39820    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
39821    ** The original design allowed these amounts to vary, but as of
39822    ** version 3.6.0, we require them to be fixed.
39823    */
39824    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
39825      goto page1_init_failed;
39826    }
39827    pageSize = get2byte(&page1[16]);
39828    if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
39829        (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
39830    ){
39831      goto page1_init_failed;
39832    }
39833    assert( (pageSize & 7)==0 );
39834    usableSize = pageSize - page1[20];
39835    if( pageSize!=pBt->pageSize ){
39836      /* After reading the first page of the database assuming a page size
39837      ** of BtShared.pageSize, we have discovered that the page-size is
39838      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
39839      ** zero and return SQLITE_OK. The caller will call this function
39840      ** again with the correct page-size.
39841      */
39842      releasePage(pPage1);
39843      pBt->usableSize = (u16)usableSize;
39844      pBt->pageSize = (u16)pageSize;
39845      freeTempSpace(pBt);
39846      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
39847                                   pageSize-usableSize);
39848      return rc;
39849    }
39850    if( usableSize<480 ){
39851      goto page1_init_failed;
39852    }
39853    pBt->pageSize = (u16)pageSize;
39854    pBt->usableSize = (u16)usableSize;
39855#ifndef SQLITE_OMIT_AUTOVACUUM
39856    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
39857    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
39858#endif
39859  }
39860
39861  /* maxLocal is the maximum amount of payload to store locally for
39862  ** a cell.  Make sure it is small enough so that at least minFanout
39863  ** cells can will fit on one page.  We assume a 10-byte page header.
39864  ** Besides the payload, the cell must store:
39865  **     2-byte pointer to the cell
39866  **     4-byte child pointer
39867  **     9-byte nKey value
39868  **     4-byte nData value
39869  **     4-byte overflow page pointer
39870  ** So a cell consists of a 2-byte poiner, a header which is as much as
39871  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
39872  ** page pointer.
39873  */
39874  pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
39875  pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
39876  pBt->maxLeaf = pBt->usableSize - 35;
39877  pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
39878  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
39879  pBt->pPage1 = pPage1;
39880  return SQLITE_OK;
39881
39882page1_init_failed:
39883  releasePage(pPage1);
39884  pBt->pPage1 = 0;
39885  return rc;
39886}
39887
39888/*
39889** If there are no outstanding cursors and we are not in the middle
39890** of a transaction but there is a read lock on the database, then
39891** this routine unrefs the first page of the database file which
39892** has the effect of releasing the read lock.
39893**
39894** If there is a transaction in progress, this routine is a no-op.
39895*/
39896static void unlockBtreeIfUnused(BtShared *pBt){
39897  assert( sqlite3_mutex_held(pBt->mutex) );
39898  assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
39899  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
39900    assert( pBt->pPage1->aData );
39901    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
39902    assert( pBt->pPage1->aData );
39903    releasePage(pBt->pPage1);
39904    pBt->pPage1 = 0;
39905  }
39906}
39907
39908/*
39909** If pBt points to an empty file then convert that empty file
39910** into a new empty database by initializing the first page of
39911** the database.
39912*/
39913static int newDatabase(BtShared *pBt){
39914  MemPage *pP1;
39915  unsigned char *data;
39916  int rc;
39917  int nPage;
39918
39919  assert( sqlite3_mutex_held(pBt->mutex) );
39920  rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
39921  if( rc!=SQLITE_OK || nPage>0 ){
39922    return rc;
39923  }
39924  pP1 = pBt->pPage1;
39925  assert( pP1!=0 );
39926  data = pP1->aData;
39927  rc = sqlite3PagerWrite(pP1->pDbPage);
39928  if( rc ) return rc;
39929  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
39930  assert( sizeof(zMagicHeader)==16 );
39931  put2byte(&data[16], pBt->pageSize);
39932  data[18] = 1;
39933  data[19] = 1;
39934  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
39935  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
39936  data[21] = 64;
39937  data[22] = 32;
39938  data[23] = 32;
39939  memset(&data[24], 0, 100-24);
39940  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
39941  pBt->pageSizeFixed = 1;
39942#ifndef SQLITE_OMIT_AUTOVACUUM
39943  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
39944  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
39945  put4byte(&data[36 + 4*4], pBt->autoVacuum);
39946  put4byte(&data[36 + 7*4], pBt->incrVacuum);
39947#endif
39948  return SQLITE_OK;
39949}
39950
39951/*
39952** Attempt to start a new transaction. A write-transaction
39953** is started if the second argument is nonzero, otherwise a read-
39954** transaction.  If the second argument is 2 or more and exclusive
39955** transaction is started, meaning that no other process is allowed
39956** to access the database.  A preexisting transaction may not be
39957** upgraded to exclusive by calling this routine a second time - the
39958** exclusivity flag only works for a new transaction.
39959**
39960** A write-transaction must be started before attempting any
39961** changes to the database.  None of the following routines
39962** will work unless a transaction is started first:
39963**
39964**      sqlite3BtreeCreateTable()
39965**      sqlite3BtreeCreateIndex()
39966**      sqlite3BtreeClearTable()
39967**      sqlite3BtreeDropTable()
39968**      sqlite3BtreeInsert()
39969**      sqlite3BtreeDelete()
39970**      sqlite3BtreeUpdateMeta()
39971**
39972** If an initial attempt to acquire the lock fails because of lock contention
39973** and the database was previously unlocked, then invoke the busy handler
39974** if there is one.  But if there was previously a read-lock, do not
39975** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
39976** returned when there is already a read-lock in order to avoid a deadlock.
39977**
39978** Suppose there are two processes A and B.  A has a read lock and B has
39979** a reserved lock.  B tries to promote to exclusive but is blocked because
39980** of A's read lock.  A tries to promote to reserved but is blocked by B.
39981** One or the other of the two processes must give way or there can be
39982** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
39983** when A already has a read lock, we encourage A to give up and let B
39984** proceed.
39985*/
39986SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
39987  sqlite3 *pBlock = 0;
39988  BtShared *pBt = p->pBt;
39989  int rc = SQLITE_OK;
39990
39991  sqlite3BtreeEnter(p);
39992  btreeIntegrity(p);
39993
39994  /* If the btree is already in a write-transaction, or it
39995  ** is already in a read-transaction and a read-transaction
39996  ** is requested, this is a no-op.
39997  */
39998  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
39999    goto trans_begun;
40000  }
40001
40002  /* Write transactions are not possible on a read-only database */
40003  if( pBt->readOnly && wrflag ){
40004    rc = SQLITE_READONLY;
40005    goto trans_begun;
40006  }
40007
40008#ifndef SQLITE_OMIT_SHARED_CACHE
40009  /* If another database handle has already opened a write transaction
40010  ** on this shared-btree structure and a second write transaction is
40011  ** requested, return SQLITE_LOCKED.
40012  */
40013  if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
40014    pBlock = pBt->pWriter->db;
40015  }else if( wrflag>1 ){
40016    BtLock *pIter;
40017    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
40018      if( pIter->pBtree!=p ){
40019        pBlock = pIter->pBtree->db;
40020        break;
40021      }
40022    }
40023  }
40024  if( pBlock ){
40025    sqlite3ConnectionBlocked(p->db, pBlock);
40026    rc = SQLITE_LOCKED_SHAREDCACHE;
40027    goto trans_begun;
40028  }
40029#endif
40030
40031  /* Any read-only or read-write transaction implies a read-lock on
40032  ** page 1. So if some other shared-cache client already has a write-lock
40033  ** on page 1, the transaction cannot be opened. */
40034  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
40035  if( SQLITE_OK!=rc ) goto trans_begun;
40036
40037  do {
40038    /* Call lockBtree() until either pBt->pPage1 is populated or
40039    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
40040    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
40041    ** reading page 1 it discovers that the page-size of the database
40042    ** file is not pBt->pageSize. In this case lockBtree() will update
40043    ** pBt->pageSize to the page-size of the file on disk.
40044    */
40045    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
40046
40047    if( rc==SQLITE_OK && wrflag ){
40048      if( pBt->readOnly ){
40049        rc = SQLITE_READONLY;
40050      }else{
40051        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
40052        if( rc==SQLITE_OK ){
40053          rc = newDatabase(pBt);
40054        }
40055      }
40056    }
40057
40058    if( rc!=SQLITE_OK ){
40059      unlockBtreeIfUnused(pBt);
40060    }
40061  }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
40062          btreeInvokeBusyHandler(pBt) );
40063
40064  if( rc==SQLITE_OK ){
40065    if( p->inTrans==TRANS_NONE ){
40066      pBt->nTransaction++;
40067#ifndef SQLITE_OMIT_SHARED_CACHE
40068      if( p->sharable ){
40069	assert( p->lock.pBtree==p && p->lock.iTable==1 );
40070        p->lock.eLock = READ_LOCK;
40071        p->lock.pNext = pBt->pLock;
40072        pBt->pLock = &p->lock;
40073      }
40074#endif
40075    }
40076    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
40077    if( p->inTrans>pBt->inTransaction ){
40078      pBt->inTransaction = p->inTrans;
40079    }
40080#ifndef SQLITE_OMIT_SHARED_CACHE
40081    if( wrflag ){
40082      assert( !pBt->pWriter );
40083      pBt->pWriter = p;
40084      pBt->isExclusive = (u8)(wrflag>1);
40085    }
40086#endif
40087  }
40088
40089
40090trans_begun:
40091  if( rc==SQLITE_OK && wrflag ){
40092    /* This call makes sure that the pager has the correct number of
40093    ** open savepoints. If the second parameter is greater than 0 and
40094    ** the sub-journal is not already open, then it will be opened here.
40095    */
40096    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
40097  }
40098
40099  btreeIntegrity(p);
40100  sqlite3BtreeLeave(p);
40101  return rc;
40102}
40103
40104#ifndef SQLITE_OMIT_AUTOVACUUM
40105
40106/*
40107** Set the pointer-map entries for all children of page pPage. Also, if
40108** pPage contains cells that point to overflow pages, set the pointer
40109** map entries for the overflow pages as well.
40110*/
40111static int setChildPtrmaps(MemPage *pPage){
40112  int i;                             /* Counter variable */
40113  int nCell;                         /* Number of cells in page pPage */
40114  int rc;                            /* Return code */
40115  BtShared *pBt = pPage->pBt;
40116  u8 isInitOrig = pPage->isInit;
40117  Pgno pgno = pPage->pgno;
40118
40119  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
40120  rc = btreeInitPage(pPage);
40121  if( rc!=SQLITE_OK ){
40122    goto set_child_ptrmaps_out;
40123  }
40124  nCell = pPage->nCell;
40125
40126  for(i=0; i<nCell; i++){
40127    u8 *pCell = findCell(pPage, i);
40128
40129    ptrmapPutOvflPtr(pPage, pCell, &rc);
40130
40131    if( !pPage->leaf ){
40132      Pgno childPgno = get4byte(pCell);
40133      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
40134    }
40135  }
40136
40137  if( !pPage->leaf ){
40138    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
40139    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
40140  }
40141
40142set_child_ptrmaps_out:
40143  pPage->isInit = isInitOrig;
40144  return rc;
40145}
40146
40147/*
40148** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
40149** that it points to iTo. Parameter eType describes the type of pointer to
40150** be modified, as  follows:
40151**
40152** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
40153**                   page of pPage.
40154**
40155** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
40156**                   page pointed to by one of the cells on pPage.
40157**
40158** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
40159**                   overflow page in the list.
40160*/
40161static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
40162  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
40163  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
40164  if( eType==PTRMAP_OVERFLOW2 ){
40165    /* The pointer is always the first 4 bytes of the page in this case.  */
40166    if( get4byte(pPage->aData)!=iFrom ){
40167      return SQLITE_CORRUPT_BKPT;
40168    }
40169    put4byte(pPage->aData, iTo);
40170  }else{
40171    u8 isInitOrig = pPage->isInit;
40172    int i;
40173    int nCell;
40174
40175    btreeInitPage(pPage);
40176    nCell = pPage->nCell;
40177
40178    for(i=0; i<nCell; i++){
40179      u8 *pCell = findCell(pPage, i);
40180      if( eType==PTRMAP_OVERFLOW1 ){
40181        CellInfo info;
40182        btreeParseCellPtr(pPage, pCell, &info);
40183        if( info.iOverflow ){
40184          if( iFrom==get4byte(&pCell[info.iOverflow]) ){
40185            put4byte(&pCell[info.iOverflow], iTo);
40186            break;
40187          }
40188        }
40189      }else{
40190        if( get4byte(pCell)==iFrom ){
40191          put4byte(pCell, iTo);
40192          break;
40193        }
40194      }
40195    }
40196
40197    if( i==nCell ){
40198      if( eType!=PTRMAP_BTREE ||
40199          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
40200        return SQLITE_CORRUPT_BKPT;
40201      }
40202      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
40203    }
40204
40205    pPage->isInit = isInitOrig;
40206  }
40207  return SQLITE_OK;
40208}
40209
40210
40211/*
40212** Move the open database page pDbPage to location iFreePage in the
40213** database. The pDbPage reference remains valid.
40214**
40215** The isCommit flag indicates that there is no need to remember that
40216** the journal needs to be sync()ed before database page pDbPage->pgno
40217** can be written to. The caller has already promised not to write to that
40218** page.
40219*/
40220static int relocatePage(
40221  BtShared *pBt,           /* Btree */
40222  MemPage *pDbPage,        /* Open page to move */
40223  u8 eType,                /* Pointer map 'type' entry for pDbPage */
40224  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
40225  Pgno iFreePage,          /* The location to move pDbPage to */
40226  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
40227){
40228  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
40229  Pgno iDbPage = pDbPage->pgno;
40230  Pager *pPager = pBt->pPager;
40231  int rc;
40232
40233  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
40234      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
40235  assert( sqlite3_mutex_held(pBt->mutex) );
40236  assert( pDbPage->pBt==pBt );
40237
40238  /* Move page iDbPage from its current location to page number iFreePage */
40239  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
40240      iDbPage, iFreePage, iPtrPage, eType));
40241  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
40242  if( rc!=SQLITE_OK ){
40243    return rc;
40244  }
40245  pDbPage->pgno = iFreePage;
40246
40247  /* If pDbPage was a btree-page, then it may have child pages and/or cells
40248  ** that point to overflow pages. The pointer map entries for all these
40249  ** pages need to be changed.
40250  **
40251  ** If pDbPage is an overflow page, then the first 4 bytes may store a
40252  ** pointer to a subsequent overflow page. If this is the case, then
40253  ** the pointer map needs to be updated for the subsequent overflow page.
40254  */
40255  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
40256    rc = setChildPtrmaps(pDbPage);
40257    if( rc!=SQLITE_OK ){
40258      return rc;
40259    }
40260  }else{
40261    Pgno nextOvfl = get4byte(pDbPage->aData);
40262    if( nextOvfl!=0 ){
40263      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
40264      if( rc!=SQLITE_OK ){
40265        return rc;
40266      }
40267    }
40268  }
40269
40270  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
40271  ** that it points at iFreePage. Also fix the pointer map entry for
40272  ** iPtrPage.
40273  */
40274  if( eType!=PTRMAP_ROOTPAGE ){
40275    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
40276    if( rc!=SQLITE_OK ){
40277      return rc;
40278    }
40279    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
40280    if( rc!=SQLITE_OK ){
40281      releasePage(pPtrPage);
40282      return rc;
40283    }
40284    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
40285    releasePage(pPtrPage);
40286    if( rc==SQLITE_OK ){
40287      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
40288    }
40289  }
40290  return rc;
40291}
40292
40293/* Forward declaration required by incrVacuumStep(). */
40294static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
40295
40296/*
40297** Perform a single step of an incremental-vacuum. If successful,
40298** return SQLITE_OK. If there is no work to do (and therefore no
40299** point in calling this function again), return SQLITE_DONE.
40300**
40301** More specificly, this function attempts to re-organize the
40302** database so that the last page of the file currently in use
40303** is no longer in use.
40304**
40305** If the nFin parameter is non-zero, this function assumes
40306** that the caller will keep calling incrVacuumStep() until
40307** it returns SQLITE_DONE or an error, and that nFin is the
40308** number of pages the database file will contain after this
40309** process is complete.  If nFin is zero, it is assumed that
40310** incrVacuumStep() will be called a finite amount of times
40311** which may or may not empty the freelist.  A full autovacuum
40312** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
40313*/
40314static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
40315  Pgno nFreeList;           /* Number of pages still on the free-list */
40316
40317  assert( sqlite3_mutex_held(pBt->mutex) );
40318  assert( iLastPg>nFin );
40319
40320  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
40321    int rc;
40322    u8 eType;
40323    Pgno iPtrPage;
40324
40325    nFreeList = get4byte(&pBt->pPage1->aData[36]);
40326    if( nFreeList==0 ){
40327      return SQLITE_DONE;
40328    }
40329
40330    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
40331    if( rc!=SQLITE_OK ){
40332      return rc;
40333    }
40334    if( eType==PTRMAP_ROOTPAGE ){
40335      return SQLITE_CORRUPT_BKPT;
40336    }
40337
40338    if( eType==PTRMAP_FREEPAGE ){
40339      if( nFin==0 ){
40340        /* Remove the page from the files free-list. This is not required
40341        ** if nFin is non-zero. In that case, the free-list will be
40342        ** truncated to zero after this function returns, so it doesn't
40343        ** matter if it still contains some garbage entries.
40344        */
40345        Pgno iFreePg;
40346        MemPage *pFreePg;
40347        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
40348        if( rc!=SQLITE_OK ){
40349          return rc;
40350        }
40351        assert( iFreePg==iLastPg );
40352        releasePage(pFreePg);
40353      }
40354    } else {
40355      Pgno iFreePg;             /* Index of free page to move pLastPg to */
40356      MemPage *pLastPg;
40357
40358      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
40359      if( rc!=SQLITE_OK ){
40360        return rc;
40361      }
40362
40363      /* If nFin is zero, this loop runs exactly once and page pLastPg
40364      ** is swapped with the first free page pulled off the free list.
40365      **
40366      ** On the other hand, if nFin is greater than zero, then keep
40367      ** looping until a free-page located within the first nFin pages
40368      ** of the file is found.
40369      */
40370      do {
40371        MemPage *pFreePg;
40372        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
40373        if( rc!=SQLITE_OK ){
40374          releasePage(pLastPg);
40375          return rc;
40376        }
40377        releasePage(pFreePg);
40378      }while( nFin!=0 && iFreePg>nFin );
40379      assert( iFreePg<iLastPg );
40380
40381      rc = sqlite3PagerWrite(pLastPg->pDbPage);
40382      if( rc==SQLITE_OK ){
40383        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
40384      }
40385      releasePage(pLastPg);
40386      if( rc!=SQLITE_OK ){
40387        return rc;
40388      }
40389    }
40390  }
40391
40392  if( nFin==0 ){
40393    iLastPg--;
40394    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
40395      if( PTRMAP_ISPAGE(pBt, iLastPg) ){
40396        MemPage *pPg;
40397        int rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
40398        if( rc!=SQLITE_OK ){
40399          return rc;
40400        }
40401        rc = sqlite3PagerWrite(pPg->pDbPage);
40402        releasePage(pPg);
40403        if( rc!=SQLITE_OK ){
40404          return rc;
40405        }
40406      }
40407      iLastPg--;
40408    }
40409    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
40410  }
40411  return SQLITE_OK;
40412}
40413
40414/*
40415** A write-transaction must be opened before calling this function.
40416** It performs a single unit of work towards an incremental vacuum.
40417**
40418** If the incremental vacuum is finished after this function has run,
40419** SQLITE_DONE is returned. If it is not finished, but no error occurred,
40420** SQLITE_OK is returned. Otherwise an SQLite error code.
40421*/
40422SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
40423  int rc;
40424  BtShared *pBt = p->pBt;
40425
40426  sqlite3BtreeEnter(p);
40427  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
40428  if( !pBt->autoVacuum ){
40429    rc = SQLITE_DONE;
40430  }else{
40431    invalidateAllOverflowCache(pBt);
40432    rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
40433  }
40434  sqlite3BtreeLeave(p);
40435  return rc;
40436}
40437
40438/*
40439** This routine is called prior to sqlite3PagerCommit when a transaction
40440** is commited for an auto-vacuum database.
40441**
40442** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
40443** the database file should be truncated to during the commit process.
40444** i.e. the database has been reorganized so that only the first *pnTrunc
40445** pages are in use.
40446*/
40447static int autoVacuumCommit(BtShared *pBt){
40448  int rc = SQLITE_OK;
40449  Pager *pPager = pBt->pPager;
40450  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
40451
40452  assert( sqlite3_mutex_held(pBt->mutex) );
40453  invalidateAllOverflowCache(pBt);
40454  assert(pBt->autoVacuum);
40455  if( !pBt->incrVacuum ){
40456    Pgno nFin;         /* Number of pages in database after autovacuuming */
40457    Pgno nFree;        /* Number of pages on the freelist initially */
40458    Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
40459    Pgno iFree;        /* The next page to be freed */
40460    int nEntry;        /* Number of entries on one ptrmap page */
40461    Pgno nOrig;        /* Database size before freeing */
40462
40463    nOrig = pagerPagecount(pBt);
40464    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
40465      /* It is not possible to create a database for which the final page
40466      ** is either a pointer-map page or the pending-byte page. If one
40467      ** is encountered, this indicates corruption.
40468      */
40469      return SQLITE_CORRUPT_BKPT;
40470    }
40471
40472    nFree = get4byte(&pBt->pPage1->aData[36]);
40473    nEntry = pBt->usableSize/5;
40474    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
40475    nFin = nOrig - nFree - nPtrmap;
40476    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
40477      nFin--;
40478    }
40479    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
40480      nFin--;
40481    }
40482    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
40483
40484    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
40485      rc = incrVacuumStep(pBt, nFin, iFree);
40486    }
40487    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
40488      rc = SQLITE_OK;
40489      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
40490      put4byte(&pBt->pPage1->aData[32], 0);
40491      put4byte(&pBt->pPage1->aData[36], 0);
40492      sqlite3PagerTruncateImage(pBt->pPager, nFin);
40493    }
40494    if( rc!=SQLITE_OK ){
40495      sqlite3PagerRollback(pPager);
40496    }
40497  }
40498
40499  assert( nRef==sqlite3PagerRefcount(pPager) );
40500  return rc;
40501}
40502
40503#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
40504# define setChildPtrmaps(x) SQLITE_OK
40505#endif
40506
40507/*
40508** This routine does the first phase of a two-phase commit.  This routine
40509** causes a rollback journal to be created (if it does not already exist)
40510** and populated with enough information so that if a power loss occurs
40511** the database can be restored to its original state by playing back
40512** the journal.  Then the contents of the journal are flushed out to
40513** the disk.  After the journal is safely on oxide, the changes to the
40514** database are written into the database file and flushed to oxide.
40515** At the end of this call, the rollback journal still exists on the
40516** disk and we are still holding all locks, so the transaction has not
40517** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
40518** commit process.
40519**
40520** This call is a no-op if no write-transaction is currently active on pBt.
40521**
40522** Otherwise, sync the database file for the btree pBt. zMaster points to
40523** the name of a master journal file that should be written into the
40524** individual journal file, or is NULL, indicating no master journal file
40525** (single database transaction).
40526**
40527** When this is called, the master journal should already have been
40528** created, populated with this journal pointer and synced to disk.
40529**
40530** Once this is routine has returned, the only thing required to commit
40531** the write-transaction for this database file is to delete the journal.
40532*/
40533SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
40534  int rc = SQLITE_OK;
40535  if( p->inTrans==TRANS_WRITE ){
40536    BtShared *pBt = p->pBt;
40537    sqlite3BtreeEnter(p);
40538#ifndef SQLITE_OMIT_AUTOVACUUM
40539    if( pBt->autoVacuum ){
40540      rc = autoVacuumCommit(pBt);
40541      if( rc!=SQLITE_OK ){
40542        sqlite3BtreeLeave(p);
40543        return rc;
40544      }
40545    }
40546#endif
40547    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
40548    sqlite3BtreeLeave(p);
40549  }
40550  return rc;
40551}
40552
40553/*
40554** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
40555** at the conclusion of a transaction.
40556*/
40557static void btreeEndTransaction(Btree *p){
40558  BtShared *pBt = p->pBt;
40559  assert( sqlite3BtreeHoldsMutex(p) );
40560
40561  btreeClearHasContent(pBt);
40562  if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
40563    /* If there are other active statements that belong to this database
40564    ** handle, downgrade to a read-only transaction. The other statements
40565    ** may still be reading from the database.  */
40566    downgradeAllSharedCacheTableLocks(p);
40567    p->inTrans = TRANS_READ;
40568  }else{
40569    /* If the handle had any kind of transaction open, decrement the
40570    ** transaction count of the shared btree. If the transaction count
40571    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
40572    ** call below will unlock the pager.  */
40573    if( p->inTrans!=TRANS_NONE ){
40574      clearAllSharedCacheTableLocks(p);
40575      pBt->nTransaction--;
40576      if( 0==pBt->nTransaction ){
40577        pBt->inTransaction = TRANS_NONE;
40578      }
40579    }
40580
40581    /* Set the current transaction state to TRANS_NONE and unlock the
40582    ** pager if this call closed the only read or write transaction.  */
40583    p->inTrans = TRANS_NONE;
40584    unlockBtreeIfUnused(pBt);
40585  }
40586
40587  btreeIntegrity(p);
40588}
40589
40590/*
40591** Commit the transaction currently in progress.
40592**
40593** This routine implements the second phase of a 2-phase commit.  The
40594** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
40595** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
40596** routine did all the work of writing information out to disk and flushing the
40597** contents so that they are written onto the disk platter.  All this
40598** routine has to do is delete or truncate or zero the header in the
40599** the rollback journal (which causes the transaction to commit) and
40600** drop locks.
40601**
40602** This will release the write lock on the database file.  If there
40603** are no active cursors, it also releases the read lock.
40604*/
40605SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
40606  BtShared *pBt = p->pBt;
40607
40608  sqlite3BtreeEnter(p);
40609  btreeIntegrity(p);
40610
40611  /* If the handle has a write-transaction open, commit the shared-btrees
40612  ** transaction and set the shared state to TRANS_READ.
40613  */
40614  if( p->inTrans==TRANS_WRITE ){
40615    int rc;
40616    assert( pBt->inTransaction==TRANS_WRITE );
40617    assert( pBt->nTransaction>0 );
40618    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
40619    if( rc!=SQLITE_OK ){
40620      sqlite3BtreeLeave(p);
40621      return rc;
40622    }
40623    pBt->inTransaction = TRANS_READ;
40624  }
40625
40626  btreeEndTransaction(p);
40627  sqlite3BtreeLeave(p);
40628  return SQLITE_OK;
40629}
40630
40631/*
40632** Do both phases of a commit.
40633*/
40634SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
40635  int rc;
40636  sqlite3BtreeEnter(p);
40637  rc = sqlite3BtreeCommitPhaseOne(p, 0);
40638  if( rc==SQLITE_OK ){
40639    rc = sqlite3BtreeCommitPhaseTwo(p);
40640  }
40641  sqlite3BtreeLeave(p);
40642  return rc;
40643}
40644
40645#ifndef NDEBUG
40646/*
40647** Return the number of write-cursors open on this handle. This is for use
40648** in assert() expressions, so it is only compiled if NDEBUG is not
40649** defined.
40650**
40651** For the purposes of this routine, a write-cursor is any cursor that
40652** is capable of writing to the databse.  That means the cursor was
40653** originally opened for writing and the cursor has not be disabled
40654** by having its state changed to CURSOR_FAULT.
40655*/
40656static int countWriteCursors(BtShared *pBt){
40657  BtCursor *pCur;
40658  int r = 0;
40659  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
40660    if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
40661  }
40662  return r;
40663}
40664#endif
40665
40666/*
40667** This routine sets the state to CURSOR_FAULT and the error
40668** code to errCode for every cursor on BtShared that pBtree
40669** references.
40670**
40671** Every cursor is tripped, including cursors that belong
40672** to other database connections that happen to be sharing
40673** the cache with pBtree.
40674**
40675** This routine gets called when a rollback occurs.
40676** All cursors using the same cache must be tripped
40677** to prevent them from trying to use the btree after
40678** the rollback.  The rollback may have deleted tables
40679** or moved root pages, so it is not sufficient to
40680** save the state of the cursor.  The cursor must be
40681** invalidated.
40682*/
40683SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
40684  BtCursor *p;
40685  sqlite3BtreeEnter(pBtree);
40686  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
40687    int i;
40688    sqlite3BtreeClearCursor(p);
40689    p->eState = CURSOR_FAULT;
40690    p->skipNext = errCode;
40691    for(i=0; i<=p->iPage; i++){
40692      releasePage(p->apPage[i]);
40693      p->apPage[i] = 0;
40694    }
40695  }
40696  sqlite3BtreeLeave(pBtree);
40697}
40698
40699/*
40700** Rollback the transaction in progress.  All cursors will be
40701** invalided by this operation.  Any attempt to use a cursor
40702** that was open at the beginning of this operation will result
40703** in an error.
40704**
40705** This will release the write lock on the database file.  If there
40706** are no active cursors, it also releases the read lock.
40707*/
40708SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
40709  int rc;
40710  BtShared *pBt = p->pBt;
40711  MemPage *pPage1;
40712
40713  sqlite3BtreeEnter(p);
40714  rc = saveAllCursors(pBt, 0, 0);
40715#ifndef SQLITE_OMIT_SHARED_CACHE
40716  if( rc!=SQLITE_OK ){
40717    /* This is a horrible situation. An IO or malloc() error occurred whilst
40718    ** trying to save cursor positions. If this is an automatic rollback (as
40719    ** the result of a constraint, malloc() failure or IO error) then
40720    ** the cache may be internally inconsistent (not contain valid trees) so
40721    ** we cannot simply return the error to the caller. Instead, abort
40722    ** all queries that may be using any of the cursors that failed to save.
40723    */
40724    sqlite3BtreeTripAllCursors(p, rc);
40725  }
40726#endif
40727  btreeIntegrity(p);
40728
40729  if( p->inTrans==TRANS_WRITE ){
40730    int rc2;
40731
40732    assert( TRANS_WRITE==pBt->inTransaction );
40733    rc2 = sqlite3PagerRollback(pBt->pPager);
40734    if( rc2!=SQLITE_OK ){
40735      rc = rc2;
40736    }
40737
40738    /* The rollback may have destroyed the pPage1->aData value.  So
40739    ** call btreeGetPage() on page 1 again to make
40740    ** sure pPage1->aData is set correctly. */
40741    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
40742      releasePage(pPage1);
40743    }
40744    assert( countWriteCursors(pBt)==0 );
40745    pBt->inTransaction = TRANS_READ;
40746  }
40747
40748  btreeEndTransaction(p);
40749  sqlite3BtreeLeave(p);
40750  return rc;
40751}
40752
40753/*
40754** Start a statement subtransaction. The subtransaction can can be rolled
40755** back independently of the main transaction. You must start a transaction
40756** before starting a subtransaction. The subtransaction is ended automatically
40757** if the main transaction commits or rolls back.
40758**
40759** Statement subtransactions are used around individual SQL statements
40760** that are contained within a BEGIN...COMMIT block.  If a constraint
40761** error occurs within the statement, the effect of that one statement
40762** can be rolled back without having to rollback the entire transaction.
40763**
40764** A statement sub-transaction is implemented as an anonymous savepoint. The
40765** value passed as the second parameter is the total number of savepoints,
40766** including the new anonymous savepoint, open on the B-Tree. i.e. if there
40767** are no active savepoints and no other statement-transactions open,
40768** iStatement is 1. This anonymous savepoint can be released or rolled back
40769** using the sqlite3BtreeSavepoint() function.
40770*/
40771SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
40772  int rc;
40773  BtShared *pBt = p->pBt;
40774  sqlite3BtreeEnter(p);
40775  assert( p->inTrans==TRANS_WRITE );
40776  assert( pBt->readOnly==0 );
40777  assert( iStatement>0 );
40778  assert( iStatement>p->db->nSavepoint );
40779  if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
40780    rc = SQLITE_INTERNAL;
40781  }else{
40782    assert( pBt->inTransaction==TRANS_WRITE );
40783    /* At the pager level, a statement transaction is a savepoint with
40784    ** an index greater than all savepoints created explicitly using
40785    ** SQL statements. It is illegal to open, release or rollback any
40786    ** such savepoints while the statement transaction savepoint is active.
40787    */
40788    rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
40789  }
40790  sqlite3BtreeLeave(p);
40791  return rc;
40792}
40793
40794/*
40795** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
40796** or SAVEPOINT_RELEASE. This function either releases or rolls back the
40797** savepoint identified by parameter iSavepoint, depending on the value
40798** of op.
40799**
40800** Normally, iSavepoint is greater than or equal to zero. However, if op is
40801** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
40802** contents of the entire transaction are rolled back. This is different
40803** from a normal transaction rollback, as no locks are released and the
40804** transaction remains open.
40805*/
40806SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
40807  int rc = SQLITE_OK;
40808  if( p && p->inTrans==TRANS_WRITE ){
40809    BtShared *pBt = p->pBt;
40810    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
40811    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
40812    sqlite3BtreeEnter(p);
40813    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
40814    if( rc==SQLITE_OK ){
40815      rc = newDatabase(pBt);
40816    }
40817    sqlite3BtreeLeave(p);
40818  }
40819  return rc;
40820}
40821
40822/*
40823** Create a new cursor for the BTree whose root is on the page
40824** iTable. If a read-only cursor is requested, it is assumed that
40825** the caller already has at least a read-only transaction open
40826** on the database already. If a write-cursor is requested, then
40827** the caller is assumed to have an open write transaction.
40828**
40829** If wrFlag==0, then the cursor can only be used for reading.
40830** If wrFlag==1, then the cursor can be used for reading or for
40831** writing if other conditions for writing are also met.  These
40832** are the conditions that must be met in order for writing to
40833** be allowed:
40834**
40835** 1:  The cursor must have been opened with wrFlag==1
40836**
40837** 2:  Other database connections that share the same pager cache
40838**     but which are not in the READ_UNCOMMITTED state may not have
40839**     cursors open with wrFlag==0 on the same table.  Otherwise
40840**     the changes made by this write cursor would be visible to
40841**     the read cursors in the other database connection.
40842**
40843** 3:  The database must be writable (not on read-only media)
40844**
40845** 4:  There must be an active transaction.
40846**
40847** No checking is done to make sure that page iTable really is the
40848** root page of a b-tree.  If it is not, then the cursor acquired
40849** will not work correctly.
40850**
40851** It is assumed that the sqlite3BtreeCursorZero() has been called
40852** on pCur to initialize the memory space prior to invoking this routine.
40853*/
40854static int btreeCursor(
40855  Btree *p,                              /* The btree */
40856  int iTable,                            /* Root page of table to open */
40857  int wrFlag,                            /* 1 to write. 0 read-only */
40858  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
40859  BtCursor *pCur                         /* Space for new cursor */
40860){
40861  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
40862
40863  assert( sqlite3BtreeHoldsMutex(p) );
40864  assert( wrFlag==0 || wrFlag==1 );
40865
40866  /* The following assert statements verify that if this is a sharable
40867  ** b-tree database, the connection is holding the required table locks,
40868  ** and that no other connection has any open cursor that conflicts with
40869  ** this lock.  */
40870  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
40871  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
40872
40873  /* Assert that the caller has opened the required transaction. */
40874  assert( p->inTrans>TRANS_NONE );
40875  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
40876  assert( pBt->pPage1 && pBt->pPage1->aData );
40877
40878  if( NEVER(wrFlag && pBt->readOnly) ){
40879    return SQLITE_READONLY;
40880  }
40881  if( iTable==1 && pagerPagecount(pBt)==0 ){
40882    return SQLITE_EMPTY;
40883  }
40884
40885  /* Now that no other errors can occur, finish filling in the BtCursor
40886  ** variables and link the cursor into the BtShared list.  */
40887  pCur->pgnoRoot = (Pgno)iTable;
40888  pCur->iPage = -1;
40889  pCur->pKeyInfo = pKeyInfo;
40890  pCur->pBtree = p;
40891  pCur->pBt = pBt;
40892  pCur->wrFlag = (u8)wrFlag;
40893  pCur->pNext = pBt->pCursor;
40894  if( pCur->pNext ){
40895    pCur->pNext->pPrev = pCur;
40896  }
40897  pBt->pCursor = pCur;
40898  pCur->eState = CURSOR_INVALID;
40899  pCur->cachedRowid = 0;
40900  return SQLITE_OK;
40901}
40902SQLITE_PRIVATE int sqlite3BtreeCursor(
40903  Btree *p,                                   /* The btree */
40904  int iTable,                                 /* Root page of table to open */
40905  int wrFlag,                                 /* 1 to write. 0 read-only */
40906  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
40907  BtCursor *pCur                              /* Write new cursor here */
40908){
40909  int rc;
40910  sqlite3BtreeEnter(p);
40911  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
40912  sqlite3BtreeLeave(p);
40913  return rc;
40914}
40915
40916/*
40917** Return the size of a BtCursor object in bytes.
40918**
40919** This interfaces is needed so that users of cursors can preallocate
40920** sufficient storage to hold a cursor.  The BtCursor object is opaque
40921** to users so they cannot do the sizeof() themselves - they must call
40922** this routine.
40923*/
40924SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
40925  return ROUND8(sizeof(BtCursor));
40926}
40927
40928/*
40929** Initialize memory that will be converted into a BtCursor object.
40930**
40931** The simple approach here would be to memset() the entire object
40932** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
40933** do not need to be zeroed and they are large, so we can save a lot
40934** of run-time by skipping the initialization of those elements.
40935*/
40936SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
40937  memset(p, 0, offsetof(BtCursor, iPage));
40938}
40939
40940/*
40941** Set the cached rowid value of every cursor in the same database file
40942** as pCur and having the same root page number as pCur.  The value is
40943** set to iRowid.
40944**
40945** Only positive rowid values are considered valid for this cache.
40946** The cache is initialized to zero, indicating an invalid cache.
40947** A btree will work fine with zero or negative rowids.  We just cannot
40948** cache zero or negative rowids, which means tables that use zero or
40949** negative rowids might run a little slower.  But in practice, zero
40950** or negative rowids are very uncommon so this should not be a problem.
40951*/
40952SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
40953  BtCursor *p;
40954  for(p=pCur->pBt->pCursor; p; p=p->pNext){
40955    if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
40956  }
40957  assert( pCur->cachedRowid==iRowid );
40958}
40959
40960/*
40961** Return the cached rowid for the given cursor.  A negative or zero
40962** return value indicates that the rowid cache is invalid and should be
40963** ignored.  If the rowid cache has never before been set, then a
40964** zero is returned.
40965*/
40966SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
40967  return pCur->cachedRowid;
40968}
40969
40970/*
40971** Close a cursor.  The read lock on the database file is released
40972** when the last cursor is closed.
40973*/
40974SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
40975  Btree *pBtree = pCur->pBtree;
40976  if( pBtree ){
40977    int i;
40978    BtShared *pBt = pCur->pBt;
40979    sqlite3BtreeEnter(pBtree);
40980    sqlite3BtreeClearCursor(pCur);
40981    if( pCur->pPrev ){
40982      pCur->pPrev->pNext = pCur->pNext;
40983    }else{
40984      pBt->pCursor = pCur->pNext;
40985    }
40986    if( pCur->pNext ){
40987      pCur->pNext->pPrev = pCur->pPrev;
40988    }
40989    for(i=0; i<=pCur->iPage; i++){
40990      releasePage(pCur->apPage[i]);
40991    }
40992    unlockBtreeIfUnused(pBt);
40993    invalidateOverflowCache(pCur);
40994    /* sqlite3_free(pCur); */
40995    sqlite3BtreeLeave(pBtree);
40996  }
40997  return SQLITE_OK;
40998}
40999
41000/*
41001** Make sure the BtCursor* given in the argument has a valid
41002** BtCursor.info structure.  If it is not already valid, call
41003** btreeParseCell() to fill it in.
41004**
41005** BtCursor.info is a cache of the information in the current cell.
41006** Using this cache reduces the number of calls to btreeParseCell().
41007**
41008** 2007-06-25:  There is a bug in some versions of MSVC that cause the
41009** compiler to crash when getCellInfo() is implemented as a macro.
41010** But there is a measureable speed advantage to using the macro on gcc
41011** (when less compiler optimizations like -Os or -O0 are used and the
41012** compiler is not doing agressive inlining.)  So we use a real function
41013** for MSVC and a macro for everything else.  Ticket #2457.
41014*/
41015#ifndef NDEBUG
41016  static void assertCellInfo(BtCursor *pCur){
41017    CellInfo info;
41018    int iPage = pCur->iPage;
41019    memset(&info, 0, sizeof(info));
41020    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
41021    assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
41022  }
41023#else
41024  #define assertCellInfo(x)
41025#endif
41026#ifdef _MSC_VER
41027  /* Use a real function in MSVC to work around bugs in that compiler. */
41028  static void getCellInfo(BtCursor *pCur){
41029    if( pCur->info.nSize==0 ){
41030      int iPage = pCur->iPage;
41031      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
41032      pCur->validNKey = 1;
41033    }else{
41034      assertCellInfo(pCur);
41035    }
41036  }
41037#else /* if not _MSC_VER */
41038  /* Use a macro in all other compilers so that the function is inlined */
41039#define getCellInfo(pCur)                                                      \
41040  if( pCur->info.nSize==0 ){                                                   \
41041    int iPage = pCur->iPage;                                                   \
41042    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
41043    pCur->validNKey = 1;                                                       \
41044  }else{                                                                       \
41045    assertCellInfo(pCur);                                                      \
41046  }
41047#endif /* _MSC_VER */
41048
41049#ifndef NDEBUG  /* The next routine used only within assert() statements */
41050/*
41051** Return true if the given BtCursor is valid.  A valid cursor is one
41052** that is currently pointing to a row in a (non-empty) table.
41053** This is a verification routine is used only within assert() statements.
41054*/
41055SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
41056  return pCur && pCur->eState==CURSOR_VALID;
41057}
41058#endif /* NDEBUG */
41059
41060/*
41061** Set *pSize to the size of the buffer needed to hold the value of
41062** the key for the current entry.  If the cursor is not pointing
41063** to a valid entry, *pSize is set to 0.
41064**
41065** For a table with the INTKEY flag set, this routine returns the key
41066** itself, not the number of bytes in the key.
41067**
41068** The caller must position the cursor prior to invoking this routine.
41069**
41070** This routine cannot fail.  It always returns SQLITE_OK.
41071*/
41072SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
41073  assert( cursorHoldsMutex(pCur) );
41074  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
41075  if( pCur->eState!=CURSOR_VALID ){
41076    *pSize = 0;
41077  }else{
41078    getCellInfo(pCur);
41079    *pSize = pCur->info.nKey;
41080  }
41081  return SQLITE_OK;
41082}
41083
41084/*
41085** Set *pSize to the number of bytes of data in the entry the
41086** cursor currently points to.
41087**
41088** The caller must guarantee that the cursor is pointing to a non-NULL
41089** valid entry.  In other words, the calling procedure must guarantee
41090** that the cursor has Cursor.eState==CURSOR_VALID.
41091**
41092** Failure is not possible.  This function always returns SQLITE_OK.
41093** It might just as well be a procedure (returning void) but we continue
41094** to return an integer result code for historical reasons.
41095*/
41096SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
41097  assert( cursorHoldsMutex(pCur) );
41098  assert( pCur->eState==CURSOR_VALID );
41099  getCellInfo(pCur);
41100  *pSize = pCur->info.nData;
41101  return SQLITE_OK;
41102}
41103
41104/*
41105** Given the page number of an overflow page in the database (parameter
41106** ovfl), this function finds the page number of the next page in the
41107** linked list of overflow pages. If possible, it uses the auto-vacuum
41108** pointer-map data instead of reading the content of page ovfl to do so.
41109**
41110** If an error occurs an SQLite error code is returned. Otherwise:
41111**
41112** The page number of the next overflow page in the linked list is
41113** written to *pPgnoNext. If page ovfl is the last page in its linked
41114** list, *pPgnoNext is set to zero.
41115**
41116** If ppPage is not NULL, and a reference to the MemPage object corresponding
41117** to page number pOvfl was obtained, then *ppPage is set to point to that
41118** reference. It is the responsibility of the caller to call releasePage()
41119** on *ppPage to free the reference. In no reference was obtained (because
41120** the pointer-map was used to obtain the value for *pPgnoNext), then
41121** *ppPage is set to zero.
41122*/
41123static int getOverflowPage(
41124  BtShared *pBt,               /* The database file */
41125  Pgno ovfl,                   /* Current overflow page number */
41126  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
41127  Pgno *pPgnoNext              /* OUT: Next overflow page number */
41128){
41129  Pgno next = 0;
41130  MemPage *pPage = 0;
41131  int rc = SQLITE_OK;
41132
41133  assert( sqlite3_mutex_held(pBt->mutex) );
41134  assert(pPgnoNext);
41135
41136#ifndef SQLITE_OMIT_AUTOVACUUM
41137  /* Try to find the next page in the overflow list using the
41138  ** autovacuum pointer-map pages. Guess that the next page in
41139  ** the overflow list is page number (ovfl+1). If that guess turns
41140  ** out to be wrong, fall back to loading the data of page
41141  ** number ovfl to determine the next page number.
41142  */
41143  if( pBt->autoVacuum ){
41144    Pgno pgno;
41145    Pgno iGuess = ovfl+1;
41146    u8 eType;
41147
41148    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
41149      iGuess++;
41150    }
41151
41152    if( iGuess<=pagerPagecount(pBt) ){
41153      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
41154      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
41155        next = iGuess;
41156        rc = SQLITE_DONE;
41157      }
41158    }
41159  }
41160#endif
41161
41162  assert( next==0 || rc==SQLITE_DONE );
41163  if( rc==SQLITE_OK ){
41164    rc = btreeGetPage(pBt, ovfl, &pPage, 0);
41165    assert( rc==SQLITE_OK || pPage==0 );
41166    if( rc==SQLITE_OK ){
41167      next = get4byte(pPage->aData);
41168    }
41169  }
41170
41171  *pPgnoNext = next;
41172  if( ppPage ){
41173    *ppPage = pPage;
41174  }else{
41175    releasePage(pPage);
41176  }
41177  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
41178}
41179
41180/*
41181** Copy data from a buffer to a page, or from a page to a buffer.
41182**
41183** pPayload is a pointer to data stored on database page pDbPage.
41184** If argument eOp is false, then nByte bytes of data are copied
41185** from pPayload to the buffer pointed at by pBuf. If eOp is true,
41186** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
41187** of data are copied from the buffer pBuf to pPayload.
41188**
41189** SQLITE_OK is returned on success, otherwise an error code.
41190*/
41191static int copyPayload(
41192  void *pPayload,           /* Pointer to page data */
41193  void *pBuf,               /* Pointer to buffer */
41194  int nByte,                /* Number of bytes to copy */
41195  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
41196  DbPage *pDbPage           /* Page containing pPayload */
41197){
41198  if( eOp ){
41199    /* Copy data from buffer to page (a write operation) */
41200    int rc = sqlite3PagerWrite(pDbPage);
41201    if( rc!=SQLITE_OK ){
41202      return rc;
41203    }
41204    memcpy(pPayload, pBuf, nByte);
41205  }else{
41206    /* Copy data from page to buffer (a read operation) */
41207    memcpy(pBuf, pPayload, nByte);
41208  }
41209  return SQLITE_OK;
41210}
41211
41212/*
41213** This function is used to read or overwrite payload information
41214** for the entry that the pCur cursor is pointing to. If the eOp
41215** parameter is 0, this is a read operation (data copied into
41216** buffer pBuf). If it is non-zero, a write (data copied from
41217** buffer pBuf).
41218**
41219** A total of "amt" bytes are read or written beginning at "offset".
41220** Data is read to or from the buffer pBuf.
41221**
41222** The content being read or written might appear on the main page
41223** or be scattered out on multiple overflow pages.
41224**
41225** If the BtCursor.isIncrblobHandle flag is set, and the current
41226** cursor entry uses one or more overflow pages, this function
41227** allocates space for and lazily popluates the overflow page-list
41228** cache array (BtCursor.aOverflow). Subsequent calls use this
41229** cache to make seeking to the supplied offset more efficient.
41230**
41231** Once an overflow page-list cache has been allocated, it may be
41232** invalidated if some other cursor writes to the same table, or if
41233** the cursor is moved to a different row. Additionally, in auto-vacuum
41234** mode, the following events may invalidate an overflow page-list cache.
41235**
41236**   * An incremental vacuum,
41237**   * A commit in auto_vacuum="full" mode,
41238**   * Creating a table (may require moving an overflow page).
41239*/
41240static int accessPayload(
41241  BtCursor *pCur,      /* Cursor pointing to entry to read from */
41242  u32 offset,          /* Begin reading this far into payload */
41243  u32 amt,             /* Read this many bytes */
41244  unsigned char *pBuf, /* Write the bytes into this buffer */
41245  int eOp              /* zero to read. non-zero to write. */
41246){
41247  unsigned char *aPayload;
41248  int rc = SQLITE_OK;
41249  u32 nKey;
41250  int iIdx = 0;
41251  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
41252  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
41253
41254  assert( pPage );
41255  assert( pCur->eState==CURSOR_VALID );
41256  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41257  assert( cursorHoldsMutex(pCur) );
41258
41259  getCellInfo(pCur);
41260  aPayload = pCur->info.pCell + pCur->info.nHeader;
41261  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
41262
41263  if( NEVER(offset+amt > nKey+pCur->info.nData)
41264   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
41265  ){
41266    /* Trying to read or write past the end of the data is an error */
41267    return SQLITE_CORRUPT_BKPT;
41268  }
41269
41270  /* Check if data must be read/written to/from the btree page itself. */
41271  if( offset<pCur->info.nLocal ){
41272    int a = amt;
41273    if( a+offset>pCur->info.nLocal ){
41274      a = pCur->info.nLocal - offset;
41275    }
41276    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
41277    offset = 0;
41278    pBuf += a;
41279    amt -= a;
41280  }else{
41281    offset -= pCur->info.nLocal;
41282  }
41283
41284  if( rc==SQLITE_OK && amt>0 ){
41285    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
41286    Pgno nextPage;
41287
41288    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
41289
41290#ifndef SQLITE_OMIT_INCRBLOB
41291    /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
41292    ** has not been allocated, allocate it now. The array is sized at
41293    ** one entry for each overflow page in the overflow chain. The
41294    ** page number of the first overflow page is stored in aOverflow[0],
41295    ** etc. A value of 0 in the aOverflow[] array means "not yet known"
41296    ** (the cache is lazily populated).
41297    */
41298    if( pCur->isIncrblobHandle && !pCur->aOverflow ){
41299      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
41300      pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
41301      /* nOvfl is always positive.  If it were zero, fetchPayload would have
41302      ** been used instead of this routine. */
41303      if( ALWAYS(nOvfl) && !pCur->aOverflow ){
41304        rc = SQLITE_NOMEM;
41305      }
41306    }
41307
41308    /* If the overflow page-list cache has been allocated and the
41309    ** entry for the first required overflow page is valid, skip
41310    ** directly to it.
41311    */
41312    if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
41313      iIdx = (offset/ovflSize);
41314      nextPage = pCur->aOverflow[iIdx];
41315      offset = (offset%ovflSize);
41316    }
41317#endif
41318
41319    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
41320
41321#ifndef SQLITE_OMIT_INCRBLOB
41322      /* If required, populate the overflow page-list cache. */
41323      if( pCur->aOverflow ){
41324        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
41325        pCur->aOverflow[iIdx] = nextPage;
41326      }
41327#endif
41328
41329      if( offset>=ovflSize ){
41330        /* The only reason to read this page is to obtain the page
41331        ** number for the next page in the overflow chain. The page
41332        ** data is not required. So first try to lookup the overflow
41333        ** page-list cache, if any, then fall back to the getOverflowPage()
41334        ** function.
41335        */
41336#ifndef SQLITE_OMIT_INCRBLOB
41337        if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
41338          nextPage = pCur->aOverflow[iIdx+1];
41339        } else
41340#endif
41341          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
41342        offset -= ovflSize;
41343      }else{
41344        /* Need to read this page properly. It contains some of the
41345        ** range of data that is being read (eOp==0) or written (eOp!=0).
41346        */
41347        DbPage *pDbPage;
41348        int a = amt;
41349        rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
41350        if( rc==SQLITE_OK ){
41351          aPayload = sqlite3PagerGetData(pDbPage);
41352          nextPage = get4byte(aPayload);
41353          if( a + offset > ovflSize ){
41354            a = ovflSize - offset;
41355          }
41356          rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
41357          sqlite3PagerUnref(pDbPage);
41358          offset = 0;
41359          amt -= a;
41360          pBuf += a;
41361        }
41362      }
41363    }
41364  }
41365
41366  if( rc==SQLITE_OK && amt>0 ){
41367    return SQLITE_CORRUPT_BKPT;
41368  }
41369  return rc;
41370}
41371
41372/*
41373** Read part of the key associated with cursor pCur.  Exactly
41374** "amt" bytes will be transfered into pBuf[].  The transfer
41375** begins at "offset".
41376**
41377** The caller must ensure that pCur is pointing to a valid row
41378** in the table.
41379**
41380** Return SQLITE_OK on success or an error code if anything goes
41381** wrong.  An error is returned if "offset+amt" is larger than
41382** the available payload.
41383*/
41384SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
41385  assert( cursorHoldsMutex(pCur) );
41386  assert( pCur->eState==CURSOR_VALID );
41387  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
41388  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
41389  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
41390}
41391
41392/*
41393** Read part of the data associated with cursor pCur.  Exactly
41394** "amt" bytes will be transfered into pBuf[].  The transfer
41395** begins at "offset".
41396**
41397** Return SQLITE_OK on success or an error code if anything goes
41398** wrong.  An error is returned if "offset+amt" is larger than
41399** the available payload.
41400*/
41401SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
41402  int rc;
41403
41404#ifndef SQLITE_OMIT_INCRBLOB
41405  if ( pCur->eState==CURSOR_INVALID ){
41406    return SQLITE_ABORT;
41407  }
41408#endif
41409
41410  assert( cursorHoldsMutex(pCur) );
41411  rc = restoreCursorPosition(pCur);
41412  if( rc==SQLITE_OK ){
41413    assert( pCur->eState==CURSOR_VALID );
41414    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
41415    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
41416    rc = accessPayload(pCur, offset, amt, pBuf, 0);
41417  }
41418  return rc;
41419}
41420
41421/*
41422** Return a pointer to payload information from the entry that the
41423** pCur cursor is pointing to.  The pointer is to the beginning of
41424** the key if skipKey==0 and it points to the beginning of data if
41425** skipKey==1.  The number of bytes of available key/data is written
41426** into *pAmt.  If *pAmt==0, then the value returned will not be
41427** a valid pointer.
41428**
41429** This routine is an optimization.  It is common for the entire key
41430** and data to fit on the local page and for there to be no overflow
41431** pages.  When that is so, this routine can be used to access the
41432** key and data without making a copy.  If the key and/or data spills
41433** onto overflow pages, then accessPayload() must be used to reassemble
41434** the key/data and copy it into a preallocated buffer.
41435**
41436** The pointer returned by this routine looks directly into the cached
41437** page of the database.  The data might change or move the next time
41438** any btree routine is called.
41439*/
41440static const unsigned char *fetchPayload(
41441  BtCursor *pCur,      /* Cursor pointing to entry to read from */
41442  int *pAmt,           /* Write the number of available bytes here */
41443  int skipKey          /* read beginning at data if this is true */
41444){
41445  unsigned char *aPayload;
41446  MemPage *pPage;
41447  u32 nKey;
41448  u32 nLocal;
41449
41450  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
41451  assert( pCur->eState==CURSOR_VALID );
41452  assert( cursorHoldsMutex(pCur) );
41453  pPage = pCur->apPage[pCur->iPage];
41454  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41455  if( NEVER(pCur->info.nSize==0) ){
41456    btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
41457                   &pCur->info);
41458  }
41459  aPayload = pCur->info.pCell;
41460  aPayload += pCur->info.nHeader;
41461  if( pPage->intKey ){
41462    nKey = 0;
41463  }else{
41464    nKey = (int)pCur->info.nKey;
41465  }
41466  if( skipKey ){
41467    aPayload += nKey;
41468    nLocal = pCur->info.nLocal - nKey;
41469  }else{
41470    nLocal = pCur->info.nLocal;
41471    assert( nLocal<=nKey );
41472  }
41473  *pAmt = nLocal;
41474  return aPayload;
41475}
41476
41477
41478/*
41479** For the entry that cursor pCur is point to, return as
41480** many bytes of the key or data as are available on the local
41481** b-tree page.  Write the number of available bytes into *pAmt.
41482**
41483** The pointer returned is ephemeral.  The key/data may move
41484** or be destroyed on the next call to any Btree routine,
41485** including calls from other threads against the same cache.
41486** Hence, a mutex on the BtShared should be held prior to calling
41487** this routine.
41488**
41489** These routines is used to get quick access to key and data
41490** in the common case where no overflow pages are used.
41491*/
41492SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
41493  const void *p = 0;
41494  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41495  assert( cursorHoldsMutex(pCur) );
41496  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
41497    p = (const void*)fetchPayload(pCur, pAmt, 0);
41498  }
41499  return p;
41500}
41501SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
41502  const void *p = 0;
41503  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41504  assert( cursorHoldsMutex(pCur) );
41505  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
41506    p = (const void*)fetchPayload(pCur, pAmt, 1);
41507  }
41508  return p;
41509}
41510
41511
41512/*
41513** Move the cursor down to a new child page.  The newPgno argument is the
41514** page number of the child page to move to.
41515**
41516** This function returns SQLITE_CORRUPT if the page-header flags field of
41517** the new child page does not match the flags field of the parent (i.e.
41518** if an intkey page appears to be the parent of a non-intkey page, or
41519** vice-versa).
41520*/
41521static int moveToChild(BtCursor *pCur, u32 newPgno){
41522  int rc;
41523  int i = pCur->iPage;
41524  MemPage *pNewPage;
41525  BtShared *pBt = pCur->pBt;
41526
41527  assert( cursorHoldsMutex(pCur) );
41528  assert( pCur->eState==CURSOR_VALID );
41529  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
41530  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
41531    return SQLITE_CORRUPT_BKPT;
41532  }
41533  rc = getAndInitPage(pBt, newPgno, &pNewPage);
41534  if( rc ) return rc;
41535  pCur->apPage[i+1] = pNewPage;
41536  pCur->aiIdx[i+1] = 0;
41537  pCur->iPage++;
41538
41539  pCur->info.nSize = 0;
41540  pCur->validNKey = 0;
41541  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
41542    return SQLITE_CORRUPT_BKPT;
41543  }
41544  return SQLITE_OK;
41545}
41546
41547#ifndef NDEBUG
41548/*
41549** Page pParent is an internal (non-leaf) tree page. This function
41550** asserts that page number iChild is the left-child if the iIdx'th
41551** cell in page pParent. Or, if iIdx is equal to the total number of
41552** cells in pParent, that page number iChild is the right-child of
41553** the page.
41554*/
41555static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
41556  assert( iIdx<=pParent->nCell );
41557  if( iIdx==pParent->nCell ){
41558    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
41559  }else{
41560    assert( get4byte(findCell(pParent, iIdx))==iChild );
41561  }
41562}
41563#else
41564#  define assertParentIndex(x,y,z)
41565#endif
41566
41567/*
41568** Move the cursor up to the parent page.
41569**
41570** pCur->idx is set to the cell index that contains the pointer
41571** to the page we are coming from.  If we are coming from the
41572** right-most child page then pCur->idx is set to one more than
41573** the largest cell index.
41574*/
41575static void moveToParent(BtCursor *pCur){
41576  assert( cursorHoldsMutex(pCur) );
41577  assert( pCur->eState==CURSOR_VALID );
41578  assert( pCur->iPage>0 );
41579  assert( pCur->apPage[pCur->iPage] );
41580  assertParentIndex(
41581    pCur->apPage[pCur->iPage-1],
41582    pCur->aiIdx[pCur->iPage-1],
41583    pCur->apPage[pCur->iPage]->pgno
41584  );
41585  releasePage(pCur->apPage[pCur->iPage]);
41586  pCur->iPage--;
41587  pCur->info.nSize = 0;
41588  pCur->validNKey = 0;
41589}
41590
41591/*
41592** Move the cursor to point to the root page of its b-tree structure.
41593**
41594** If the table has a virtual root page, then the cursor is moved to point
41595** to the virtual root page instead of the actual root page. A table has a
41596** virtual root page when the actual root page contains no cells and a
41597** single child page. This can only happen with the table rooted at page 1.
41598**
41599** If the b-tree structure is empty, the cursor state is set to
41600** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
41601** cell located on the root (or virtual root) page and the cursor state
41602** is set to CURSOR_VALID.
41603**
41604** If this function returns successfully, it may be assumed that the
41605** page-header flags indicate that the [virtual] root-page is the expected
41606** kind of b-tree page (i.e. if when opening the cursor the caller did not
41607** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
41608** indicating a table b-tree, or if the caller did specify a KeyInfo
41609** structure the flags byte is set to 0x02 or 0x0A, indicating an index
41610** b-tree).
41611*/
41612static int moveToRoot(BtCursor *pCur){
41613  MemPage *pRoot;
41614  int rc = SQLITE_OK;
41615  Btree *p = pCur->pBtree;
41616  BtShared *pBt = p->pBt;
41617
41618  assert( cursorHoldsMutex(pCur) );
41619  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
41620  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
41621  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
41622  if( pCur->eState>=CURSOR_REQUIRESEEK ){
41623    if( pCur->eState==CURSOR_FAULT ){
41624      assert( pCur->skipNext!=SQLITE_OK );
41625      return pCur->skipNext;
41626    }
41627    sqlite3BtreeClearCursor(pCur);
41628  }
41629
41630  if( pCur->iPage>=0 ){
41631    int i;
41632    for(i=1; i<=pCur->iPage; i++){
41633      releasePage(pCur->apPage[i]);
41634    }
41635    pCur->iPage = 0;
41636  }else{
41637    rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
41638    if( rc!=SQLITE_OK ){
41639      pCur->eState = CURSOR_INVALID;
41640      return rc;
41641    }
41642    pCur->iPage = 0;
41643
41644    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
41645    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
41646    ** NULL, the caller expects a table b-tree. If this is not the case,
41647    ** return an SQLITE_CORRUPT error.  */
41648    assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
41649    if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
41650      return SQLITE_CORRUPT_BKPT;
41651    }
41652  }
41653
41654  /* Assert that the root page is of the correct type. This must be the
41655  ** case as the call to this function that loaded the root-page (either
41656  ** this call or a previous invocation) would have detected corruption
41657  ** if the assumption were not true, and it is not possible for the flags
41658  ** byte to have been modified while this cursor is holding a reference
41659  ** to the page.  */
41660  pRoot = pCur->apPage[0];
41661  assert( pRoot->pgno==pCur->pgnoRoot );
41662  assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
41663
41664  pCur->aiIdx[0] = 0;
41665  pCur->info.nSize = 0;
41666  pCur->atLast = 0;
41667  pCur->validNKey = 0;
41668
41669  if( pRoot->nCell==0 && !pRoot->leaf ){
41670    Pgno subpage;
41671    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
41672    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
41673    pCur->eState = CURSOR_VALID;
41674    rc = moveToChild(pCur, subpage);
41675  }else{
41676    pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
41677  }
41678  return rc;
41679}
41680
41681/*
41682** Move the cursor down to the left-most leaf entry beneath the
41683** entry to which it is currently pointing.
41684**
41685** The left-most leaf is the one with the smallest key - the first
41686** in ascending order.
41687*/
41688static int moveToLeftmost(BtCursor *pCur){
41689  Pgno pgno;
41690  int rc = SQLITE_OK;
41691  MemPage *pPage;
41692
41693  assert( cursorHoldsMutex(pCur) );
41694  assert( pCur->eState==CURSOR_VALID );
41695  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
41696    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
41697    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
41698    rc = moveToChild(pCur, pgno);
41699  }
41700  return rc;
41701}
41702
41703/*
41704** Move the cursor down to the right-most leaf entry beneath the
41705** page to which it is currently pointing.  Notice the difference
41706** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
41707** finds the left-most entry beneath the *entry* whereas moveToRightmost()
41708** finds the right-most entry beneath the *page*.
41709**
41710** The right-most entry is the one with the largest key - the last
41711** key in ascending order.
41712*/
41713static int moveToRightmost(BtCursor *pCur){
41714  Pgno pgno;
41715  int rc = SQLITE_OK;
41716  MemPage *pPage = 0;
41717
41718  assert( cursorHoldsMutex(pCur) );
41719  assert( pCur->eState==CURSOR_VALID );
41720  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
41721    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
41722    pCur->aiIdx[pCur->iPage] = pPage->nCell;
41723    rc = moveToChild(pCur, pgno);
41724  }
41725  if( rc==SQLITE_OK ){
41726    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
41727    pCur->info.nSize = 0;
41728    pCur->validNKey = 0;
41729  }
41730  return rc;
41731}
41732
41733/* Move the cursor to the first entry in the table.  Return SQLITE_OK
41734** on success.  Set *pRes to 0 if the cursor actually points to something
41735** or set *pRes to 1 if the table is empty.
41736*/
41737SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
41738  int rc;
41739
41740  assert( cursorHoldsMutex(pCur) );
41741  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41742  rc = moveToRoot(pCur);
41743  if( rc==SQLITE_OK ){
41744    if( pCur->eState==CURSOR_INVALID ){
41745      assert( pCur->apPage[pCur->iPage]->nCell==0 );
41746      *pRes = 1;
41747      rc = SQLITE_OK;
41748    }else{
41749      assert( pCur->apPage[pCur->iPage]->nCell>0 );
41750      *pRes = 0;
41751      rc = moveToLeftmost(pCur);
41752    }
41753  }
41754  return rc;
41755}
41756
41757/* Move the cursor to the last entry in the table.  Return SQLITE_OK
41758** on success.  Set *pRes to 0 if the cursor actually points to something
41759** or set *pRes to 1 if the table is empty.
41760*/
41761SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
41762  int rc;
41763
41764  assert( cursorHoldsMutex(pCur) );
41765  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41766
41767  /* If the cursor already points to the last entry, this is a no-op. */
41768  if( CURSOR_VALID==pCur->eState && pCur->atLast ){
41769#ifdef SQLITE_DEBUG
41770    /* This block serves to assert() that the cursor really does point
41771    ** to the last entry in the b-tree. */
41772    int ii;
41773    for(ii=0; ii<pCur->iPage; ii++){
41774      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
41775    }
41776    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
41777    assert( pCur->apPage[pCur->iPage]->leaf );
41778#endif
41779    return SQLITE_OK;
41780  }
41781
41782  rc = moveToRoot(pCur);
41783  if( rc==SQLITE_OK ){
41784    if( CURSOR_INVALID==pCur->eState ){
41785      assert( pCur->apPage[pCur->iPage]->nCell==0 );
41786      *pRes = 1;
41787    }else{
41788      assert( pCur->eState==CURSOR_VALID );
41789      *pRes = 0;
41790      rc = moveToRightmost(pCur);
41791      pCur->atLast = rc==SQLITE_OK ?1:0;
41792    }
41793  }
41794  return rc;
41795}
41796
41797/* Move the cursor so that it points to an entry near the key
41798** specified by pIdxKey or intKey.   Return a success code.
41799**
41800** For INTKEY tables, the intKey parameter is used.  pIdxKey
41801** must be NULL.  For index tables, pIdxKey is used and intKey
41802** is ignored.
41803**
41804** If an exact match is not found, then the cursor is always
41805** left pointing at a leaf page which would hold the entry if it
41806** were present.  The cursor might point to an entry that comes
41807** before or after the key.
41808**
41809** An integer is written into *pRes which is the result of
41810** comparing the key with the entry to which the cursor is
41811** pointing.  The meaning of the integer written into
41812** *pRes is as follows:
41813**
41814**     *pRes<0      The cursor is left pointing at an entry that
41815**                  is smaller than intKey/pIdxKey or if the table is empty
41816**                  and the cursor is therefore left point to nothing.
41817**
41818**     *pRes==0     The cursor is left pointing at an entry that
41819**                  exactly matches intKey/pIdxKey.
41820**
41821**     *pRes>0      The cursor is left pointing at an entry that
41822**                  is larger than intKey/pIdxKey.
41823**
41824*/
41825SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
41826  BtCursor *pCur,          /* The cursor to be moved */
41827  UnpackedRecord *pIdxKey, /* Unpacked index key */
41828  i64 intKey,              /* The table key */
41829  int biasRight,           /* If true, bias the search to the high end */
41830  int *pRes                /* Write search results here */
41831){
41832  int rc;
41833
41834  assert( cursorHoldsMutex(pCur) );
41835  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
41836  assert( pRes );
41837  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
41838
41839  /* If the cursor is already positioned at the point we are trying
41840  ** to move to, then just return without doing any work */
41841  if( pCur->eState==CURSOR_VALID && pCur->validNKey
41842   && pCur->apPage[0]->intKey
41843  ){
41844    if( pCur->info.nKey==intKey ){
41845      *pRes = 0;
41846      return SQLITE_OK;
41847    }
41848    if( pCur->atLast && pCur->info.nKey<intKey ){
41849      *pRes = -1;
41850      return SQLITE_OK;
41851    }
41852  }
41853
41854  rc = moveToRoot(pCur);
41855  if( rc ){
41856    return rc;
41857  }
41858  assert( pCur->apPage[pCur->iPage] );
41859  assert( pCur->apPage[pCur->iPage]->isInit );
41860  assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
41861  if( pCur->eState==CURSOR_INVALID ){
41862    *pRes = -1;
41863    assert( pCur->apPage[pCur->iPage]->nCell==0 );
41864    return SQLITE_OK;
41865  }
41866  assert( pCur->apPage[0]->intKey || pIdxKey );
41867  for(;;){
41868    int lwr, upr;
41869    Pgno chldPg;
41870    MemPage *pPage = pCur->apPage[pCur->iPage];
41871    int c;
41872
41873    /* pPage->nCell must be greater than zero. If this is the root-page
41874    ** the cursor would have been INVALID above and this for(;;) loop
41875    ** not run. If this is not the root-page, then the moveToChild() routine
41876    ** would have already detected db corruption. Similarly, pPage must
41877    ** be the right kind (index or table) of b-tree page. Otherwise
41878    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
41879    assert( pPage->nCell>0 );
41880    assert( pPage->intKey==(pIdxKey==0) );
41881    lwr = 0;
41882    upr = pPage->nCell-1;
41883    if( biasRight ){
41884      pCur->aiIdx[pCur->iPage] = (u16)upr;
41885    }else{
41886      pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
41887    }
41888    for(;;){
41889      int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
41890      u8 *pCell;                          /* Pointer to current cell in pPage */
41891
41892      pCur->info.nSize = 0;
41893      pCell = findCell(pPage, idx) + pPage->childPtrSize;
41894      if( pPage->intKey ){
41895        i64 nCellKey;
41896        if( pPage->hasData ){
41897          u32 dummy;
41898          pCell += getVarint32(pCell, dummy);
41899        }
41900        getVarint(pCell, (u64*)&nCellKey);
41901        if( nCellKey==intKey ){
41902          c = 0;
41903        }else if( nCellKey<intKey ){
41904          c = -1;
41905        }else{
41906          assert( nCellKey>intKey );
41907          c = +1;
41908        }
41909        pCur->validNKey = 1;
41910        pCur->info.nKey = nCellKey;
41911      }else{
41912        /* The maximum supported page-size is 32768 bytes. This means that
41913        ** the maximum number of record bytes stored on an index B-Tree
41914        ** page is at most 8198 bytes, which may be stored as a 2-byte
41915        ** varint. This information is used to attempt to avoid parsing
41916        ** the entire cell by checking for the cases where the record is
41917        ** stored entirely within the b-tree page by inspecting the first
41918        ** 2 bytes of the cell.
41919        */
41920        int nCell = pCell[0];
41921        if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
41922          /* This branch runs if the record-size field of the cell is a
41923          ** single byte varint and the record fits entirely on the main
41924          ** b-tree page.  */
41925          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
41926        }else if( !(pCell[1] & 0x80)
41927          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
41928        ){
41929          /* The record-size field is a 2 byte varint and the record
41930          ** fits entirely on the main b-tree page.  */
41931          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
41932        }else{
41933          /* The record flows over onto one or more overflow pages. In
41934          ** this case the whole cell needs to be parsed, a buffer allocated
41935          ** and accessPayload() used to retrieve the record into the
41936          ** buffer before VdbeRecordCompare() can be called. */
41937          void *pCellKey;
41938          u8 * const pCellBody = pCell - pPage->childPtrSize;
41939          btreeParseCellPtr(pPage, pCellBody, &pCur->info);
41940          nCell = (int)pCur->info.nKey;
41941          pCellKey = sqlite3Malloc( nCell );
41942          if( pCellKey==0 ){
41943            rc = SQLITE_NOMEM;
41944            goto moveto_finish;
41945          }
41946          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
41947          if( rc ){
41948            sqlite3_free(pCellKey);
41949            goto moveto_finish;
41950          }
41951          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
41952          sqlite3_free(pCellKey);
41953        }
41954      }
41955      if( c==0 ){
41956        if( pPage->intKey && !pPage->leaf ){
41957          lwr = idx;
41958          upr = lwr - 1;
41959          break;
41960        }else{
41961          *pRes = 0;
41962          rc = SQLITE_OK;
41963          goto moveto_finish;
41964        }
41965      }
41966      if( c<0 ){
41967        lwr = idx+1;
41968      }else{
41969        upr = idx-1;
41970      }
41971      if( lwr>upr ){
41972        break;
41973      }
41974      pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
41975    }
41976    assert( lwr==upr+1 );
41977    assert( pPage->isInit );
41978    if( pPage->leaf ){
41979      chldPg = 0;
41980    }else if( lwr>=pPage->nCell ){
41981      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
41982    }else{
41983      chldPg = get4byte(findCell(pPage, lwr));
41984    }
41985    if( chldPg==0 ){
41986      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
41987      *pRes = c;
41988      rc = SQLITE_OK;
41989      goto moveto_finish;
41990    }
41991    pCur->aiIdx[pCur->iPage] = (u16)lwr;
41992    pCur->info.nSize = 0;
41993    pCur->validNKey = 0;
41994    rc = moveToChild(pCur, chldPg);
41995    if( rc ) goto moveto_finish;
41996  }
41997moveto_finish:
41998  return rc;
41999}
42000
42001
42002/*
42003** Return TRUE if the cursor is not pointing at an entry of the table.
42004**
42005** TRUE will be returned after a call to sqlite3BtreeNext() moves
42006** past the last entry in the table or sqlite3BtreePrev() moves past
42007** the first entry.  TRUE is also returned if the table is empty.
42008*/
42009SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
42010  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
42011  ** have been deleted? This API will need to change to return an error code
42012  ** as well as the boolean result value.
42013  */
42014  return (CURSOR_VALID!=pCur->eState);
42015}
42016
42017/*
42018** Advance the cursor to the next entry in the database.  If
42019** successful then set *pRes=0.  If the cursor
42020** was already pointing to the last entry in the database before
42021** this routine was called, then set *pRes=1.
42022*/
42023SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
42024  int rc;
42025  int idx;
42026  MemPage *pPage;
42027
42028  assert( cursorHoldsMutex(pCur) );
42029  rc = restoreCursorPosition(pCur);
42030  if( rc!=SQLITE_OK ){
42031    return rc;
42032  }
42033  assert( pRes!=0 );
42034  if( CURSOR_INVALID==pCur->eState ){
42035    *pRes = 1;
42036    return SQLITE_OK;
42037  }
42038  if( pCur->skipNext>0 ){
42039    pCur->skipNext = 0;
42040    *pRes = 0;
42041    return SQLITE_OK;
42042  }
42043  pCur->skipNext = 0;
42044
42045  pPage = pCur->apPage[pCur->iPage];
42046  idx = ++pCur->aiIdx[pCur->iPage];
42047  assert( pPage->isInit );
42048  assert( idx<=pPage->nCell );
42049
42050  pCur->info.nSize = 0;
42051  pCur->validNKey = 0;
42052  if( idx>=pPage->nCell ){
42053    if( !pPage->leaf ){
42054      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
42055      if( rc ) return rc;
42056      rc = moveToLeftmost(pCur);
42057      *pRes = 0;
42058      return rc;
42059    }
42060    do{
42061      if( pCur->iPage==0 ){
42062        *pRes = 1;
42063        pCur->eState = CURSOR_INVALID;
42064        return SQLITE_OK;
42065      }
42066      moveToParent(pCur);
42067      pPage = pCur->apPage[pCur->iPage];
42068    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
42069    *pRes = 0;
42070    if( pPage->intKey ){
42071      rc = sqlite3BtreeNext(pCur, pRes);
42072    }else{
42073      rc = SQLITE_OK;
42074    }
42075    return rc;
42076  }
42077  *pRes = 0;
42078  if( pPage->leaf ){
42079    return SQLITE_OK;
42080  }
42081  rc = moveToLeftmost(pCur);
42082  return rc;
42083}
42084
42085
42086/*
42087** Step the cursor to the back to the previous entry in the database.  If
42088** successful then set *pRes=0.  If the cursor
42089** was already pointing to the first entry in the database before
42090** this routine was called, then set *pRes=1.
42091*/
42092SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
42093  int rc;
42094  MemPage *pPage;
42095
42096  assert( cursorHoldsMutex(pCur) );
42097  rc = restoreCursorPosition(pCur);
42098  if( rc!=SQLITE_OK ){
42099    return rc;
42100  }
42101  pCur->atLast = 0;
42102  if( CURSOR_INVALID==pCur->eState ){
42103    *pRes = 1;
42104    return SQLITE_OK;
42105  }
42106  if( pCur->skipNext<0 ){
42107    pCur->skipNext = 0;
42108    *pRes = 0;
42109    return SQLITE_OK;
42110  }
42111  pCur->skipNext = 0;
42112
42113  pPage = pCur->apPage[pCur->iPage];
42114  assert( pPage->isInit );
42115  if( !pPage->leaf ){
42116    int idx = pCur->aiIdx[pCur->iPage];
42117    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
42118    if( rc ){
42119      return rc;
42120    }
42121    rc = moveToRightmost(pCur);
42122  }else{
42123    while( pCur->aiIdx[pCur->iPage]==0 ){
42124      if( pCur->iPage==0 ){
42125        pCur->eState = CURSOR_INVALID;
42126        *pRes = 1;
42127        return SQLITE_OK;
42128      }
42129      moveToParent(pCur);
42130    }
42131    pCur->info.nSize = 0;
42132    pCur->validNKey = 0;
42133
42134    pCur->aiIdx[pCur->iPage]--;
42135    pPage = pCur->apPage[pCur->iPage];
42136    if( pPage->intKey && !pPage->leaf ){
42137      rc = sqlite3BtreePrevious(pCur, pRes);
42138    }else{
42139      rc = SQLITE_OK;
42140    }
42141  }
42142  *pRes = 0;
42143  return rc;
42144}
42145
42146/*
42147** Allocate a new page from the database file.
42148**
42149** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
42150** has already been called on the new page.)  The new page has also
42151** been referenced and the calling routine is responsible for calling
42152** sqlite3PagerUnref() on the new page when it is done.
42153**
42154** SQLITE_OK is returned on success.  Any other return value indicates
42155** an error.  *ppPage and *pPgno are undefined in the event of an error.
42156** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
42157**
42158** If the "nearby" parameter is not 0, then a (feeble) effort is made to
42159** locate a page close to the page number "nearby".  This can be used in an
42160** attempt to keep related pages close to each other in the database file,
42161** which in turn can make database access faster.
42162**
42163** If the "exact" parameter is not 0, and the page-number nearby exists
42164** anywhere on the free-list, then it is guarenteed to be returned. This
42165** is only used by auto-vacuum databases when allocating a new table.
42166*/
42167static int allocateBtreePage(
42168  BtShared *pBt,
42169  MemPage **ppPage,
42170  Pgno *pPgno,
42171  Pgno nearby,
42172  u8 exact
42173){
42174  MemPage *pPage1;
42175  int rc;
42176  u32 n;     /* Number of pages on the freelist */
42177  u32 k;     /* Number of leaves on the trunk of the freelist */
42178  MemPage *pTrunk = 0;
42179  MemPage *pPrevTrunk = 0;
42180  Pgno mxPage;     /* Total size of the database file */
42181
42182  assert( sqlite3_mutex_held(pBt->mutex) );
42183  pPage1 = pBt->pPage1;
42184  mxPage = pagerPagecount(pBt);
42185  n = get4byte(&pPage1->aData[36]);
42186  testcase( n==mxPage-1 );
42187  if( n>=mxPage ){
42188    return SQLITE_CORRUPT_BKPT;
42189  }
42190  if( n>0 ){
42191    /* There are pages on the freelist.  Reuse one of those pages. */
42192    Pgno iTrunk;
42193    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
42194
42195    /* If the 'exact' parameter was true and a query of the pointer-map
42196    ** shows that the page 'nearby' is somewhere on the free-list, then
42197    ** the entire-list will be searched for that page.
42198    */
42199#ifndef SQLITE_OMIT_AUTOVACUUM
42200    if( exact && nearby<=mxPage ){
42201      u8 eType;
42202      assert( nearby>0 );
42203      assert( pBt->autoVacuum );
42204      rc = ptrmapGet(pBt, nearby, &eType, 0);
42205      if( rc ) return rc;
42206      if( eType==PTRMAP_FREEPAGE ){
42207        searchList = 1;
42208      }
42209      *pPgno = nearby;
42210    }
42211#endif
42212
42213    /* Decrement the free-list count by 1. Set iTrunk to the index of the
42214    ** first free-list trunk page. iPrevTrunk is initially 1.
42215    */
42216    rc = sqlite3PagerWrite(pPage1->pDbPage);
42217    if( rc ) return rc;
42218    put4byte(&pPage1->aData[36], n-1);
42219
42220    /* The code within this loop is run only once if the 'searchList' variable
42221    ** is not true. Otherwise, it runs once for each trunk-page on the
42222    ** free-list until the page 'nearby' is located.
42223    */
42224    do {
42225      pPrevTrunk = pTrunk;
42226      if( pPrevTrunk ){
42227        iTrunk = get4byte(&pPrevTrunk->aData[0]);
42228      }else{
42229        iTrunk = get4byte(&pPage1->aData[32]);
42230      }
42231      testcase( iTrunk==mxPage );
42232      if( iTrunk>mxPage ){
42233        rc = SQLITE_CORRUPT_BKPT;
42234      }else{
42235        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
42236      }
42237      if( rc ){
42238        pTrunk = 0;
42239        goto end_allocate_page;
42240      }
42241
42242      k = get4byte(&pTrunk->aData[4]);
42243      if( k==0 && !searchList ){
42244        /* The trunk has no leaves and the list is not being searched.
42245        ** So extract the trunk page itself and use it as the newly
42246        ** allocated page */
42247        assert( pPrevTrunk==0 );
42248        rc = sqlite3PagerWrite(pTrunk->pDbPage);
42249        if( rc ){
42250          goto end_allocate_page;
42251        }
42252        *pPgno = iTrunk;
42253        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
42254        *ppPage = pTrunk;
42255        pTrunk = 0;
42256        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
42257      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
42258        /* Value of k is out of range.  Database corruption */
42259        rc = SQLITE_CORRUPT_BKPT;
42260        goto end_allocate_page;
42261#ifndef SQLITE_OMIT_AUTOVACUUM
42262      }else if( searchList && nearby==iTrunk ){
42263        /* The list is being searched and this trunk page is the page
42264        ** to allocate, regardless of whether it has leaves.
42265        */
42266        assert( *pPgno==iTrunk );
42267        *ppPage = pTrunk;
42268        searchList = 0;
42269        rc = sqlite3PagerWrite(pTrunk->pDbPage);
42270        if( rc ){
42271          goto end_allocate_page;
42272        }
42273        if( k==0 ){
42274          if( !pPrevTrunk ){
42275            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
42276          }else{
42277            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
42278          }
42279        }else{
42280          /* The trunk page is required by the caller but it contains
42281          ** pointers to free-list leaves. The first leaf becomes a trunk
42282          ** page in this case.
42283          */
42284          MemPage *pNewTrunk;
42285          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
42286          if( iNewTrunk>mxPage ){
42287            rc = SQLITE_CORRUPT_BKPT;
42288            goto end_allocate_page;
42289          }
42290          testcase( iNewTrunk==mxPage );
42291          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
42292          if( rc!=SQLITE_OK ){
42293            goto end_allocate_page;
42294          }
42295          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
42296          if( rc!=SQLITE_OK ){
42297            releasePage(pNewTrunk);
42298            goto end_allocate_page;
42299          }
42300          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
42301          put4byte(&pNewTrunk->aData[4], k-1);
42302          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
42303          releasePage(pNewTrunk);
42304          if( !pPrevTrunk ){
42305            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
42306            put4byte(&pPage1->aData[32], iNewTrunk);
42307          }else{
42308            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
42309            if( rc ){
42310              goto end_allocate_page;
42311            }
42312            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
42313          }
42314        }
42315        pTrunk = 0;
42316        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
42317#endif
42318      }else if( k>0 ){
42319        /* Extract a leaf from the trunk */
42320        u32 closest;
42321        Pgno iPage;
42322        unsigned char *aData = pTrunk->aData;
42323        rc = sqlite3PagerWrite(pTrunk->pDbPage);
42324        if( rc ){
42325          goto end_allocate_page;
42326        }
42327        if( nearby>0 ){
42328          u32 i;
42329          int dist;
42330          closest = 0;
42331          dist = get4byte(&aData[8]) - nearby;
42332          if( dist<0 ) dist = -dist;
42333          for(i=1; i<k; i++){
42334            int d2 = get4byte(&aData[8+i*4]) - nearby;
42335            if( d2<0 ) d2 = -d2;
42336            if( d2<dist ){
42337              closest = i;
42338              dist = d2;
42339            }
42340          }
42341        }else{
42342          closest = 0;
42343        }
42344
42345        iPage = get4byte(&aData[8+closest*4]);
42346        testcase( iPage==mxPage );
42347        if( iPage>mxPage ){
42348          rc = SQLITE_CORRUPT_BKPT;
42349          goto end_allocate_page;
42350        }
42351        testcase( iPage==mxPage );
42352        if( !searchList || iPage==nearby ){
42353          int noContent;
42354          *pPgno = iPage;
42355          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
42356                 ": %d more free pages\n",
42357                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
42358          if( closest<k-1 ){
42359            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
42360          }
42361          put4byte(&aData[4], k-1);
42362          assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
42363          noContent = !btreeGetHasContent(pBt, *pPgno);
42364          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
42365          if( rc==SQLITE_OK ){
42366            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
42367            if( rc!=SQLITE_OK ){
42368              releasePage(*ppPage);
42369            }
42370          }
42371          searchList = 0;
42372        }
42373      }
42374      releasePage(pPrevTrunk);
42375      pPrevTrunk = 0;
42376    }while( searchList );
42377  }else{
42378    /* There are no pages on the freelist, so create a new page at the
42379    ** end of the file */
42380    int nPage = pagerPagecount(pBt);
42381    *pPgno = nPage + 1;
42382
42383    if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
42384      (*pPgno)++;
42385    }
42386
42387#ifndef SQLITE_OMIT_AUTOVACUUM
42388    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
42389      /* If *pPgno refers to a pointer-map page, allocate two new pages
42390      ** at the end of the file instead of one. The first allocated page
42391      ** becomes a new pointer-map page, the second is used by the caller.
42392      */
42393      MemPage *pPg = 0;
42394      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
42395      assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42396      rc = btreeGetPage(pBt, *pPgno, &pPg, 0);
42397      if( rc==SQLITE_OK ){
42398        rc = sqlite3PagerWrite(pPg->pDbPage);
42399        releasePage(pPg);
42400      }
42401      if( rc ) return rc;
42402      (*pPgno)++;
42403      if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
42404    }
42405#endif
42406
42407    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42408    rc = btreeGetPage(pBt, *pPgno, ppPage, 0);
42409    if( rc ) return rc;
42410    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
42411    if( rc!=SQLITE_OK ){
42412      releasePage(*ppPage);
42413    }
42414    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
42415  }
42416
42417  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
42418
42419end_allocate_page:
42420  releasePage(pTrunk);
42421  releasePage(pPrevTrunk);
42422  if( rc==SQLITE_OK ){
42423    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
42424      releasePage(*ppPage);
42425      return SQLITE_CORRUPT_BKPT;
42426    }
42427    (*ppPage)->isInit = 0;
42428  }else{
42429    *ppPage = 0;
42430  }
42431  return rc;
42432}
42433
42434/*
42435** This function is used to add page iPage to the database file free-list.
42436** It is assumed that the page is not already a part of the free-list.
42437**
42438** The value passed as the second argument to this function is optional.
42439** If the caller happens to have a pointer to the MemPage object
42440** corresponding to page iPage handy, it may pass it as the second value.
42441** Otherwise, it may pass NULL.
42442**
42443** If a pointer to a MemPage object is passed as the second argument,
42444** its reference count is not altered by this function.
42445*/
42446static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
42447  MemPage *pTrunk = 0;                /* Free-list trunk page */
42448  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
42449  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
42450  MemPage *pPage;                     /* Page being freed. May be NULL. */
42451  int rc;                             /* Return Code */
42452  int nFree;                          /* Initial number of pages on free-list */
42453
42454  assert( sqlite3_mutex_held(pBt->mutex) );
42455  assert( iPage>1 );
42456  assert( !pMemPage || pMemPage->pgno==iPage );
42457
42458  if( pMemPage ){
42459    pPage = pMemPage;
42460    sqlite3PagerRef(pPage->pDbPage);
42461  }else{
42462    pPage = btreePageLookup(pBt, iPage);
42463  }
42464
42465  /* Increment the free page count on pPage1 */
42466  rc = sqlite3PagerWrite(pPage1->pDbPage);
42467  if( rc ) goto freepage_out;
42468  nFree = get4byte(&pPage1->aData[36]);
42469  put4byte(&pPage1->aData[36], nFree+1);
42470
42471#ifdef SQLITE_SECURE_DELETE
42472  /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
42473  ** always fully overwrite deleted information with zeros.
42474  */
42475  if( (!pPage && (rc = btreeGetPage(pBt, iPage, &pPage, 0)))
42476   ||            (rc = sqlite3PagerWrite(pPage->pDbPage))
42477  ){
42478    goto freepage_out;
42479  }
42480  memset(pPage->aData, 0, pPage->pBt->pageSize);
42481#endif
42482
42483  /* If the database supports auto-vacuum, write an entry in the pointer-map
42484  ** to indicate that the page is free.
42485  */
42486  if( ISAUTOVACUUM ){
42487    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
42488    if( rc ) goto freepage_out;
42489  }
42490
42491  /* Now manipulate the actual database free-list structure. There are two
42492  ** possibilities. If the free-list is currently empty, or if the first
42493  ** trunk page in the free-list is full, then this page will become a
42494  ** new free-list trunk page. Otherwise, it will become a leaf of the
42495  ** first trunk page in the current free-list. This block tests if it
42496  ** is possible to add the page as a new free-list leaf.
42497  */
42498  if( nFree!=0 ){
42499    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
42500
42501    iTrunk = get4byte(&pPage1->aData[32]);
42502    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
42503    if( rc!=SQLITE_OK ){
42504      goto freepage_out;
42505    }
42506
42507    nLeaf = get4byte(&pTrunk->aData[4]);
42508    assert( pBt->usableSize>32 );
42509    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
42510      rc = SQLITE_CORRUPT_BKPT;
42511      goto freepage_out;
42512    }
42513    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
42514      /* In this case there is room on the trunk page to insert the page
42515      ** being freed as a new leaf.
42516      **
42517      ** Note that the trunk page is not really full until it contains
42518      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
42519      ** coded.  But due to a coding error in versions of SQLite prior to
42520      ** 3.6.0, databases with freelist trunk pages holding more than
42521      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
42522      ** to maintain backwards compatibility with older versions of SQLite,
42523      ** we will continue to restrict the number of entries to usableSize/4 - 8
42524      ** for now.  At some point in the future (once everyone has upgraded
42525      ** to 3.6.0 or later) we should consider fixing the conditional above
42526      ** to read "usableSize/4-2" instead of "usableSize/4-8".
42527      */
42528      rc = sqlite3PagerWrite(pTrunk->pDbPage);
42529      if( rc==SQLITE_OK ){
42530        put4byte(&pTrunk->aData[4], nLeaf+1);
42531        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
42532#ifndef SQLITE_SECURE_DELETE
42533        if( pPage ){
42534          sqlite3PagerDontWrite(pPage->pDbPage);
42535        }
42536#endif
42537        rc = btreeSetHasContent(pBt, iPage);
42538      }
42539      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
42540      goto freepage_out;
42541    }
42542  }
42543
42544  /* If control flows to this point, then it was not possible to add the
42545  ** the page being freed as a leaf page of the first trunk in the free-list.
42546  ** Possibly because the free-list is empty, or possibly because the
42547  ** first trunk in the free-list is full. Either way, the page being freed
42548  ** will become the new first trunk page in the free-list.
42549  */
42550  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
42551    goto freepage_out;
42552  }
42553  rc = sqlite3PagerWrite(pPage->pDbPage);
42554  if( rc!=SQLITE_OK ){
42555    goto freepage_out;
42556  }
42557  put4byte(pPage->aData, iTrunk);
42558  put4byte(&pPage->aData[4], 0);
42559  put4byte(&pPage1->aData[32], iPage);
42560  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
42561
42562freepage_out:
42563  if( pPage ){
42564    pPage->isInit = 0;
42565  }
42566  releasePage(pPage);
42567  releasePage(pTrunk);
42568  return rc;
42569}
42570static void freePage(MemPage *pPage, int *pRC){
42571  if( (*pRC)==SQLITE_OK ){
42572    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
42573  }
42574}
42575
42576/*
42577** Free any overflow pages associated with the given Cell.
42578*/
42579static int clearCell(MemPage *pPage, unsigned char *pCell){
42580  BtShared *pBt = pPage->pBt;
42581  CellInfo info;
42582  Pgno ovflPgno;
42583  int rc;
42584  int nOvfl;
42585  u16 ovflPageSize;
42586
42587  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42588  btreeParseCellPtr(pPage, pCell, &info);
42589  if( info.iOverflow==0 ){
42590    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
42591  }
42592  ovflPgno = get4byte(&pCell[info.iOverflow]);
42593  assert( pBt->usableSize > 4 );
42594  ovflPageSize = pBt->usableSize - 4;
42595  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
42596  assert( ovflPgno==0 || nOvfl>0 );
42597  while( nOvfl-- ){
42598    Pgno iNext = 0;
42599    MemPage *pOvfl = 0;
42600    if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
42601      /* 0 is not a legal page number and page 1 cannot be an
42602      ** overflow page. Therefore if ovflPgno<2 or past the end of the
42603      ** file the database must be corrupt. */
42604      return SQLITE_CORRUPT_BKPT;
42605    }
42606    if( nOvfl ){
42607      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
42608      if( rc ) return rc;
42609    }
42610    rc = freePage2(pBt, pOvfl, ovflPgno);
42611    if( pOvfl ){
42612      sqlite3PagerUnref(pOvfl->pDbPage);
42613    }
42614    if( rc ) return rc;
42615    ovflPgno = iNext;
42616  }
42617  return SQLITE_OK;
42618}
42619
42620/*
42621** Create the byte sequence used to represent a cell on page pPage
42622** and write that byte sequence into pCell[].  Overflow pages are
42623** allocated and filled in as necessary.  The calling procedure
42624** is responsible for making sure sufficient space has been allocated
42625** for pCell[].
42626**
42627** Note that pCell does not necessary need to point to the pPage->aData
42628** area.  pCell might point to some temporary storage.  The cell will
42629** be constructed in this temporary area then copied into pPage->aData
42630** later.
42631*/
42632static int fillInCell(
42633  MemPage *pPage,                /* The page that contains the cell */
42634  unsigned char *pCell,          /* Complete text of the cell */
42635  const void *pKey, i64 nKey,    /* The key */
42636  const void *pData,int nData,   /* The data */
42637  int nZero,                     /* Extra zero bytes to append to pData */
42638  int *pnSize                    /* Write cell size here */
42639){
42640  int nPayload;
42641  const u8 *pSrc;
42642  int nSrc, n, rc;
42643  int spaceLeft;
42644  MemPage *pOvfl = 0;
42645  MemPage *pToRelease = 0;
42646  unsigned char *pPrior;
42647  unsigned char *pPayload;
42648  BtShared *pBt = pPage->pBt;
42649  Pgno pgnoOvfl = 0;
42650  int nHeader;
42651  CellInfo info;
42652
42653  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42654
42655  /* pPage is not necessarily writeable since pCell might be auxiliary
42656  ** buffer space that is separate from the pPage buffer area */
42657  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
42658            || sqlite3PagerIswriteable(pPage->pDbPage) );
42659
42660  /* Fill in the header. */
42661  nHeader = 0;
42662  if( !pPage->leaf ){
42663    nHeader += 4;
42664  }
42665  if( pPage->hasData ){
42666    nHeader += putVarint(&pCell[nHeader], nData+nZero);
42667  }else{
42668    nData = nZero = 0;
42669  }
42670  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
42671  btreeParseCellPtr(pPage, pCell, &info);
42672  assert( info.nHeader==nHeader );
42673  assert( info.nKey==nKey );
42674  assert( info.nData==(u32)(nData+nZero) );
42675
42676  /* Fill in the payload */
42677  nPayload = nData + nZero;
42678  if( pPage->intKey ){
42679    pSrc = pData;
42680    nSrc = nData;
42681    nData = 0;
42682  }else{
42683    if( NEVER(nKey>0x7fffffff || pKey==0) ){
42684      return SQLITE_CORRUPT_BKPT;
42685    }
42686    nPayload += (int)nKey;
42687    pSrc = pKey;
42688    nSrc = (int)nKey;
42689  }
42690  *pnSize = info.nSize;
42691  spaceLeft = info.nLocal;
42692  pPayload = &pCell[nHeader];
42693  pPrior = &pCell[info.iOverflow];
42694
42695  while( nPayload>0 ){
42696    if( spaceLeft==0 ){
42697#ifndef SQLITE_OMIT_AUTOVACUUM
42698      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
42699      if( pBt->autoVacuum ){
42700        do{
42701          pgnoOvfl++;
42702        } while(
42703          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
42704        );
42705      }
42706#endif
42707      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
42708#ifndef SQLITE_OMIT_AUTOVACUUM
42709      /* If the database supports auto-vacuum, and the second or subsequent
42710      ** overflow page is being allocated, add an entry to the pointer-map
42711      ** for that page now.
42712      **
42713      ** If this is the first overflow page, then write a partial entry
42714      ** to the pointer-map. If we write nothing to this pointer-map slot,
42715      ** then the optimistic overflow chain processing in clearCell()
42716      ** may misinterpret the uninitialised values and delete the
42717      ** wrong pages from the database.
42718      */
42719      if( pBt->autoVacuum && rc==SQLITE_OK ){
42720        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
42721        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
42722        if( rc ){
42723          releasePage(pOvfl);
42724        }
42725      }
42726#endif
42727      if( rc ){
42728        releasePage(pToRelease);
42729        return rc;
42730      }
42731
42732      /* If pToRelease is not zero than pPrior points into the data area
42733      ** of pToRelease.  Make sure pToRelease is still writeable. */
42734      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
42735
42736      /* If pPrior is part of the data area of pPage, then make sure pPage
42737      ** is still writeable */
42738      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
42739            || sqlite3PagerIswriteable(pPage->pDbPage) );
42740
42741      put4byte(pPrior, pgnoOvfl);
42742      releasePage(pToRelease);
42743      pToRelease = pOvfl;
42744      pPrior = pOvfl->aData;
42745      put4byte(pPrior, 0);
42746      pPayload = &pOvfl->aData[4];
42747      spaceLeft = pBt->usableSize - 4;
42748    }
42749    n = nPayload;
42750    if( n>spaceLeft ) n = spaceLeft;
42751
42752    /* If pToRelease is not zero than pPayload points into the data area
42753    ** of pToRelease.  Make sure pToRelease is still writeable. */
42754    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
42755
42756    /* If pPayload is part of the data area of pPage, then make sure pPage
42757    ** is still writeable */
42758    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
42759            || sqlite3PagerIswriteable(pPage->pDbPage) );
42760
42761    if( nSrc>0 ){
42762      if( n>nSrc ) n = nSrc;
42763      assert( pSrc );
42764      memcpy(pPayload, pSrc, n);
42765    }else{
42766      memset(pPayload, 0, n);
42767    }
42768    nPayload -= n;
42769    pPayload += n;
42770    pSrc += n;
42771    nSrc -= n;
42772    spaceLeft -= n;
42773    if( nSrc==0 ){
42774      nSrc = nData;
42775      pSrc = pData;
42776    }
42777  }
42778  releasePage(pToRelease);
42779  return SQLITE_OK;
42780}
42781
42782/*
42783** Remove the i-th cell from pPage.  This routine effects pPage only.
42784** The cell content is not freed or deallocated.  It is assumed that
42785** the cell content has been copied someplace else.  This routine just
42786** removes the reference to the cell from pPage.
42787**
42788** "sz" must be the number of bytes in the cell.
42789*/
42790static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
42791  int i;          /* Loop counter */
42792  int pc;         /* Offset to cell content of cell being deleted */
42793  u8 *data;       /* pPage->aData */
42794  u8 *ptr;        /* Used to move bytes around within data[] */
42795  int rc;         /* The return code */
42796  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
42797
42798  if( *pRC ) return;
42799
42800  assert( idx>=0 && idx<pPage->nCell );
42801  assert( sz==cellSize(pPage, idx) );
42802  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
42803  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42804  data = pPage->aData;
42805  ptr = &data[pPage->cellOffset + 2*idx];
42806  pc = get2byte(ptr);
42807  hdr = pPage->hdrOffset;
42808  testcase( pc==get2byte(&data[hdr+5]) );
42809  testcase( pc+sz==pPage->pBt->usableSize );
42810  if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
42811    *pRC = SQLITE_CORRUPT_BKPT;
42812    return;
42813  }
42814  rc = freeSpace(pPage, pc, sz);
42815  if( rc ){
42816    *pRC = rc;
42817    return;
42818  }
42819  for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
42820    ptr[0] = ptr[2];
42821    ptr[1] = ptr[3];
42822  }
42823  pPage->nCell--;
42824  put2byte(&data[hdr+3], pPage->nCell);
42825  pPage->nFree += 2;
42826}
42827
42828/*
42829** Insert a new cell on pPage at cell index "i".  pCell points to the
42830** content of the cell.
42831**
42832** If the cell content will fit on the page, then put it there.  If it
42833** will not fit, then make a copy of the cell content into pTemp if
42834** pTemp is not null.  Regardless of pTemp, allocate a new entry
42835** in pPage->aOvfl[] and make it point to the cell content (either
42836** in pTemp or the original pCell) and also record its index.
42837** Allocating a new entry in pPage->aCell[] implies that
42838** pPage->nOverflow is incremented.
42839**
42840** If nSkip is non-zero, then do not copy the first nSkip bytes of the
42841** cell. The caller will overwrite them after this function returns. If
42842** nSkip is non-zero, then pCell may not point to an invalid memory location
42843** (but pCell+nSkip is always valid).
42844*/
42845static void insertCell(
42846  MemPage *pPage,   /* Page into which we are copying */
42847  int i,            /* New cell becomes the i-th cell of the page */
42848  u8 *pCell,        /* Content of the new cell */
42849  int sz,           /* Bytes of content in pCell */
42850  u8 *pTemp,        /* Temp storage space for pCell, if needed */
42851  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
42852  int *pRC          /* Read and write return code from here */
42853){
42854  int idx;          /* Where to write new cell content in data[] */
42855  int j;            /* Loop counter */
42856  int end;          /* First byte past the last cell pointer in data[] */
42857  int ins;          /* Index in data[] where new cell pointer is inserted */
42858  int cellOffset;   /* Address of first cell pointer in data[] */
42859  u8 *data;         /* The content of the whole page */
42860  u8 *ptr;          /* Used for moving information around in data[] */
42861
42862  int nSkip = (iChild ? 4 : 0);
42863
42864  if( *pRC ) return;
42865
42866  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
42867  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
42868  assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
42869  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42870  /* The cell should normally be sized correctly.  However, when moving a
42871  ** malformed cell from a leaf page to an interior page, if the cell size
42872  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
42873  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
42874  ** the term after the || in the following assert(). */
42875  assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
42876  if( pPage->nOverflow || sz+2>pPage->nFree ){
42877    if( pTemp ){
42878      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
42879      pCell = pTemp;
42880    }
42881    if( iChild ){
42882      put4byte(pCell, iChild);
42883    }
42884    j = pPage->nOverflow++;
42885    assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
42886    pPage->aOvfl[j].pCell = pCell;
42887    pPage->aOvfl[j].idx = (u16)i;
42888  }else{
42889    int rc = sqlite3PagerWrite(pPage->pDbPage);
42890    if( rc!=SQLITE_OK ){
42891      *pRC = rc;
42892      return;
42893    }
42894    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
42895    data = pPage->aData;
42896    cellOffset = pPage->cellOffset;
42897    end = cellOffset + 2*pPage->nCell;
42898    ins = cellOffset + 2*i;
42899    rc = allocateSpace(pPage, sz, &idx);
42900    if( rc ){ *pRC = rc; return; }
42901    /* The allocateSpace() routine guarantees the following two properties
42902    ** if it returns success */
42903    assert( idx >= end+2 );
42904    assert( idx+sz <= pPage->pBt->usableSize );
42905    pPage->nCell++;
42906    pPage->nFree -= (u16)(2 + sz);
42907    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
42908    if( iChild ){
42909      put4byte(&data[idx], iChild);
42910    }
42911    for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
42912      ptr[0] = ptr[-2];
42913      ptr[1] = ptr[-1];
42914    }
42915    put2byte(&data[ins], idx);
42916    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
42917#ifndef SQLITE_OMIT_AUTOVACUUM
42918    if( pPage->pBt->autoVacuum ){
42919      /* The cell may contain a pointer to an overflow page. If so, write
42920      ** the entry for the overflow page into the pointer map.
42921      */
42922      ptrmapPutOvflPtr(pPage, pCell, pRC);
42923    }
42924#endif
42925  }
42926}
42927
42928/*
42929** Add a list of cells to a page.  The page should be initially empty.
42930** The cells are guaranteed to fit on the page.
42931*/
42932static void assemblePage(
42933  MemPage *pPage,   /* The page to be assemblied */
42934  int nCell,        /* The number of cells to add to this page */
42935  u8 **apCell,      /* Pointers to cell bodies */
42936  u16 *aSize        /* Sizes of the cells */
42937){
42938  int i;            /* Loop counter */
42939  u8 *pCellptr;     /* Address of next cell pointer */
42940  int cellbody;     /* Address of next cell body */
42941  u8 * const data = pPage->aData;             /* Pointer to data for pPage */
42942  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
42943  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
42944
42945  assert( pPage->nOverflow==0 );
42946  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
42947  assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
42948  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
42949
42950  /* Check that the page has just been zeroed by zeroPage() */
42951  assert( pPage->nCell==0 );
42952  assert( get2byte(&data[hdr+5])==nUsable );
42953
42954  pCellptr = &data[pPage->cellOffset + nCell*2];
42955  cellbody = nUsable;
42956  for(i=nCell-1; i>=0; i--){
42957    pCellptr -= 2;
42958    cellbody -= aSize[i];
42959    put2byte(pCellptr, cellbody);
42960    memcpy(&data[cellbody], apCell[i], aSize[i]);
42961  }
42962  put2byte(&data[hdr+3], nCell);
42963  put2byte(&data[hdr+5], cellbody);
42964  pPage->nFree -= (nCell*2 + nUsable - cellbody);
42965  pPage->nCell = (u16)nCell;
42966}
42967
42968/*
42969** The following parameters determine how many adjacent pages get involved
42970** in a balancing operation.  NN is the number of neighbors on either side
42971** of the page that participate in the balancing operation.  NB is the
42972** total number of pages that participate, including the target page and
42973** NN neighbors on either side.
42974**
42975** The minimum value of NN is 1 (of course).  Increasing NN above 1
42976** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
42977** in exchange for a larger degradation in INSERT and UPDATE performance.
42978** The value of NN appears to give the best results overall.
42979*/
42980#define NN 1             /* Number of neighbors on either side of pPage */
42981#define NB (NN*2+1)      /* Total pages involved in the balance */
42982
42983
42984#ifndef SQLITE_OMIT_QUICKBALANCE
42985/*
42986** This version of balance() handles the common special case where
42987** a new entry is being inserted on the extreme right-end of the
42988** tree, in other words, when the new entry will become the largest
42989** entry in the tree.
42990**
42991** Instead of trying to balance the 3 right-most leaf pages, just add
42992** a new page to the right-hand side and put the one new entry in
42993** that page.  This leaves the right side of the tree somewhat
42994** unbalanced.  But odds are that we will be inserting new entries
42995** at the end soon afterwards so the nearly empty page will quickly
42996** fill up.  On average.
42997**
42998** pPage is the leaf page which is the right-most page in the tree.
42999** pParent is its parent.  pPage must have a single overflow entry
43000** which is also the right-most entry on the page.
43001**
43002** The pSpace buffer is used to store a temporary copy of the divider
43003** cell that will be inserted into pParent. Such a cell consists of a 4
43004** byte page number followed by a variable length integer. In other
43005** words, at most 13 bytes. Hence the pSpace buffer must be at
43006** least 13 bytes in size.
43007*/
43008static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
43009  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
43010  MemPage *pNew;                       /* Newly allocated page */
43011  int rc;                              /* Return Code */
43012  Pgno pgnoNew;                        /* Page number of pNew */
43013
43014  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43015  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43016  assert( pPage->nOverflow==1 );
43017
43018  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
43019
43020  /* Allocate a new page. This page will become the right-sibling of
43021  ** pPage. Make the parent page writable, so that the new divider cell
43022  ** may be inserted. If both these operations are successful, proceed.
43023  */
43024  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
43025
43026  if( rc==SQLITE_OK ){
43027
43028    u8 *pOut = &pSpace[4];
43029    u8 *pCell = pPage->aOvfl[0].pCell;
43030    u16 szCell = cellSizePtr(pPage, pCell);
43031    u8 *pStop;
43032
43033    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
43034    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
43035    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
43036    assemblePage(pNew, 1, &pCell, &szCell);
43037
43038    /* If this is an auto-vacuum database, update the pointer map
43039    ** with entries for the new page, and any pointer from the
43040    ** cell on the page to an overflow page. If either of these
43041    ** operations fails, the return code is set, but the contents
43042    ** of the parent page are still manipulated by thh code below.
43043    ** That is Ok, at this point the parent page is guaranteed to
43044    ** be marked as dirty. Returning an error code will cause a
43045    ** rollback, undoing any changes made to the parent page.
43046    */
43047    if( ISAUTOVACUUM ){
43048      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
43049      if( szCell>pNew->minLocal ){
43050        ptrmapPutOvflPtr(pNew, pCell, &rc);
43051      }
43052    }
43053
43054    /* Create a divider cell to insert into pParent. The divider cell
43055    ** consists of a 4-byte page number (the page number of pPage) and
43056    ** a variable length key value (which must be the same value as the
43057    ** largest key on pPage).
43058    **
43059    ** To find the largest key value on pPage, first find the right-most
43060    ** cell on pPage. The first two fields of this cell are the
43061    ** record-length (a variable length integer at most 32-bits in size)
43062    ** and the key value (a variable length integer, may have any value).
43063    ** The first of the while(...) loops below skips over the record-length
43064    ** field. The second while(...) loop copies the key value from the
43065    ** cell on pPage into the pSpace buffer.
43066    */
43067    pCell = findCell(pPage, pPage->nCell-1);
43068    pStop = &pCell[9];
43069    while( (*(pCell++)&0x80) && pCell<pStop );
43070    pStop = &pCell[9];
43071    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
43072
43073    /* Insert the new divider cell into pParent. */
43074    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
43075               0, pPage->pgno, &rc);
43076
43077    /* Set the right-child pointer of pParent to point to the new page. */
43078    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
43079
43080    /* Release the reference to the new page. */
43081    releasePage(pNew);
43082  }
43083
43084  return rc;
43085}
43086#endif /* SQLITE_OMIT_QUICKBALANCE */
43087
43088#if 0
43089/*
43090** This function does not contribute anything to the operation of SQLite.
43091** it is sometimes activated temporarily while debugging code responsible
43092** for setting pointer-map entries.
43093*/
43094static int ptrmapCheckPages(MemPage **apPage, int nPage){
43095  int i, j;
43096  for(i=0; i<nPage; i++){
43097    Pgno n;
43098    u8 e;
43099    MemPage *pPage = apPage[i];
43100    BtShared *pBt = pPage->pBt;
43101    assert( pPage->isInit );
43102
43103    for(j=0; j<pPage->nCell; j++){
43104      CellInfo info;
43105      u8 *z;
43106
43107      z = findCell(pPage, j);
43108      btreeParseCellPtr(pPage, z, &info);
43109      if( info.iOverflow ){
43110        Pgno ovfl = get4byte(&z[info.iOverflow]);
43111        ptrmapGet(pBt, ovfl, &e, &n);
43112        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
43113      }
43114      if( !pPage->leaf ){
43115        Pgno child = get4byte(z);
43116        ptrmapGet(pBt, child, &e, &n);
43117        assert( n==pPage->pgno && e==PTRMAP_BTREE );
43118      }
43119    }
43120    if( !pPage->leaf ){
43121      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
43122      ptrmapGet(pBt, child, &e, &n);
43123      assert( n==pPage->pgno && e==PTRMAP_BTREE );
43124    }
43125  }
43126  return 1;
43127}
43128#endif
43129
43130/*
43131** This function is used to copy the contents of the b-tree node stored
43132** on page pFrom to page pTo. If page pFrom was not a leaf page, then
43133** the pointer-map entries for each child page are updated so that the
43134** parent page stored in the pointer map is page pTo. If pFrom contained
43135** any cells with overflow page pointers, then the corresponding pointer
43136** map entries are also updated so that the parent page is page pTo.
43137**
43138** If pFrom is currently carrying any overflow cells (entries in the
43139** MemPage.aOvfl[] array), they are not copied to pTo.
43140**
43141** Before returning, page pTo is reinitialized using btreeInitPage().
43142**
43143** The performance of this function is not critical. It is only used by
43144** the balance_shallower() and balance_deeper() procedures, neither of
43145** which are called often under normal circumstances.
43146*/
43147static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
43148  if( (*pRC)==SQLITE_OK ){
43149    BtShared * const pBt = pFrom->pBt;
43150    u8 * const aFrom = pFrom->aData;
43151    u8 * const aTo = pTo->aData;
43152    int const iFromHdr = pFrom->hdrOffset;
43153    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
43154    int rc;
43155    int iData;
43156
43157
43158    assert( pFrom->isInit );
43159    assert( pFrom->nFree>=iToHdr );
43160    assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
43161
43162    /* Copy the b-tree node content from page pFrom to page pTo. */
43163    iData = get2byte(&aFrom[iFromHdr+5]);
43164    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
43165    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
43166
43167    /* Reinitialize page pTo so that the contents of the MemPage structure
43168    ** match the new data. The initialization of pTo can actually fail under
43169    ** fairly obscure circumstances, even though it is a copy of initialized
43170    ** page pFrom.
43171    */
43172    pTo->isInit = 0;
43173    rc = btreeInitPage(pTo);
43174    if( rc!=SQLITE_OK ){
43175      *pRC = rc;
43176      return;
43177    }
43178
43179    /* If this is an auto-vacuum database, update the pointer-map entries
43180    ** for any b-tree or overflow pages that pTo now contains the pointers to.
43181    */
43182    if( ISAUTOVACUUM ){
43183      *pRC = setChildPtrmaps(pTo);
43184    }
43185  }
43186}
43187
43188/*
43189** This routine redistributes cells on the iParentIdx'th child of pParent
43190** (hereafter "the page") and up to 2 siblings so that all pages have about the
43191** same amount of free space. Usually a single sibling on either side of the
43192** page are used in the balancing, though both siblings might come from one
43193** side if the page is the first or last child of its parent. If the page
43194** has fewer than 2 siblings (something which can only happen if the page
43195** is a root page or a child of a root page) then all available siblings
43196** participate in the balancing.
43197**
43198** The number of siblings of the page might be increased or decreased by
43199** one or two in an effort to keep pages nearly full but not over full.
43200**
43201** Note that when this routine is called, some of the cells on the page
43202** might not actually be stored in MemPage.aData[]. This can happen
43203** if the page is overfull. This routine ensures that all cells allocated
43204** to the page and its siblings fit into MemPage.aData[] before returning.
43205**
43206** In the course of balancing the page and its siblings, cells may be
43207** inserted into or removed from the parent page (pParent). Doing so
43208** may cause the parent page to become overfull or underfull. If this
43209** happens, it is the responsibility of the caller to invoke the correct
43210** balancing routine to fix this problem (see the balance() routine).
43211**
43212** If this routine fails for any reason, it might leave the database
43213** in a corrupted state. So if this routine fails, the database should
43214** be rolled back.
43215**
43216** The third argument to this function, aOvflSpace, is a pointer to a
43217** buffer big enough to hold one page. If while inserting cells into the parent
43218** page (pParent) the parent page becomes overfull, this buffer is
43219** used to store the parent's overflow cells. Because this function inserts
43220** a maximum of four divider cells into the parent page, and the maximum
43221** size of a cell stored within an internal node is always less than 1/4
43222** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
43223** enough for all overflow cells.
43224**
43225** If aOvflSpace is set to a null pointer, this function returns
43226** SQLITE_NOMEM.
43227*/
43228static int balance_nonroot(
43229  MemPage *pParent,               /* Parent page of siblings being balanced */
43230  int iParentIdx,                 /* Index of "the page" in pParent */
43231  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
43232  int isRoot                      /* True if pParent is a root-page */
43233){
43234  BtShared *pBt;               /* The whole database */
43235  int nCell = 0;               /* Number of cells in apCell[] */
43236  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
43237  int nNew = 0;                /* Number of pages in apNew[] */
43238  int nOld;                    /* Number of pages in apOld[] */
43239  int i, j, k;                 /* Loop counters */
43240  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
43241  int rc = SQLITE_OK;          /* The return code */
43242  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
43243  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
43244  int usableSpace;             /* Bytes in pPage beyond the header */
43245  int pageFlags;               /* Value of pPage->aData[0] */
43246  int subtotal;                /* Subtotal of bytes in cells on one page */
43247  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
43248  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
43249  int szScratch;               /* Size of scratch memory requested */
43250  MemPage *apOld[NB];          /* pPage and up to two siblings */
43251  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
43252  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
43253  u8 *pRight;                  /* Location in parent of right-sibling pointer */
43254  u8 *apDiv[NB-1];             /* Divider cells in pParent */
43255  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
43256  int szNew[NB+2];             /* Combined size of cells place on i-th page */
43257  u8 **apCell = 0;             /* All cells begin balanced */
43258  u16 *szCell;                 /* Local size of all cells in apCell[] */
43259  u8 *aSpace1;                 /* Space for copies of dividers cells */
43260  Pgno pgno;                   /* Temp var to store a page number in */
43261
43262  pBt = pParent->pBt;
43263  assert( sqlite3_mutex_held(pBt->mutex) );
43264  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43265
43266#if 0
43267  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
43268#endif
43269
43270  /* At this point pParent may have at most one overflow cell. And if
43271  ** this overflow cell is present, it must be the cell with
43272  ** index iParentIdx. This scenario comes about when this function
43273  ** is called (indirectly) from sqlite3BtreeDelete().
43274  */
43275  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
43276  assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
43277
43278  if( !aOvflSpace ){
43279    return SQLITE_NOMEM;
43280  }
43281
43282  /* Find the sibling pages to balance. Also locate the cells in pParent
43283  ** that divide the siblings. An attempt is made to find NN siblings on
43284  ** either side of pPage. More siblings are taken from one side, however,
43285  ** if there are fewer than NN siblings on the other side. If pParent
43286  ** has NB or fewer children then all children of pParent are taken.
43287  **
43288  ** This loop also drops the divider cells from the parent page. This
43289  ** way, the remainder of the function does not have to deal with any
43290  ** overflow cells in the parent page, since if any existed they will
43291  ** have already been removed.
43292  */
43293  i = pParent->nOverflow + pParent->nCell;
43294  if( i<2 ){
43295    nxDiv = 0;
43296    nOld = i+1;
43297  }else{
43298    nOld = 3;
43299    if( iParentIdx==0 ){
43300      nxDiv = 0;
43301    }else if( iParentIdx==i ){
43302      nxDiv = i-2;
43303    }else{
43304      nxDiv = iParentIdx-1;
43305    }
43306    i = 2;
43307  }
43308  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
43309    pRight = &pParent->aData[pParent->hdrOffset+8];
43310  }else{
43311    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
43312  }
43313  pgno = get4byte(pRight);
43314  while( 1 ){
43315    rc = getAndInitPage(pBt, pgno, &apOld[i]);
43316    if( rc ){
43317      memset(apOld, 0, (i+1)*sizeof(MemPage*));
43318      goto balance_cleanup;
43319    }
43320    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
43321    if( (i--)==0 ) break;
43322
43323    if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
43324      apDiv[i] = pParent->aOvfl[0].pCell;
43325      pgno = get4byte(apDiv[i]);
43326      szNew[i] = cellSizePtr(pParent, apDiv[i]);
43327      pParent->nOverflow = 0;
43328    }else{
43329      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
43330      pgno = get4byte(apDiv[i]);
43331      szNew[i] = cellSizePtr(pParent, apDiv[i]);
43332
43333      /* Drop the cell from the parent page. apDiv[i] still points to
43334      ** the cell within the parent, even though it has been dropped.
43335      ** This is safe because dropping a cell only overwrites the first
43336      ** four bytes of it, and this function does not need the first
43337      ** four bytes of the divider cell. So the pointer is safe to use
43338      ** later on.
43339      **
43340      ** Unless SQLite is compiled in secure-delete mode. In this case,
43341      ** the dropCell() routine will overwrite the entire cell with zeroes.
43342      ** In this case, temporarily copy the cell into the aOvflSpace[]
43343      ** buffer. It will be copied out again as soon as the aSpace[] buffer
43344      ** is allocated.  */
43345#ifdef SQLITE_SECURE_DELETE
43346      memcpy(&aOvflSpace[apDiv[i]-pParent->aData], apDiv[i], szNew[i]);
43347      apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
43348#endif
43349      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
43350    }
43351  }
43352
43353  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
43354  ** alignment */
43355  nMaxCells = (nMaxCells + 3)&~3;
43356
43357  /*
43358  ** Allocate space for memory structures
43359  */
43360  k = pBt->pageSize + ROUND8(sizeof(MemPage));
43361  szScratch =
43362       nMaxCells*sizeof(u8*)                       /* apCell */
43363     + nMaxCells*sizeof(u16)                       /* szCell */
43364     + pBt->pageSize                               /* aSpace1 */
43365     + k*nOld;                                     /* Page copies (apCopy) */
43366  apCell = sqlite3ScratchMalloc( szScratch );
43367  if( apCell==0 ){
43368    rc = SQLITE_NOMEM;
43369    goto balance_cleanup;
43370  }
43371  szCell = (u16*)&apCell[nMaxCells];
43372  aSpace1 = (u8*)&szCell[nMaxCells];
43373  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
43374
43375  /*
43376  ** Load pointers to all cells on sibling pages and the divider cells
43377  ** into the local apCell[] array.  Make copies of the divider cells
43378  ** into space obtained from aSpace1[] and remove the the divider Cells
43379  ** from pParent.
43380  **
43381  ** If the siblings are on leaf pages, then the child pointers of the
43382  ** divider cells are stripped from the cells before they are copied
43383  ** into aSpace1[].  In this way, all cells in apCell[] are without
43384  ** child pointers.  If siblings are not leaves, then all cell in
43385  ** apCell[] include child pointers.  Either way, all cells in apCell[]
43386  ** are alike.
43387  **
43388  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
43389  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
43390  */
43391  leafCorrection = apOld[0]->leaf*4;
43392  leafData = apOld[0]->hasData;
43393  for(i=0; i<nOld; i++){
43394    int limit;
43395
43396    /* Before doing anything else, take a copy of the i'th original sibling
43397    ** The rest of this function will use data from the copies rather
43398    ** that the original pages since the original pages will be in the
43399    ** process of being overwritten.  */
43400    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
43401    memcpy(pOld, apOld[i], sizeof(MemPage));
43402    pOld->aData = (void*)&pOld[1];
43403    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
43404
43405    limit = pOld->nCell+pOld->nOverflow;
43406    for(j=0; j<limit; j++){
43407      assert( nCell<nMaxCells );
43408      apCell[nCell] = findOverflowCell(pOld, j);
43409      szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
43410      nCell++;
43411    }
43412    if( i<nOld-1 && !leafData){
43413      u16 sz = (u16)szNew[i];
43414      u8 *pTemp;
43415      assert( nCell<nMaxCells );
43416      szCell[nCell] = sz;
43417      pTemp = &aSpace1[iSpace1];
43418      iSpace1 += sz;
43419      assert( sz<=pBt->pageSize/4 );
43420      assert( iSpace1<=pBt->pageSize );
43421      memcpy(pTemp, apDiv[i], sz);
43422      apCell[nCell] = pTemp+leafCorrection;
43423      assert( leafCorrection==0 || leafCorrection==4 );
43424      szCell[nCell] = szCell[nCell] - leafCorrection;
43425      if( !pOld->leaf ){
43426        assert( leafCorrection==0 );
43427        assert( pOld->hdrOffset==0 );
43428        /* The right pointer of the child page pOld becomes the left
43429        ** pointer of the divider cell */
43430        memcpy(apCell[nCell], &pOld->aData[8], 4);
43431      }else{
43432        assert( leafCorrection==4 );
43433        if( szCell[nCell]<4 ){
43434          /* Do not allow any cells smaller than 4 bytes. */
43435          szCell[nCell] = 4;
43436        }
43437      }
43438      nCell++;
43439    }
43440  }
43441
43442  /*
43443  ** Figure out the number of pages needed to hold all nCell cells.
43444  ** Store this number in "k".  Also compute szNew[] which is the total
43445  ** size of all cells on the i-th page and cntNew[] which is the index
43446  ** in apCell[] of the cell that divides page i from page i+1.
43447  ** cntNew[k] should equal nCell.
43448  **
43449  ** Values computed by this block:
43450  **
43451  **           k: The total number of sibling pages
43452  **    szNew[i]: Spaced used on the i-th sibling page.
43453  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
43454  **              the right of the i-th sibling page.
43455  ** usableSpace: Number of bytes of space available on each sibling.
43456  **
43457  */
43458  usableSpace = pBt->usableSize - 12 + leafCorrection;
43459  for(subtotal=k=i=0; i<nCell; i++){
43460    assert( i<nMaxCells );
43461    subtotal += szCell[i] + 2;
43462    if( subtotal > usableSpace ){
43463      szNew[k] = subtotal - szCell[i];
43464      cntNew[k] = i;
43465      if( leafData ){ i--; }
43466      subtotal = 0;
43467      k++;
43468      if( k>NB+1 ){ rc = SQLITE_CORRUPT; goto balance_cleanup; }
43469    }
43470  }
43471  szNew[k] = subtotal;
43472  cntNew[k] = nCell;
43473  k++;
43474
43475  /*
43476  ** The packing computed by the previous block is biased toward the siblings
43477  ** on the left side.  The left siblings are always nearly full, while the
43478  ** right-most sibling might be nearly empty.  This block of code attempts
43479  ** to adjust the packing of siblings to get a better balance.
43480  **
43481  ** This adjustment is more than an optimization.  The packing above might
43482  ** be so out of balance as to be illegal.  For example, the right-most
43483  ** sibling might be completely empty.  This adjustment is not optional.
43484  */
43485  for(i=k-1; i>0; i--){
43486    int szRight = szNew[i];  /* Size of sibling on the right */
43487    int szLeft = szNew[i-1]; /* Size of sibling on the left */
43488    int r;              /* Index of right-most cell in left sibling */
43489    int d;              /* Index of first cell to the left of right sibling */
43490
43491    r = cntNew[i-1] - 1;
43492    d = r + 1 - leafData;
43493    assert( d<nMaxCells );
43494    assert( r<nMaxCells );
43495    while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
43496      szRight += szCell[d] + 2;
43497      szLeft -= szCell[r] + 2;
43498      cntNew[i-1]--;
43499      r = cntNew[i-1] - 1;
43500      d = r + 1 - leafData;
43501    }
43502    szNew[i] = szRight;
43503    szNew[i-1] = szLeft;
43504  }
43505
43506  /* Either we found one or more cells (cntnew[0])>0) or pPage is
43507  ** a virtual root page.  A virtual root page is when the real root
43508  ** page is page 1 and we are the only child of that page.
43509  */
43510  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
43511
43512  TRACE(("BALANCE: old: %d %d %d  ",
43513    apOld[0]->pgno,
43514    nOld>=2 ? apOld[1]->pgno : 0,
43515    nOld>=3 ? apOld[2]->pgno : 0
43516  ));
43517
43518  /*
43519  ** Allocate k new pages.  Reuse old pages where possible.
43520  */
43521  if( apOld[0]->pgno<=1 ){
43522    rc = SQLITE_CORRUPT;
43523    goto balance_cleanup;
43524  }
43525  pageFlags = apOld[0]->aData[0];
43526  for(i=0; i<k; i++){
43527    MemPage *pNew;
43528    if( i<nOld ){
43529      pNew = apNew[i] = apOld[i];
43530      apOld[i] = 0;
43531      rc = sqlite3PagerWrite(pNew->pDbPage);
43532      nNew++;
43533      if( rc ) goto balance_cleanup;
43534    }else{
43535      assert( i>0 );
43536      rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
43537      if( rc ) goto balance_cleanup;
43538      apNew[i] = pNew;
43539      nNew++;
43540
43541      /* Set the pointer-map entry for the new sibling page. */
43542      if( ISAUTOVACUUM ){
43543        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
43544        if( rc!=SQLITE_OK ){
43545          goto balance_cleanup;
43546        }
43547      }
43548    }
43549  }
43550
43551  /* Free any old pages that were not reused as new pages.
43552  */
43553  while( i<nOld ){
43554    freePage(apOld[i], &rc);
43555    if( rc ) goto balance_cleanup;
43556    releasePage(apOld[i]);
43557    apOld[i] = 0;
43558    i++;
43559  }
43560
43561  /*
43562  ** Put the new pages in accending order.  This helps to
43563  ** keep entries in the disk file in order so that a scan
43564  ** of the table is a linear scan through the file.  That
43565  ** in turn helps the operating system to deliver pages
43566  ** from the disk more rapidly.
43567  **
43568  ** An O(n^2) insertion sort algorithm is used, but since
43569  ** n is never more than NB (a small constant), that should
43570  ** not be a problem.
43571  **
43572  ** When NB==3, this one optimization makes the database
43573  ** about 25% faster for large insertions and deletions.
43574  */
43575  for(i=0; i<k-1; i++){
43576    int minV = apNew[i]->pgno;
43577    int minI = i;
43578    for(j=i+1; j<k; j++){
43579      if( apNew[j]->pgno<(unsigned)minV ){
43580        minI = j;
43581        minV = apNew[j]->pgno;
43582      }
43583    }
43584    if( minI>i ){
43585      int t;
43586      MemPage *pT;
43587      t = apNew[i]->pgno;
43588      pT = apNew[i];
43589      apNew[i] = apNew[minI];
43590      apNew[minI] = pT;
43591    }
43592  }
43593  TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
43594    apNew[0]->pgno, szNew[0],
43595    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
43596    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
43597    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
43598    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
43599
43600  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43601  put4byte(pRight, apNew[nNew-1]->pgno);
43602
43603  /*
43604  ** Evenly distribute the data in apCell[] across the new pages.
43605  ** Insert divider cells into pParent as necessary.
43606  */
43607  j = 0;
43608  for(i=0; i<nNew; i++){
43609    /* Assemble the new sibling page. */
43610    MemPage *pNew = apNew[i];
43611    assert( j<nMaxCells );
43612    zeroPage(pNew, pageFlags);
43613    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
43614    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
43615    assert( pNew->nOverflow==0 );
43616
43617    j = cntNew[i];
43618
43619    /* If the sibling page assembled above was not the right-most sibling,
43620    ** insert a divider cell into the parent page.
43621    */
43622    assert( i<nNew-1 || j==nCell );
43623    if( j<nCell ){
43624      u8 *pCell;
43625      u8 *pTemp;
43626      int sz;
43627
43628      assert( j<nMaxCells );
43629      pCell = apCell[j];
43630      sz = szCell[j] + leafCorrection;
43631      pTemp = &aOvflSpace[iOvflSpace];
43632      if( !pNew->leaf ){
43633        memcpy(&pNew->aData[8], pCell, 4);
43634      }else if( leafData ){
43635        /* If the tree is a leaf-data tree, and the siblings are leaves,
43636        ** then there is no divider cell in apCell[]. Instead, the divider
43637        ** cell consists of the integer key for the right-most cell of
43638        ** the sibling-page assembled above only.
43639        */
43640        CellInfo info;
43641        j--;
43642        btreeParseCellPtr(pNew, apCell[j], &info);
43643        pCell = pTemp;
43644        sz = 4 + putVarint(&pCell[4], info.nKey);
43645        pTemp = 0;
43646      }else{
43647        pCell -= 4;
43648        /* Obscure case for non-leaf-data trees: If the cell at pCell was
43649        ** previously stored on a leaf node, and its reported size was 4
43650        ** bytes, then it may actually be smaller than this
43651        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
43652        ** any cell). But it is important to pass the correct size to
43653        ** insertCell(), so reparse the cell now.
43654        **
43655        ** Note that this can never happen in an SQLite data file, as all
43656        ** cells are at least 4 bytes. It only happens in b-trees used
43657        ** to evaluate "IN (SELECT ...)" and similar clauses.
43658        */
43659        if( szCell[j]==4 ){
43660          assert(leafCorrection==4);
43661          sz = cellSizePtr(pParent, pCell);
43662        }
43663      }
43664      iOvflSpace += sz;
43665      assert( sz<=pBt->pageSize/4 );
43666      assert( iOvflSpace<=pBt->pageSize );
43667      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
43668      if( rc!=SQLITE_OK ) goto balance_cleanup;
43669      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
43670
43671      j++;
43672      nxDiv++;
43673    }
43674  }
43675  assert( j==nCell );
43676  assert( nOld>0 );
43677  assert( nNew>0 );
43678  if( (pageFlags & PTF_LEAF)==0 ){
43679    u8 *zChild = &apCopy[nOld-1]->aData[8];
43680    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
43681  }
43682
43683  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
43684    /* The root page of the b-tree now contains no cells. The only sibling
43685    ** page is the right-child of the parent. Copy the contents of the
43686    ** child page into the parent, decreasing the overall height of the
43687    ** b-tree structure by one. This is described as the "balance-shallower"
43688    ** sub-algorithm in some documentation.
43689    **
43690    ** If this is an auto-vacuum database, the call to copyNodeContent()
43691    ** sets all pointer-map entries corresponding to database image pages
43692    ** for which the pointer is stored within the content being copied.
43693    **
43694    ** The second assert below verifies that the child page is defragmented
43695    ** (it must be, as it was just reconstructed using assemblePage()). This
43696    ** is important if the parent page happens to be page 1 of the database
43697    ** image.  */
43698    assert( nNew==1 );
43699    assert( apNew[0]->nFree ==
43700        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
43701    );
43702    copyNodeContent(apNew[0], pParent, &rc);
43703    freePage(apNew[0], &rc);
43704  }else if( ISAUTOVACUUM ){
43705    /* Fix the pointer-map entries for all the cells that were shifted around.
43706    ** There are several different types of pointer-map entries that need to
43707    ** be dealt with by this routine. Some of these have been set already, but
43708    ** many have not. The following is a summary:
43709    **
43710    **   1) The entries associated with new sibling pages that were not
43711    **      siblings when this function was called. These have already
43712    **      been set. We don't need to worry about old siblings that were
43713    **      moved to the free-list - the freePage() code has taken care
43714    **      of those.
43715    **
43716    **   2) The pointer-map entries associated with the first overflow
43717    **      page in any overflow chains used by new divider cells. These
43718    **      have also already been taken care of by the insertCell() code.
43719    **
43720    **   3) If the sibling pages are not leaves, then the child pages of
43721    **      cells stored on the sibling pages may need to be updated.
43722    **
43723    **   4) If the sibling pages are not internal intkey nodes, then any
43724    **      overflow pages used by these cells may need to be updated
43725    **      (internal intkey nodes never contain pointers to overflow pages).
43726    **
43727    **   5) If the sibling pages are not leaves, then the pointer-map
43728    **      entries for the right-child pages of each sibling may need
43729    **      to be updated.
43730    **
43731    ** Cases 1 and 2 are dealt with above by other code. The next
43732    ** block deals with cases 3 and 4 and the one after that, case 5. Since
43733    ** setting a pointer map entry is a relatively expensive operation, this
43734    ** code only sets pointer map entries for child or overflow pages that have
43735    ** actually moved between pages.  */
43736    MemPage *pNew = apNew[0];
43737    MemPage *pOld = apCopy[0];
43738    int nOverflow = pOld->nOverflow;
43739    int iNextOld = pOld->nCell + nOverflow;
43740    int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
43741    j = 0;                             /* Current 'old' sibling page */
43742    k = 0;                             /* Current 'new' sibling page */
43743    for(i=0; i<nCell; i++){
43744      int isDivider = 0;
43745      while( i==iNextOld ){
43746        /* Cell i is the cell immediately following the last cell on old
43747        ** sibling page j. If the siblings are not leaf pages of an
43748        ** intkey b-tree, then cell i was a divider cell. */
43749        pOld = apCopy[++j];
43750        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
43751        if( pOld->nOverflow ){
43752          nOverflow = pOld->nOverflow;
43753          iOverflow = i + !leafData + pOld->aOvfl[0].idx;
43754        }
43755        isDivider = !leafData;
43756      }
43757
43758      assert(nOverflow>0 || iOverflow<i );
43759      assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
43760      assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
43761      if( i==iOverflow ){
43762        isDivider = 1;
43763        if( (--nOverflow)>0 ){
43764          iOverflow++;
43765        }
43766      }
43767
43768      if( i==cntNew[k] ){
43769        /* Cell i is the cell immediately following the last cell on new
43770        ** sibling page k. If the siblings are not leaf pages of an
43771        ** intkey b-tree, then cell i is a divider cell.  */
43772        pNew = apNew[++k];
43773        if( !leafData ) continue;
43774      }
43775      assert( j<nOld );
43776      assert( k<nNew );
43777
43778      /* If the cell was originally divider cell (and is not now) or
43779      ** an overflow cell, or if the cell was located on a different sibling
43780      ** page before the balancing, then the pointer map entries associated
43781      ** with any child or overflow pages need to be updated.  */
43782      if( isDivider || pOld->pgno!=pNew->pgno ){
43783        if( !leafCorrection ){
43784          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
43785        }
43786        if( szCell[i]>pNew->minLocal ){
43787          ptrmapPutOvflPtr(pNew, apCell[i], &rc);
43788        }
43789      }
43790    }
43791
43792    if( !leafCorrection ){
43793      for(i=0; i<nNew; i++){
43794        u32 key = get4byte(&apNew[i]->aData[8]);
43795        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
43796      }
43797    }
43798
43799#if 0
43800    /* The ptrmapCheckPages() contains assert() statements that verify that
43801    ** all pointer map pages are set correctly. This is helpful while
43802    ** debugging. This is usually disabled because a corrupt database may
43803    ** cause an assert() statement to fail.  */
43804    ptrmapCheckPages(apNew, nNew);
43805    ptrmapCheckPages(&pParent, 1);
43806#endif
43807  }
43808
43809  assert( pParent->isInit );
43810  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
43811          nOld, nNew, nCell));
43812
43813  /*
43814  ** Cleanup before returning.
43815  */
43816balance_cleanup:
43817  sqlite3ScratchFree(apCell);
43818  for(i=0; i<nOld; i++){
43819    releasePage(apOld[i]);
43820  }
43821  for(i=0; i<nNew; i++){
43822    releasePage(apNew[i]);
43823  }
43824
43825  return rc;
43826}
43827
43828
43829/*
43830** This function is called when the root page of a b-tree structure is
43831** overfull (has one or more overflow pages).
43832**
43833** A new child page is allocated and the contents of the current root
43834** page, including overflow cells, are copied into the child. The root
43835** page is then overwritten to make it an empty page with the right-child
43836** pointer pointing to the new page.
43837**
43838** Before returning, all pointer-map entries corresponding to pages
43839** that the new child-page now contains pointers to are updated. The
43840** entry corresponding to the new right-child pointer of the root
43841** page is also updated.
43842**
43843** If successful, *ppChild is set to contain a reference to the child
43844** page and SQLITE_OK is returned. In this case the caller is required
43845** to call releasePage() on *ppChild exactly once. If an error occurs,
43846** an error code is returned and *ppChild is set to 0.
43847*/
43848static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
43849  int rc;                        /* Return value from subprocedures */
43850  MemPage *pChild = 0;           /* Pointer to a new child page */
43851  Pgno pgnoChild = 0;            /* Page number of the new child page */
43852  BtShared *pBt = pRoot->pBt;    /* The BTree */
43853
43854  assert( pRoot->nOverflow>0 );
43855  assert( sqlite3_mutex_held(pBt->mutex) );
43856
43857  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
43858  ** page that will become the new right-child of pPage. Copy the contents
43859  ** of the node stored on pRoot into the new child page.
43860  */
43861  rc = sqlite3PagerWrite(pRoot->pDbPage);
43862  if( rc==SQLITE_OK ){
43863    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
43864    copyNodeContent(pRoot, pChild, &rc);
43865    if( ISAUTOVACUUM ){
43866      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
43867    }
43868  }
43869  if( rc ){
43870    *ppChild = 0;
43871    releasePage(pChild);
43872    return rc;
43873  }
43874  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
43875  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
43876  assert( pChild->nCell==pRoot->nCell );
43877
43878  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
43879
43880  /* Copy the overflow cells from pRoot to pChild */
43881  memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
43882  pChild->nOverflow = pRoot->nOverflow;
43883
43884  /* Zero the contents of pRoot. Then install pChild as the right-child. */
43885  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
43886  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
43887
43888  *ppChild = pChild;
43889  return SQLITE_OK;
43890}
43891
43892/*
43893** The page that pCur currently points to has just been modified in
43894** some way. This function figures out if this modification means the
43895** tree needs to be balanced, and if so calls the appropriate balancing
43896** routine. Balancing routines are:
43897**
43898**   balance_quick()
43899**   balance_deeper()
43900**   balance_nonroot()
43901*/
43902static int balance(BtCursor *pCur){
43903  int rc = SQLITE_OK;
43904  const int nMin = pCur->pBt->usableSize * 2 / 3;
43905  u8 aBalanceQuickSpace[13];
43906  u8 *pFree = 0;
43907
43908  TESTONLY( int balance_quick_called = 0 );
43909  TESTONLY( int balance_deeper_called = 0 );
43910
43911  do {
43912    int iPage = pCur->iPage;
43913    MemPage *pPage = pCur->apPage[iPage];
43914
43915    if( iPage==0 ){
43916      if( pPage->nOverflow ){
43917        /* The root page of the b-tree is overfull. In this case call the
43918        ** balance_deeper() function to create a new child for the root-page
43919        ** and copy the current contents of the root-page to it. The
43920        ** next iteration of the do-loop will balance the child page.
43921        */
43922        assert( (balance_deeper_called++)==0 );
43923        rc = balance_deeper(pPage, &pCur->apPage[1]);
43924        if( rc==SQLITE_OK ){
43925          pCur->iPage = 1;
43926          pCur->aiIdx[0] = 0;
43927          pCur->aiIdx[1] = 0;
43928          assert( pCur->apPage[1]->nOverflow );
43929        }
43930      }else{
43931        break;
43932      }
43933    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
43934      break;
43935    }else{
43936      MemPage * const pParent = pCur->apPage[iPage-1];
43937      int const iIdx = pCur->aiIdx[iPage-1];
43938
43939      rc = sqlite3PagerWrite(pParent->pDbPage);
43940      if( rc==SQLITE_OK ){
43941#ifndef SQLITE_OMIT_QUICKBALANCE
43942        if( pPage->hasData
43943         && pPage->nOverflow==1
43944         && pPage->aOvfl[0].idx==pPage->nCell
43945         && pParent->pgno!=1
43946         && pParent->nCell==iIdx
43947        ){
43948          /* Call balance_quick() to create a new sibling of pPage on which
43949          ** to store the overflow cell. balance_quick() inserts a new cell
43950          ** into pParent, which may cause pParent overflow. If this
43951          ** happens, the next interation of the do-loop will balance pParent
43952          ** use either balance_nonroot() or balance_deeper(). Until this
43953          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
43954          ** buffer.
43955          **
43956          ** The purpose of the following assert() is to check that only a
43957          ** single call to balance_quick() is made for each call to this
43958          ** function. If this were not verified, a subtle bug involving reuse
43959          ** of the aBalanceQuickSpace[] might sneak in.
43960          */
43961          assert( (balance_quick_called++)==0 );
43962          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
43963        }else
43964#endif
43965        {
43966          /* In this case, call balance_nonroot() to redistribute cells
43967          ** between pPage and up to 2 of its sibling pages. This involves
43968          ** modifying the contents of pParent, which may cause pParent to
43969          ** become overfull or underfull. The next iteration of the do-loop
43970          ** will balance the parent page to correct this.
43971          **
43972          ** If the parent page becomes overfull, the overflow cell or cells
43973          ** are stored in the pSpace buffer allocated immediately below.
43974          ** A subsequent iteration of the do-loop will deal with this by
43975          ** calling balance_nonroot() (balance_deeper() may be called first,
43976          ** but it doesn't deal with overflow cells - just moves them to a
43977          ** different page). Once this subsequent call to balance_nonroot()
43978          ** has completed, it is safe to release the pSpace buffer used by
43979          ** the previous call, as the overflow cell data will have been
43980          ** copied either into the body of a database page or into the new
43981          ** pSpace buffer passed to the latter call to balance_nonroot().
43982          */
43983          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
43984          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
43985          if( pFree ){
43986            /* If pFree is not NULL, it points to the pSpace buffer used
43987            ** by a previous call to balance_nonroot(). Its contents are
43988            ** now stored either on real database pages or within the
43989            ** new pSpace buffer, so it may be safely freed here. */
43990            sqlite3PageFree(pFree);
43991          }
43992
43993          /* The pSpace buffer will be freed after the next call to
43994          ** balance_nonroot(), or just before this function returns, whichever
43995          ** comes first. */
43996          pFree = pSpace;
43997        }
43998      }
43999
44000      pPage->nOverflow = 0;
44001
44002      /* The next iteration of the do-loop balances the parent page. */
44003      releasePage(pPage);
44004      pCur->iPage--;
44005    }
44006  }while( rc==SQLITE_OK );
44007
44008  if( pFree ){
44009    sqlite3PageFree(pFree);
44010  }
44011  return rc;
44012}
44013
44014
44015/*
44016** Insert a new record into the BTree.  The key is given by (pKey,nKey)
44017** and the data is given by (pData,nData).  The cursor is used only to
44018** define what table the record should be inserted into.  The cursor
44019** is left pointing at a random location.
44020**
44021** For an INTKEY table, only the nKey value of the key is used.  pKey is
44022** ignored.  For a ZERODATA table, the pData and nData are both ignored.
44023**
44024** If the seekResult parameter is non-zero, then a successful call to
44025** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
44026** been performed. seekResult is the search result returned (a negative
44027** number if pCur points at an entry that is smaller than (pKey, nKey), or
44028** a positive value if pCur points at an etry that is larger than
44029** (pKey, nKey)).
44030**
44031** If the seekResult parameter is non-zero, then the caller guarantees that
44032** cursor pCur is pointing at the existing copy of a row that is to be
44033** overwritten.  If the seekResult parameter is 0, then cursor pCur may
44034** point to any entry or to no entry at all and so this function has to seek
44035** the cursor before the new key can be inserted.
44036*/
44037SQLITE_PRIVATE int sqlite3BtreeInsert(
44038  BtCursor *pCur,                /* Insert data into the table of this cursor */
44039  const void *pKey, i64 nKey,    /* The key of the new record */
44040  const void *pData, int nData,  /* The data of the new record */
44041  int nZero,                     /* Number of extra 0 bytes to append to data */
44042  int appendBias,                /* True if this is likely an append */
44043  int seekResult                 /* Result of prior MovetoUnpacked() call */
44044){
44045  int rc;
44046  int loc = seekResult;          /* -1: before desired location  +1: after */
44047  int szNew = 0;
44048  int idx;
44049  MemPage *pPage;
44050  Btree *p = pCur->pBtree;
44051  BtShared *pBt = p->pBt;
44052  unsigned char *oldCell;
44053  unsigned char *newCell = 0;
44054
44055  if( pCur->eState==CURSOR_FAULT ){
44056    assert( pCur->skipNext!=SQLITE_OK );
44057    return pCur->skipNext;
44058  }
44059
44060  assert( cursorHoldsMutex(pCur) );
44061  assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
44062  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
44063
44064  /* Assert that the caller has been consistent. If this cursor was opened
44065  ** expecting an index b-tree, then the caller should be inserting blob
44066  ** keys with no associated data. If the cursor was opened expecting an
44067  ** intkey table, the caller should be inserting integer keys with a
44068  ** blob of associated data.  */
44069  assert( (pKey==0)==(pCur->pKeyInfo==0) );
44070
44071  /* If this is an insert into a table b-tree, invalidate any incrblob
44072  ** cursors open on the row being replaced (assuming this is a replace
44073  ** operation - if it is not, the following is a no-op).  */
44074  if( pCur->pKeyInfo==0 ){
44075    invalidateIncrblobCursors(p, nKey, 0);
44076  }
44077
44078  /* Save the positions of any other cursors open on this table.
44079  **
44080  ** In some cases, the call to btreeMoveto() below is a no-op. For
44081  ** example, when inserting data into a table with auto-generated integer
44082  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
44083  ** integer key to use. It then calls this function to actually insert the
44084  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
44085  ** that the cursor is already where it needs to be and returns without
44086  ** doing any work. To avoid thwarting these optimizations, it is important
44087  ** not to clear the cursor here.
44088  */
44089  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
44090  if( rc ) return rc;
44091  if( !loc ){
44092    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
44093    if( rc ) return rc;
44094  }
44095  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
44096
44097  pPage = pCur->apPage[pCur->iPage];
44098  assert( pPage->intKey || nKey>=0 );
44099  assert( pPage->leaf || !pPage->intKey );
44100
44101  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
44102          pCur->pgnoRoot, nKey, nData, pPage->pgno,
44103          loc==0 ? "overwrite" : "new entry"));
44104  assert( pPage->isInit );
44105  allocateTempSpace(pBt);
44106  newCell = pBt->pTmpSpace;
44107  if( newCell==0 ) return SQLITE_NOMEM;
44108  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
44109  if( rc ) goto end_insert;
44110  assert( szNew==cellSizePtr(pPage, newCell) );
44111  assert( szNew<=MX_CELL_SIZE(pBt) );
44112  idx = pCur->aiIdx[pCur->iPage];
44113  if( loc==0 ){
44114    u16 szOld;
44115    assert( idx<pPage->nCell );
44116    rc = sqlite3PagerWrite(pPage->pDbPage);
44117    if( rc ){
44118      goto end_insert;
44119    }
44120    oldCell = findCell(pPage, idx);
44121    if( !pPage->leaf ){
44122      memcpy(newCell, oldCell, 4);
44123    }
44124    szOld = cellSizePtr(pPage, oldCell);
44125    rc = clearCell(pPage, oldCell);
44126    dropCell(pPage, idx, szOld, &rc);
44127    if( rc ) goto end_insert;
44128  }else if( loc<0 && pPage->nCell>0 ){
44129    assert( pPage->leaf );
44130    idx = ++pCur->aiIdx[pCur->iPage];
44131  }else{
44132    assert( pPage->leaf );
44133  }
44134  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
44135  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
44136
44137  /* If no error has occured and pPage has an overflow cell, call balance()
44138  ** to redistribute the cells within the tree. Since balance() may move
44139  ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
44140  ** variables.
44141  **
44142  ** Previous versions of SQLite called moveToRoot() to move the cursor
44143  ** back to the root page as balance() used to invalidate the contents
44144  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
44145  ** set the cursor state to "invalid". This makes common insert operations
44146  ** slightly faster.
44147  **
44148  ** There is a subtle but important optimization here too. When inserting
44149  ** multiple records into an intkey b-tree using a single cursor (as can
44150  ** happen while processing an "INSERT INTO ... SELECT" statement), it
44151  ** is advantageous to leave the cursor pointing to the last entry in
44152  ** the b-tree if possible. If the cursor is left pointing to the last
44153  ** entry in the table, and the next row inserted has an integer key
44154  ** larger than the largest existing key, it is possible to insert the
44155  ** row without seeking the cursor. This can be a big performance boost.
44156  */
44157  pCur->info.nSize = 0;
44158  pCur->validNKey = 0;
44159  if( rc==SQLITE_OK && pPage->nOverflow ){
44160    rc = balance(pCur);
44161
44162    /* Must make sure nOverflow is reset to zero even if the balance()
44163    ** fails. Internal data structure corruption will result otherwise.
44164    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
44165    ** from trying to save the current position of the cursor.  */
44166    pCur->apPage[pCur->iPage]->nOverflow = 0;
44167    pCur->eState = CURSOR_INVALID;
44168  }
44169  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
44170
44171end_insert:
44172  return rc;
44173}
44174
44175/*
44176** Delete the entry that the cursor is pointing to.  The cursor
44177** is left pointing at a arbitrary location.
44178*/
44179SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
44180  Btree *p = pCur->pBtree;
44181  BtShared *pBt = p->pBt;
44182  int rc;                              /* Return code */
44183  MemPage *pPage;                      /* Page to delete cell from */
44184  unsigned char *pCell;                /* Pointer to cell to delete */
44185  int iCellIdx;                        /* Index of cell to delete */
44186  int iCellDepth;                      /* Depth of node containing pCell */
44187
44188  assert( cursorHoldsMutex(pCur) );
44189  assert( pBt->inTransaction==TRANS_WRITE );
44190  assert( !pBt->readOnly );
44191  assert( pCur->wrFlag );
44192  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
44193  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
44194
44195  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
44196   || NEVER(pCur->eState!=CURSOR_VALID)
44197  ){
44198    return SQLITE_ERROR;  /* Something has gone awry. */
44199  }
44200
44201  /* If this is a delete operation to remove a row from a table b-tree,
44202  ** invalidate any incrblob cursors open on the row being deleted.  */
44203  if( pCur->pKeyInfo==0 ){
44204    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
44205  }
44206
44207  iCellDepth = pCur->iPage;
44208  iCellIdx = pCur->aiIdx[iCellDepth];
44209  pPage = pCur->apPage[iCellDepth];
44210  pCell = findCell(pPage, iCellIdx);
44211
44212  /* If the page containing the entry to delete is not a leaf page, move
44213  ** the cursor to the largest entry in the tree that is smaller than
44214  ** the entry being deleted. This cell will replace the cell being deleted
44215  ** from the internal node. The 'previous' entry is used for this instead
44216  ** of the 'next' entry, as the previous entry is always a part of the
44217  ** sub-tree headed by the child page of the cell being deleted. This makes
44218  ** balancing the tree following the delete operation easier.  */
44219  if( !pPage->leaf ){
44220    int notUsed;
44221    rc = sqlite3BtreePrevious(pCur, &notUsed);
44222    if( rc ) return rc;
44223  }
44224
44225  /* Save the positions of any other cursors open on this table before
44226  ** making any modifications. Make the page containing the entry to be
44227  ** deleted writable. Then free any overflow pages associated with the
44228  ** entry and finally remove the cell itself from within the page.
44229  */
44230  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
44231  if( rc ) return rc;
44232  rc = sqlite3PagerWrite(pPage->pDbPage);
44233  if( rc ) return rc;
44234  rc = clearCell(pPage, pCell);
44235  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
44236  if( rc ) return rc;
44237
44238  /* If the cell deleted was not located on a leaf page, then the cursor
44239  ** is currently pointing to the largest entry in the sub-tree headed
44240  ** by the child-page of the cell that was just deleted from an internal
44241  ** node. The cell from the leaf node needs to be moved to the internal
44242  ** node to replace the deleted cell.  */
44243  if( !pPage->leaf ){
44244    MemPage *pLeaf = pCur->apPage[pCur->iPage];
44245    int nCell;
44246    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
44247    unsigned char *pTmp;
44248
44249    pCell = findCell(pLeaf, pLeaf->nCell-1);
44250    nCell = cellSizePtr(pLeaf, pCell);
44251    assert( MX_CELL_SIZE(pBt)>=nCell );
44252
44253    allocateTempSpace(pBt);
44254    pTmp = pBt->pTmpSpace;
44255
44256    rc = sqlite3PagerWrite(pLeaf->pDbPage);
44257    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
44258    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
44259    if( rc ) return rc;
44260  }
44261
44262  /* Balance the tree. If the entry deleted was located on a leaf page,
44263  ** then the cursor still points to that page. In this case the first
44264  ** call to balance() repairs the tree, and the if(...) condition is
44265  ** never true.
44266  **
44267  ** Otherwise, if the entry deleted was on an internal node page, then
44268  ** pCur is pointing to the leaf page from which a cell was removed to
44269  ** replace the cell deleted from the internal node. This is slightly
44270  ** tricky as the leaf node may be underfull, and the internal node may
44271  ** be either under or overfull. In this case run the balancing algorithm
44272  ** on the leaf node first. If the balance proceeds far enough up the
44273  ** tree that we can be sure that any problem in the internal node has
44274  ** been corrected, so be it. Otherwise, after balancing the leaf node,
44275  ** walk the cursor up the tree to the internal node and balance it as
44276  ** well.  */
44277  rc = balance(pCur);
44278  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
44279    while( pCur->iPage>iCellDepth ){
44280      releasePage(pCur->apPage[pCur->iPage--]);
44281    }
44282    rc = balance(pCur);
44283  }
44284
44285  if( rc==SQLITE_OK ){
44286    moveToRoot(pCur);
44287  }
44288  return rc;
44289}
44290
44291/*
44292** Create a new BTree table.  Write into *piTable the page
44293** number for the root page of the new table.
44294**
44295** The type of type is determined by the flags parameter.  Only the
44296** following values of flags are currently in use.  Other values for
44297** flags might not work:
44298**
44299**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
44300**     BTREE_ZERODATA                  Used for SQL indices
44301*/
44302static int btreeCreateTable(Btree *p, int *piTable, int flags){
44303  BtShared *pBt = p->pBt;
44304  MemPage *pRoot;
44305  Pgno pgnoRoot;
44306  int rc;
44307
44308  assert( sqlite3BtreeHoldsMutex(p) );
44309  assert( pBt->inTransaction==TRANS_WRITE );
44310  assert( !pBt->readOnly );
44311
44312#ifdef SQLITE_OMIT_AUTOVACUUM
44313  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
44314  if( rc ){
44315    return rc;
44316  }
44317#else
44318  if( pBt->autoVacuum ){
44319    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
44320    MemPage *pPageMove; /* The page to move to. */
44321
44322    /* Creating a new table may probably require moving an existing database
44323    ** to make room for the new tables root page. In case this page turns
44324    ** out to be an overflow page, delete all overflow page-map caches
44325    ** held by open cursors.
44326    */
44327    invalidateAllOverflowCache(pBt);
44328
44329    /* Read the value of meta[3] from the database to determine where the
44330    ** root page of the new table should go. meta[3] is the largest root-page
44331    ** created so far, so the new root-page is (meta[3]+1).
44332    */
44333    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
44334    pgnoRoot++;
44335
44336    /* The new root-page may not be allocated on a pointer-map page, or the
44337    ** PENDING_BYTE page.
44338    */
44339    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
44340        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
44341      pgnoRoot++;
44342    }
44343    assert( pgnoRoot>=3 );
44344
44345    /* Allocate a page. The page that currently resides at pgnoRoot will
44346    ** be moved to the allocated page (unless the allocated page happens
44347    ** to reside at pgnoRoot).
44348    */
44349    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
44350    if( rc!=SQLITE_OK ){
44351      return rc;
44352    }
44353
44354    if( pgnoMove!=pgnoRoot ){
44355      /* pgnoRoot is the page that will be used for the root-page of
44356      ** the new table (assuming an error did not occur). But we were
44357      ** allocated pgnoMove. If required (i.e. if it was not allocated
44358      ** by extending the file), the current page at position pgnoMove
44359      ** is already journaled.
44360      */
44361      u8 eType = 0;
44362      Pgno iPtrPage = 0;
44363
44364      releasePage(pPageMove);
44365
44366      /* Move the page currently at pgnoRoot to pgnoMove. */
44367      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
44368      if( rc!=SQLITE_OK ){
44369        return rc;
44370      }
44371      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
44372      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
44373        rc = SQLITE_CORRUPT_BKPT;
44374      }
44375      if( rc!=SQLITE_OK ){
44376        releasePage(pRoot);
44377        return rc;
44378      }
44379      assert( eType!=PTRMAP_ROOTPAGE );
44380      assert( eType!=PTRMAP_FREEPAGE );
44381      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
44382      releasePage(pRoot);
44383
44384      /* Obtain the page at pgnoRoot */
44385      if( rc!=SQLITE_OK ){
44386        return rc;
44387      }
44388      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
44389      if( rc!=SQLITE_OK ){
44390        return rc;
44391      }
44392      rc = sqlite3PagerWrite(pRoot->pDbPage);
44393      if( rc!=SQLITE_OK ){
44394        releasePage(pRoot);
44395        return rc;
44396      }
44397    }else{
44398      pRoot = pPageMove;
44399    }
44400
44401    /* Update the pointer-map and meta-data with the new root-page number. */
44402    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
44403    if( rc ){
44404      releasePage(pRoot);
44405      return rc;
44406    }
44407    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
44408    if( rc ){
44409      releasePage(pRoot);
44410      return rc;
44411    }
44412
44413  }else{
44414    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
44415    if( rc ) return rc;
44416  }
44417#endif
44418  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
44419  zeroPage(pRoot, flags | PTF_LEAF);
44420  sqlite3PagerUnref(pRoot->pDbPage);
44421  *piTable = (int)pgnoRoot;
44422  return SQLITE_OK;
44423}
44424SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
44425  int rc;
44426  sqlite3BtreeEnter(p);
44427  rc = btreeCreateTable(p, piTable, flags);
44428  sqlite3BtreeLeave(p);
44429  return rc;
44430}
44431
44432/*
44433** Erase the given database page and all its children.  Return
44434** the page to the freelist.
44435*/
44436static int clearDatabasePage(
44437  BtShared *pBt,           /* The BTree that contains the table */
44438  Pgno pgno,               /* Page number to clear */
44439  int freePageFlag,        /* Deallocate page if true */
44440  int *pnChange            /* Add number of Cells freed to this counter */
44441){
44442  MemPage *pPage;
44443  int rc;
44444  unsigned char *pCell;
44445  int i;
44446
44447  assert( sqlite3_mutex_held(pBt->mutex) );
44448  if( pgno>pagerPagecount(pBt) ){
44449    return SQLITE_CORRUPT_BKPT;
44450  }
44451
44452  rc = getAndInitPage(pBt, pgno, &pPage);
44453  if( rc ) return rc;
44454  for(i=0; i<pPage->nCell; i++){
44455    pCell = findCell(pPage, i);
44456    if( !pPage->leaf ){
44457      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
44458      if( rc ) goto cleardatabasepage_out;
44459    }
44460    rc = clearCell(pPage, pCell);
44461    if( rc ) goto cleardatabasepage_out;
44462  }
44463  if( !pPage->leaf ){
44464    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
44465    if( rc ) goto cleardatabasepage_out;
44466  }else if( pnChange ){
44467    assert( pPage->intKey );
44468    *pnChange += pPage->nCell;
44469  }
44470  if( freePageFlag ){
44471    freePage(pPage, &rc);
44472  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
44473    zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
44474  }
44475
44476cleardatabasepage_out:
44477  releasePage(pPage);
44478  return rc;
44479}
44480
44481/*
44482** Delete all information from a single table in the database.  iTable is
44483** the page number of the root of the table.  After this routine returns,
44484** the root page is empty, but still exists.
44485**
44486** This routine will fail with SQLITE_LOCKED if there are any open
44487** read cursors on the table.  Open write cursors are moved to the
44488** root of the table.
44489**
44490** If pnChange is not NULL, then table iTable must be an intkey table. The
44491** integer value pointed to by pnChange is incremented by the number of
44492** entries in the table.
44493*/
44494SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
44495  int rc;
44496  BtShared *pBt = p->pBt;
44497  sqlite3BtreeEnter(p);
44498  assert( p->inTrans==TRANS_WRITE );
44499
44500  /* Invalidate all incrblob cursors open on table iTable (assuming iTable
44501  ** is the root of a table b-tree - if it is not, the following call is
44502  ** a no-op).  */
44503  invalidateIncrblobCursors(p, 0, 1);
44504
44505  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
44506  if( SQLITE_OK==rc ){
44507    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
44508  }
44509  sqlite3BtreeLeave(p);
44510  return rc;
44511}
44512
44513/*
44514** Erase all information in a table and add the root of the table to
44515** the freelist.  Except, the root of the principle table (the one on
44516** page 1) is never added to the freelist.
44517**
44518** This routine will fail with SQLITE_LOCKED if there are any open
44519** cursors on the table.
44520**
44521** If AUTOVACUUM is enabled and the page at iTable is not the last
44522** root page in the database file, then the last root page
44523** in the database file is moved into the slot formerly occupied by
44524** iTable and that last slot formerly occupied by the last root page
44525** is added to the freelist instead of iTable.  In this say, all
44526** root pages are kept at the beginning of the database file, which
44527** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
44528** page number that used to be the last root page in the file before
44529** the move.  If no page gets moved, *piMoved is set to 0.
44530** The last root page is recorded in meta[3] and the value of
44531** meta[3] is updated by this procedure.
44532*/
44533static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
44534  int rc;
44535  MemPage *pPage = 0;
44536  BtShared *pBt = p->pBt;
44537
44538  assert( sqlite3BtreeHoldsMutex(p) );
44539  assert( p->inTrans==TRANS_WRITE );
44540
44541  /* It is illegal to drop a table if any cursors are open on the
44542  ** database. This is because in auto-vacuum mode the backend may
44543  ** need to move another root-page to fill a gap left by the deleted
44544  ** root page. If an open cursor was using this page a problem would
44545  ** occur.
44546  **
44547  ** This error is caught long before control reaches this point.
44548  */
44549  if( NEVER(pBt->pCursor) ){
44550    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
44551    return SQLITE_LOCKED_SHAREDCACHE;
44552  }
44553
44554  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
44555  if( rc ) return rc;
44556  rc = sqlite3BtreeClearTable(p, iTable, 0);
44557  if( rc ){
44558    releasePage(pPage);
44559    return rc;
44560  }
44561
44562  *piMoved = 0;
44563
44564  if( iTable>1 ){
44565#ifdef SQLITE_OMIT_AUTOVACUUM
44566    freePage(pPage, &rc);
44567    releasePage(pPage);
44568#else
44569    if( pBt->autoVacuum ){
44570      Pgno maxRootPgno;
44571      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
44572
44573      if( iTable==maxRootPgno ){
44574        /* If the table being dropped is the table with the largest root-page
44575        ** number in the database, put the root page on the free list.
44576        */
44577        freePage(pPage, &rc);
44578        releasePage(pPage);
44579        if( rc!=SQLITE_OK ){
44580          return rc;
44581        }
44582      }else{
44583        /* The table being dropped does not have the largest root-page
44584        ** number in the database. So move the page that does into the
44585        ** gap left by the deleted root-page.
44586        */
44587        MemPage *pMove;
44588        releasePage(pPage);
44589        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
44590        if( rc!=SQLITE_OK ){
44591          return rc;
44592        }
44593        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
44594        releasePage(pMove);
44595        if( rc!=SQLITE_OK ){
44596          return rc;
44597        }
44598        pMove = 0;
44599        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
44600        freePage(pMove, &rc);
44601        releasePage(pMove);
44602        if( rc!=SQLITE_OK ){
44603          return rc;
44604        }
44605        *piMoved = maxRootPgno;
44606      }
44607
44608      /* Set the new 'max-root-page' value in the database header. This
44609      ** is the old value less one, less one more if that happens to
44610      ** be a root-page number, less one again if that is the
44611      ** PENDING_BYTE_PAGE.
44612      */
44613      maxRootPgno--;
44614      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
44615             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
44616        maxRootPgno--;
44617      }
44618      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
44619
44620      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
44621    }else{
44622      freePage(pPage, &rc);
44623      releasePage(pPage);
44624    }
44625#endif
44626  }else{
44627    /* If sqlite3BtreeDropTable was called on page 1.
44628    ** This really never should happen except in a corrupt
44629    ** database.
44630    */
44631    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
44632    releasePage(pPage);
44633  }
44634  return rc;
44635}
44636SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
44637  int rc;
44638  sqlite3BtreeEnter(p);
44639  rc = btreeDropTable(p, iTable, piMoved);
44640  sqlite3BtreeLeave(p);
44641  return rc;
44642}
44643
44644
44645/*
44646** This function may only be called if the b-tree connection already
44647** has a read or write transaction open on the database.
44648**
44649** Read the meta-information out of a database file.  Meta[0]
44650** is the number of free pages currently in the database.  Meta[1]
44651** through meta[15] are available for use by higher layers.  Meta[0]
44652** is read-only, the others are read/write.
44653**
44654** The schema layer numbers meta values differently.  At the schema
44655** layer (and the SetCookie and ReadCookie opcodes) the number of
44656** free pages is not visible.  So Cookie[0] is the same as Meta[1].
44657*/
44658SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
44659  BtShared *pBt = p->pBt;
44660
44661  sqlite3BtreeEnter(p);
44662  assert( p->inTrans>TRANS_NONE );
44663  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
44664  assert( pBt->pPage1 );
44665  assert( idx>=0 && idx<=15 );
44666
44667  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
44668
44669  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
44670  ** database, mark the database as read-only.  */
44671#ifdef SQLITE_OMIT_AUTOVACUUM
44672  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
44673#endif
44674
44675  sqlite3BtreeLeave(p);
44676}
44677
44678/*
44679** Write meta-information back into the database.  Meta[0] is
44680** read-only and may not be written.
44681*/
44682SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
44683  BtShared *pBt = p->pBt;
44684  unsigned char *pP1;
44685  int rc;
44686  assert( idx>=1 && idx<=15 );
44687  sqlite3BtreeEnter(p);
44688  assert( p->inTrans==TRANS_WRITE );
44689  assert( pBt->pPage1!=0 );
44690  pP1 = pBt->pPage1->aData;
44691  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
44692  if( rc==SQLITE_OK ){
44693    put4byte(&pP1[36 + idx*4], iMeta);
44694#ifndef SQLITE_OMIT_AUTOVACUUM
44695    if( idx==BTREE_INCR_VACUUM ){
44696      assert( pBt->autoVacuum || iMeta==0 );
44697      assert( iMeta==0 || iMeta==1 );
44698      pBt->incrVacuum = (u8)iMeta;
44699    }
44700#endif
44701  }
44702  sqlite3BtreeLeave(p);
44703  return rc;
44704}
44705
44706#ifndef SQLITE_OMIT_BTREECOUNT
44707/*
44708** The first argument, pCur, is a cursor opened on some b-tree. Count the
44709** number of entries in the b-tree and write the result to *pnEntry.
44710**
44711** SQLITE_OK is returned if the operation is successfully executed.
44712** Otherwise, if an error is encountered (i.e. an IO error or database
44713** corruption) an SQLite error code is returned.
44714*/
44715SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
44716  i64 nEntry = 0;                      /* Value to return in *pnEntry */
44717  int rc;                              /* Return code */
44718  rc = moveToRoot(pCur);
44719
44720  /* Unless an error occurs, the following loop runs one iteration for each
44721  ** page in the B-Tree structure (not including overflow pages).
44722  */
44723  while( rc==SQLITE_OK ){
44724    int iIdx;                          /* Index of child node in parent */
44725    MemPage *pPage;                    /* Current page of the b-tree */
44726
44727    /* If this is a leaf page or the tree is not an int-key tree, then
44728    ** this page contains countable entries. Increment the entry counter
44729    ** accordingly.
44730    */
44731    pPage = pCur->apPage[pCur->iPage];
44732    if( pPage->leaf || !pPage->intKey ){
44733      nEntry += pPage->nCell;
44734    }
44735
44736    /* pPage is a leaf node. This loop navigates the cursor so that it
44737    ** points to the first interior cell that it points to the parent of
44738    ** the next page in the tree that has not yet been visited. The
44739    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
44740    ** of the page, or to the number of cells in the page if the next page
44741    ** to visit is the right-child of its parent.
44742    **
44743    ** If all pages in the tree have been visited, return SQLITE_OK to the
44744    ** caller.
44745    */
44746    if( pPage->leaf ){
44747      do {
44748        if( pCur->iPage==0 ){
44749          /* All pages of the b-tree have been visited. Return successfully. */
44750          *pnEntry = nEntry;
44751          return SQLITE_OK;
44752        }
44753        moveToParent(pCur);
44754      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
44755
44756      pCur->aiIdx[pCur->iPage]++;
44757      pPage = pCur->apPage[pCur->iPage];
44758    }
44759
44760    /* Descend to the child node of the cell that the cursor currently
44761    ** points at. This is the right-child if (iIdx==pPage->nCell).
44762    */
44763    iIdx = pCur->aiIdx[pCur->iPage];
44764    if( iIdx==pPage->nCell ){
44765      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
44766    }else{
44767      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
44768    }
44769  }
44770
44771  /* An error has occurred. Return an error code. */
44772  return rc;
44773}
44774#endif
44775
44776/*
44777** Return the pager associated with a BTree.  This routine is used for
44778** testing and debugging only.
44779*/
44780SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
44781  return p->pBt->pPager;
44782}
44783
44784#ifndef SQLITE_OMIT_INTEGRITY_CHECK
44785/*
44786** Append a message to the error message string.
44787*/
44788static void checkAppendMsg(
44789  IntegrityCk *pCheck,
44790  char *zMsg1,
44791  const char *zFormat,
44792  ...
44793){
44794  va_list ap;
44795  if( !pCheck->mxErr ) return;
44796  pCheck->mxErr--;
44797  pCheck->nErr++;
44798  va_start(ap, zFormat);
44799  if( pCheck->errMsg.nChar ){
44800    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
44801  }
44802  if( zMsg1 ){
44803    sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
44804  }
44805  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
44806  va_end(ap);
44807  if( pCheck->errMsg.mallocFailed ){
44808    pCheck->mallocFailed = 1;
44809  }
44810}
44811#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
44812
44813#ifndef SQLITE_OMIT_INTEGRITY_CHECK
44814/*
44815** Add 1 to the reference count for page iPage.  If this is the second
44816** reference to the page, add an error message to pCheck->zErrMsg.
44817** Return 1 if there are 2 ore more references to the page and 0 if
44818** if this is the first reference to the page.
44819**
44820** Also check that the page number is in bounds.
44821*/
44822static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
44823  if( iPage==0 ) return 1;
44824  if( iPage>pCheck->nPage ){
44825    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
44826    return 1;
44827  }
44828  if( pCheck->anRef[iPage]==1 ){
44829    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
44830    return 1;
44831  }
44832  return  (pCheck->anRef[iPage]++)>1;
44833}
44834
44835#ifndef SQLITE_OMIT_AUTOVACUUM
44836/*
44837** Check that the entry in the pointer-map for page iChild maps to
44838** page iParent, pointer type ptrType. If not, append an error message
44839** to pCheck.
44840*/
44841static void checkPtrmap(
44842  IntegrityCk *pCheck,   /* Integrity check context */
44843  Pgno iChild,           /* Child page number */
44844  u8 eType,              /* Expected pointer map type */
44845  Pgno iParent,          /* Expected pointer map parent page number */
44846  char *zContext         /* Context description (used for error msg) */
44847){
44848  int rc;
44849  u8 ePtrmapType;
44850  Pgno iPtrmapParent;
44851
44852  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
44853  if( rc!=SQLITE_OK ){
44854    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
44855    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
44856    return;
44857  }
44858
44859  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
44860    checkAppendMsg(pCheck, zContext,
44861      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
44862      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
44863  }
44864}
44865#endif
44866
44867/*
44868** Check the integrity of the freelist or of an overflow page list.
44869** Verify that the number of pages on the list is N.
44870*/
44871static void checkList(
44872  IntegrityCk *pCheck,  /* Integrity checking context */
44873  int isFreeList,       /* True for a freelist.  False for overflow page list */
44874  int iPage,            /* Page number for first page in the list */
44875  int N,                /* Expected number of pages in the list */
44876  char *zContext        /* Context for error messages */
44877){
44878  int i;
44879  int expected = N;
44880  int iFirst = iPage;
44881  while( N-- > 0 && pCheck->mxErr ){
44882    DbPage *pOvflPage;
44883    unsigned char *pOvflData;
44884    if( iPage<1 ){
44885      checkAppendMsg(pCheck, zContext,
44886         "%d of %d pages missing from overflow list starting at %d",
44887          N+1, expected, iFirst);
44888      break;
44889    }
44890    if( checkRef(pCheck, iPage, zContext) ) break;
44891    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
44892      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
44893      break;
44894    }
44895    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
44896    if( isFreeList ){
44897      int n = get4byte(&pOvflData[4]);
44898#ifndef SQLITE_OMIT_AUTOVACUUM
44899      if( pCheck->pBt->autoVacuum ){
44900        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
44901      }
44902#endif
44903      if( n>pCheck->pBt->usableSize/4-2 ){
44904        checkAppendMsg(pCheck, zContext,
44905           "freelist leaf count too big on page %d", iPage);
44906        N--;
44907      }else{
44908        for(i=0; i<n; i++){
44909          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
44910#ifndef SQLITE_OMIT_AUTOVACUUM
44911          if( pCheck->pBt->autoVacuum ){
44912            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
44913          }
44914#endif
44915          checkRef(pCheck, iFreePage, zContext);
44916        }
44917        N -= n;
44918      }
44919    }
44920#ifndef SQLITE_OMIT_AUTOVACUUM
44921    else{
44922      /* If this database supports auto-vacuum and iPage is not the last
44923      ** page in this overflow list, check that the pointer-map entry for
44924      ** the following page matches iPage.
44925      */
44926      if( pCheck->pBt->autoVacuum && N>0 ){
44927        i = get4byte(pOvflData);
44928        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
44929      }
44930    }
44931#endif
44932    iPage = get4byte(pOvflData);
44933    sqlite3PagerUnref(pOvflPage);
44934  }
44935}
44936#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
44937
44938#ifndef SQLITE_OMIT_INTEGRITY_CHECK
44939/*
44940** Do various sanity checks on a single page of a tree.  Return
44941** the tree depth.  Root pages return 0.  Parents of root pages
44942** return 1, and so forth.
44943**
44944** These checks are done:
44945**
44946**      1.  Make sure that cells and freeblocks do not overlap
44947**          but combine to completely cover the page.
44948**  NO  2.  Make sure cell keys are in order.
44949**  NO  3.  Make sure no key is less than or equal to zLowerBound.
44950**  NO  4.  Make sure no key is greater than or equal to zUpperBound.
44951**      5.  Check the integrity of overflow pages.
44952**      6.  Recursively call checkTreePage on all children.
44953**      7.  Verify that the depth of all children is the same.
44954**      8.  Make sure this page is at least 33% full or else it is
44955**          the root of the tree.
44956*/
44957static int checkTreePage(
44958  IntegrityCk *pCheck,  /* Context for the sanity check */
44959  int iPage,            /* Page number of the page to check */
44960  char *zParentContext  /* Parent context */
44961){
44962  MemPage *pPage;
44963  int i, rc, depth, d2, pgno, cnt;
44964  int hdr, cellStart;
44965  int nCell;
44966  u8 *data;
44967  BtShared *pBt;
44968  int usableSize;
44969  char zContext[100];
44970  char *hit = 0;
44971
44972  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
44973
44974  /* Check that the page exists
44975  */
44976  pBt = pCheck->pBt;
44977  usableSize = pBt->usableSize;
44978  if( iPage==0 ) return 0;
44979  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
44980  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
44981    checkAppendMsg(pCheck, zContext,
44982       "unable to get the page. error code=%d", rc);
44983    return 0;
44984  }
44985
44986  /* Clear MemPage.isInit to make sure the corruption detection code in
44987  ** btreeInitPage() is executed.  */
44988  pPage->isInit = 0;
44989  if( (rc = btreeInitPage(pPage))!=0 ){
44990    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
44991    checkAppendMsg(pCheck, zContext,
44992                   "btreeInitPage() returns error code %d", rc);
44993    releasePage(pPage);
44994    return 0;
44995  }
44996
44997  /* Check out all the cells.
44998  */
44999  depth = 0;
45000  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
45001    u8 *pCell;
45002    u32 sz;
45003    CellInfo info;
45004
45005    /* Check payload overflow pages
45006    */
45007    sqlite3_snprintf(sizeof(zContext), zContext,
45008             "On tree page %d cell %d: ", iPage, i);
45009    pCell = findCell(pPage,i);
45010    btreeParseCellPtr(pPage, pCell, &info);
45011    sz = info.nData;
45012    if( !pPage->intKey ) sz += (int)info.nKey;
45013    assert( sz==info.nPayload );
45014    if( (sz>info.nLocal)
45015     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
45016    ){
45017      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
45018      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
45019#ifndef SQLITE_OMIT_AUTOVACUUM
45020      if( pBt->autoVacuum ){
45021        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
45022      }
45023#endif
45024      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
45025    }
45026
45027    /* Check sanity of left child page.
45028    */
45029    if( !pPage->leaf ){
45030      pgno = get4byte(pCell);
45031#ifndef SQLITE_OMIT_AUTOVACUUM
45032      if( pBt->autoVacuum ){
45033        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
45034      }
45035#endif
45036      d2 = checkTreePage(pCheck, pgno, zContext);
45037      if( i>0 && d2!=depth ){
45038        checkAppendMsg(pCheck, zContext, "Child page depth differs");
45039      }
45040      depth = d2;
45041    }
45042  }
45043  if( !pPage->leaf ){
45044    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
45045    sqlite3_snprintf(sizeof(zContext), zContext,
45046                     "On page %d at right child: ", iPage);
45047#ifndef SQLITE_OMIT_AUTOVACUUM
45048    if( pBt->autoVacuum ){
45049      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, 0);
45050    }
45051#endif
45052    checkTreePage(pCheck, pgno, zContext);
45053  }
45054
45055  /* Check for complete coverage of the page
45056  */
45057  data = pPage->aData;
45058  hdr = pPage->hdrOffset;
45059  hit = sqlite3PageMalloc( pBt->pageSize );
45060  if( hit==0 ){
45061    pCheck->mallocFailed = 1;
45062  }else{
45063    u16 contentOffset = get2byte(&data[hdr+5]);
45064    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
45065    memset(hit+contentOffset, 0, usableSize-contentOffset);
45066    memset(hit, 1, contentOffset);
45067    nCell = get2byte(&data[hdr+3]);
45068    cellStart = hdr + 12 - 4*pPage->leaf;
45069    for(i=0; i<nCell; i++){
45070      int pc = get2byte(&data[cellStart+i*2]);
45071      u16 size = 1024;
45072      int j;
45073      if( pc<=usableSize-4 ){
45074        size = cellSizePtr(pPage, &data[pc]);
45075      }
45076      if( (pc+size-1)>=usableSize ){
45077        checkAppendMsg(pCheck, 0,
45078            "Corruption detected in cell %d on page %d",i,iPage,0);
45079      }else{
45080        for(j=pc+size-1; j>=pc; j--) hit[j]++;
45081      }
45082    }
45083    i = get2byte(&data[hdr+1]);
45084    while( i>0 ){
45085      int size, j;
45086      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
45087      size = get2byte(&data[i+2]);
45088      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
45089      for(j=i+size-1; j>=i; j--) hit[j]++;
45090      j = get2byte(&data[i]);
45091      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
45092      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
45093      i = j;
45094    }
45095    for(i=cnt=0; i<usableSize; i++){
45096      if( hit[i]==0 ){
45097        cnt++;
45098      }else if( hit[i]>1 ){
45099        checkAppendMsg(pCheck, 0,
45100          "Multiple uses for byte %d of page %d", i, iPage);
45101        break;
45102      }
45103    }
45104    if( cnt!=data[hdr+7] ){
45105      checkAppendMsg(pCheck, 0,
45106          "Fragmentation of %d bytes reported as %d on page %d",
45107          cnt, data[hdr+7], iPage);
45108    }
45109  }
45110  sqlite3PageFree(hit);
45111  releasePage(pPage);
45112  return depth+1;
45113}
45114#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45115
45116#ifndef SQLITE_OMIT_INTEGRITY_CHECK
45117/*
45118** This routine does a complete check of the given BTree file.  aRoot[] is
45119** an array of pages numbers were each page number is the root page of
45120** a table.  nRoot is the number of entries in aRoot.
45121**
45122** A read-only or read-write transaction must be opened before calling
45123** this function.
45124**
45125** Write the number of error seen in *pnErr.  Except for some memory
45126** allocation errors,  an error message held in memory obtained from
45127** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
45128** returned.  If a memory allocation error occurs, NULL is returned.
45129*/
45130SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
45131  Btree *p,     /* The btree to be checked */
45132  int *aRoot,   /* An array of root pages numbers for individual trees */
45133  int nRoot,    /* Number of entries in aRoot[] */
45134  int mxErr,    /* Stop reporting errors after this many */
45135  int *pnErr    /* Write number of errors seen to this variable */
45136){
45137  Pgno i;
45138  int nRef;
45139  IntegrityCk sCheck;
45140  BtShared *pBt = p->pBt;
45141  char zErr[100];
45142
45143  sqlite3BtreeEnter(p);
45144  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
45145  nRef = sqlite3PagerRefcount(pBt->pPager);
45146  sCheck.pBt = pBt;
45147  sCheck.pPager = pBt->pPager;
45148  sCheck.nPage = pagerPagecount(sCheck.pBt);
45149  sCheck.mxErr = mxErr;
45150  sCheck.nErr = 0;
45151  sCheck.mallocFailed = 0;
45152  *pnErr = 0;
45153  if( sCheck.nPage==0 ){
45154    sqlite3BtreeLeave(p);
45155    return 0;
45156  }
45157  sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
45158  if( !sCheck.anRef ){
45159    *pnErr = 1;
45160    sqlite3BtreeLeave(p);
45161    return 0;
45162  }
45163  for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
45164  i = PENDING_BYTE_PAGE(pBt);
45165  if( i<=sCheck.nPage ){
45166    sCheck.anRef[i] = 1;
45167  }
45168  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
45169
45170  /* Check the integrity of the freelist
45171  */
45172  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
45173            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
45174
45175  /* Check all the tables.
45176  */
45177  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
45178    if( aRoot[i]==0 ) continue;
45179#ifndef SQLITE_OMIT_AUTOVACUUM
45180    if( pBt->autoVacuum && aRoot[i]>1 ){
45181      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
45182    }
45183#endif
45184    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ");
45185  }
45186
45187  /* Make sure every page in the file is referenced
45188  */
45189  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
45190#ifdef SQLITE_OMIT_AUTOVACUUM
45191    if( sCheck.anRef[i]==0 ){
45192      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
45193    }
45194#else
45195    /* If the database supports auto-vacuum, make sure no tables contain
45196    ** references to pointer-map pages.
45197    */
45198    if( sCheck.anRef[i]==0 &&
45199       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
45200      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
45201    }
45202    if( sCheck.anRef[i]!=0 &&
45203       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
45204      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
45205    }
45206#endif
45207  }
45208
45209  /* Make sure this analysis did not leave any unref() pages.
45210  ** This is an internal consistency check; an integrity check
45211  ** of the integrity check.
45212  */
45213  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
45214    checkAppendMsg(&sCheck, 0,
45215      "Outstanding page count goes from %d to %d during this analysis",
45216      nRef, sqlite3PagerRefcount(pBt->pPager)
45217    );
45218  }
45219
45220  /* Clean  up and report errors.
45221  */
45222  sqlite3BtreeLeave(p);
45223  sqlite3_free(sCheck.anRef);
45224  if( sCheck.mallocFailed ){
45225    sqlite3StrAccumReset(&sCheck.errMsg);
45226    *pnErr = sCheck.nErr+1;
45227    return 0;
45228  }
45229  *pnErr = sCheck.nErr;
45230  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
45231  return sqlite3StrAccumFinish(&sCheck.errMsg);
45232}
45233#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45234
45235/*
45236** Return the full pathname of the underlying database file.
45237**
45238** The pager filename is invariant as long as the pager is
45239** open so it is safe to access without the BtShared mutex.
45240*/
45241SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
45242  assert( p->pBt->pPager!=0 );
45243  return sqlite3PagerFilename(p->pBt->pPager);
45244}
45245
45246/*
45247** Return the pathname of the journal file for this database. The return
45248** value of this routine is the same regardless of whether the journal file
45249** has been created or not.
45250**
45251** The pager journal filename is invariant as long as the pager is
45252** open so it is safe to access without the BtShared mutex.
45253*/
45254SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
45255  assert( p->pBt->pPager!=0 );
45256  return sqlite3PagerJournalname(p->pBt->pPager);
45257}
45258
45259/*
45260** Return non-zero if a transaction is active.
45261*/
45262SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
45263  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
45264  return (p && (p->inTrans==TRANS_WRITE));
45265}
45266
45267/*
45268** Return non-zero if a read (or write) transaction is active.
45269*/
45270SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
45271  assert( p );
45272  assert( sqlite3_mutex_held(p->db->mutex) );
45273  return p->inTrans!=TRANS_NONE;
45274}
45275
45276SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
45277  assert( p );
45278  assert( sqlite3_mutex_held(p->db->mutex) );
45279  return p->nBackup!=0;
45280}
45281
45282/*
45283** This function returns a pointer to a blob of memory associated with
45284** a single shared-btree. The memory is used by client code for its own
45285** purposes (for example, to store a high-level schema associated with
45286** the shared-btree). The btree layer manages reference counting issues.
45287**
45288** The first time this is called on a shared-btree, nBytes bytes of memory
45289** are allocated, zeroed, and returned to the caller. For each subsequent
45290** call the nBytes parameter is ignored and a pointer to the same blob
45291** of memory returned.
45292**
45293** If the nBytes parameter is 0 and the blob of memory has not yet been
45294** allocated, a null pointer is returned. If the blob has already been
45295** allocated, it is returned as normal.
45296**
45297** Just before the shared-btree is closed, the function passed as the
45298** xFree argument when the memory allocation was made is invoked on the
45299** blob of allocated memory. This function should not call sqlite3_free()
45300** on the memory, the btree layer does that.
45301*/
45302SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
45303  BtShared *pBt = p->pBt;
45304  sqlite3BtreeEnter(p);
45305  if( !pBt->pSchema && nBytes ){
45306    pBt->pSchema = sqlite3MallocZero(nBytes);
45307    pBt->xFreeSchema = xFree;
45308  }
45309  sqlite3BtreeLeave(p);
45310  return pBt->pSchema;
45311}
45312
45313/*
45314** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
45315** btree as the argument handle holds an exclusive lock on the
45316** sqlite_master table. Otherwise SQLITE_OK.
45317*/
45318SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
45319  int rc;
45320  assert( sqlite3_mutex_held(p->db->mutex) );
45321  sqlite3BtreeEnter(p);
45322  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
45323  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
45324  sqlite3BtreeLeave(p);
45325  return rc;
45326}
45327
45328
45329#ifndef SQLITE_OMIT_SHARED_CACHE
45330/*
45331** Obtain a lock on the table whose root page is iTab.  The
45332** lock is a write lock if isWritelock is true or a read lock
45333** if it is false.
45334*/
45335SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
45336  int rc = SQLITE_OK;
45337  assert( p->inTrans!=TRANS_NONE );
45338  if( p->sharable ){
45339    u8 lockType = READ_LOCK + isWriteLock;
45340    assert( READ_LOCK+1==WRITE_LOCK );
45341    assert( isWriteLock==0 || isWriteLock==1 );
45342
45343    sqlite3BtreeEnter(p);
45344    rc = querySharedCacheTableLock(p, iTab, lockType);
45345    if( rc==SQLITE_OK ){
45346      rc = setSharedCacheTableLock(p, iTab, lockType);
45347    }
45348    sqlite3BtreeLeave(p);
45349  }
45350  return rc;
45351}
45352#endif
45353
45354#ifndef SQLITE_OMIT_INCRBLOB
45355/*
45356** Argument pCsr must be a cursor opened for writing on an
45357** INTKEY table currently pointing at a valid table entry.
45358** This function modifies the data stored as part of that entry.
45359**
45360** Only the data content may only be modified, it is not possible to
45361** change the length of the data stored. If this function is called with
45362** parameters that attempt to write past the end of the existing data,
45363** no modifications are made and SQLITE_CORRUPT is returned.
45364*/
45365SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
45366  int rc;
45367  assert( cursorHoldsMutex(pCsr) );
45368  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
45369  assert( pCsr->isIncrblobHandle );
45370
45371  rc = restoreCursorPosition(pCsr);
45372  if( rc!=SQLITE_OK ){
45373    return rc;
45374  }
45375  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
45376  if( pCsr->eState!=CURSOR_VALID ){
45377    return SQLITE_ABORT;
45378  }
45379
45380  /* Check some assumptions:
45381  **   (a) the cursor is open for writing,
45382  **   (b) there is a read/write transaction open,
45383  **   (c) the connection holds a write-lock on the table (if required),
45384  **   (d) there are no conflicting read-locks, and
45385  **   (e) the cursor points at a valid row of an intKey table.
45386  */
45387  if( !pCsr->wrFlag ){
45388    return SQLITE_READONLY;
45389  }
45390  assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
45391  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
45392  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
45393  assert( pCsr->apPage[pCsr->iPage]->intKey );
45394
45395  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
45396}
45397
45398/*
45399** Set a flag on this cursor to cache the locations of pages from the
45400** overflow list for the current row. This is used by cursors opened
45401** for incremental blob IO only.
45402**
45403** This function sets a flag only. The actual page location cache
45404** (stored in BtCursor.aOverflow[]) is allocated and used by function
45405** accessPayload() (the worker function for sqlite3BtreeData() and
45406** sqlite3BtreePutData()).
45407*/
45408SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
45409  assert( cursorHoldsMutex(pCur) );
45410  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
45411  assert(!pCur->isIncrblobHandle);
45412  assert(!pCur->aOverflow);
45413  pCur->isIncrblobHandle = 1;
45414}
45415#endif
45416
45417/************** End of btree.c ***********************************************/
45418/************** Begin file backup.c ******************************************/
45419/*
45420** 2009 January 28
45421**
45422** The author disclaims copyright to this source code.  In place of
45423** a legal notice, here is a blessing:
45424**
45425**    May you do good and not evil.
45426**    May you find forgiveness for yourself and forgive others.
45427**    May you share freely, never taking more than you give.
45428**
45429*************************************************************************
45430** This file contains the implementation of the sqlite3_backup_XXX()
45431** API functions and the related features.
45432*/
45433
45434/* Macro to find the minimum of two numeric values.
45435*/
45436#ifndef MIN
45437# define MIN(x,y) ((x)<(y)?(x):(y))
45438#endif
45439
45440/*
45441** Structure allocated for each backup operation.
45442*/
45443struct sqlite3_backup {
45444  sqlite3* pDestDb;        /* Destination database handle */
45445  Btree *pDest;            /* Destination b-tree file */
45446  u32 iDestSchema;         /* Original schema cookie in destination */
45447  int bDestLocked;         /* True once a write-transaction is open on pDest */
45448
45449  Pgno iNext;              /* Page number of the next source page to copy */
45450  sqlite3* pSrcDb;         /* Source database handle */
45451  Btree *pSrc;             /* Source b-tree file */
45452
45453  int rc;                  /* Backup process error code */
45454
45455  /* These two variables are set by every call to backup_step(). They are
45456  ** read by calls to backup_remaining() and backup_pagecount().
45457  */
45458  Pgno nRemaining;         /* Number of pages left to copy */
45459  Pgno nPagecount;         /* Total number of pages to copy */
45460
45461  int isAttached;          /* True once backup has been registered with pager */
45462  sqlite3_backup *pNext;   /* Next backup associated with source pager */
45463};
45464
45465/*
45466** THREAD SAFETY NOTES:
45467**
45468**   Once it has been created using backup_init(), a single sqlite3_backup
45469**   structure may be accessed via two groups of thread-safe entry points:
45470**
45471**     * Via the sqlite3_backup_XXX() API function backup_step() and
45472**       backup_finish(). Both these functions obtain the source database
45473**       handle mutex and the mutex associated with the source BtShared
45474**       structure, in that order.
45475**
45476**     * Via the BackupUpdate() and BackupRestart() functions, which are
45477**       invoked by the pager layer to report various state changes in
45478**       the page cache associated with the source database. The mutex
45479**       associated with the source database BtShared structure will always
45480**       be held when either of these functions are invoked.
45481**
45482**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
45483**   backup_pagecount() are not thread-safe functions. If they are called
45484**   while some other thread is calling backup_step() or backup_finish(),
45485**   the values returned may be invalid. There is no way for a call to
45486**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
45487**   or backup_pagecount().
45488**
45489**   Depending on the SQLite configuration, the database handles and/or
45490**   the Btree objects may have their own mutexes that require locking.
45491**   Non-sharable Btrees (in-memory databases for example), do not have
45492**   associated mutexes.
45493*/
45494
45495/*
45496** Return a pointer corresponding to database zDb (i.e. "main", "temp")
45497** in connection handle pDb. If such a database cannot be found, return
45498** a NULL pointer and write an error message to pErrorDb.
45499**
45500** If the "temp" database is requested, it may need to be opened by this
45501** function. If an error occurs while doing so, return 0 and write an
45502** error message to pErrorDb.
45503*/
45504static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
45505  int i = sqlite3FindDbName(pDb, zDb);
45506
45507  if( i==1 ){
45508    Parse *pParse;
45509    int rc = 0;
45510    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
45511    if( pParse==0 ){
45512      sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
45513      rc = SQLITE_NOMEM;
45514    }else{
45515      pParse->db = pDb;
45516      if( sqlite3OpenTempDatabase(pParse) ){
45517        sqlite3ErrorClear(pParse);
45518        sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
45519        rc = SQLITE_ERROR;
45520      }
45521      sqlite3StackFree(pErrorDb, pParse);
45522    }
45523    if( rc ){
45524      return 0;
45525    }
45526  }
45527
45528  if( i<0 ){
45529    sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
45530    return 0;
45531  }
45532
45533  return pDb->aDb[i].pBt;
45534}
45535
45536/*
45537** Create an sqlite3_backup process to copy the contents of zSrcDb from
45538** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
45539** a pointer to the new sqlite3_backup object.
45540**
45541** If an error occurs, NULL is returned and an error code and error message
45542** stored in database handle pDestDb.
45543*/
45544SQLITE_API sqlite3_backup *sqlite3_backup_init(
45545  sqlite3* pDestDb,                     /* Database to write to */
45546  const char *zDestDb,                  /* Name of database within pDestDb */
45547  sqlite3* pSrcDb,                      /* Database connection to read from */
45548  const char *zSrcDb                    /* Name of database within pSrcDb */
45549){
45550  sqlite3_backup *p;                    /* Value to return */
45551
45552  /* Lock the source database handle. The destination database
45553  ** handle is not locked in this routine, but it is locked in
45554  ** sqlite3_backup_step(). The user is required to ensure that no
45555  ** other thread accesses the destination handle for the duration
45556  ** of the backup operation.  Any attempt to use the destination
45557  ** database connection while a backup is in progress may cause
45558  ** a malfunction or a deadlock.
45559  */
45560  sqlite3_mutex_enter(pSrcDb->mutex);
45561  sqlite3_mutex_enter(pDestDb->mutex);
45562
45563  if( pSrcDb==pDestDb ){
45564    sqlite3Error(
45565        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
45566    );
45567    p = 0;
45568  }else {
45569    /* Allocate space for a new sqlite3_backup object */
45570    p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
45571    if( !p ){
45572      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
45573    }
45574  }
45575
45576  /* If the allocation succeeded, populate the new object. */
45577  if( p ){
45578    memset(p, 0, sizeof(sqlite3_backup));
45579    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
45580    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
45581    p->pDestDb = pDestDb;
45582    p->pSrcDb = pSrcDb;
45583    p->iNext = 1;
45584    p->isAttached = 0;
45585
45586    if( 0==p->pSrc || 0==p->pDest ){
45587      /* One (or both) of the named databases did not exist. An error has
45588      ** already been written into the pDestDb handle. All that is left
45589      ** to do here is free the sqlite3_backup structure.
45590      */
45591      sqlite3_free(p);
45592      p = 0;
45593    }
45594  }
45595  if( p ){
45596    p->pSrc->nBackup++;
45597  }
45598
45599  sqlite3_mutex_leave(pDestDb->mutex);
45600  sqlite3_mutex_leave(pSrcDb->mutex);
45601  return p;
45602}
45603
45604/*
45605** Argument rc is an SQLite error code. Return true if this error is
45606** considered fatal if encountered during a backup operation. All errors
45607** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
45608*/
45609static int isFatalError(int rc){
45610  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
45611}
45612
45613/*
45614** Parameter zSrcData points to a buffer containing the data for
45615** page iSrcPg from the source database. Copy this data into the
45616** destination database.
45617*/
45618static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
45619  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
45620  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
45621  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
45622  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
45623  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
45624
45625  int rc = SQLITE_OK;
45626  i64 iOff;
45627
45628  assert( p->bDestLocked );
45629  assert( !isFatalError(p->rc) );
45630  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
45631  assert( zSrcData );
45632
45633  /* Catch the case where the destination is an in-memory database and the
45634  ** page sizes of the source and destination differ.
45635  */
45636  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(sqlite3BtreePager(p->pDest)) ){
45637    rc = SQLITE_READONLY;
45638  }
45639
45640  /* This loop runs once for each destination page spanned by the source
45641  ** page. For each iteration, variable iOff is set to the byte offset
45642  ** of the destination page.
45643  */
45644  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
45645    DbPage *pDestPg = 0;
45646    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
45647    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
45648    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
45649     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
45650    ){
45651      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
45652      u8 *zDestData = sqlite3PagerGetData(pDestPg);
45653      u8 *zOut = &zDestData[iOff%nDestPgsz];
45654
45655      /* Copy the data from the source page into the destination page.
45656      ** Then clear the Btree layer MemPage.isInit flag. Both this module
45657      ** and the pager code use this trick (clearing the first byte
45658      ** of the page 'extra' space to invalidate the Btree layers
45659      ** cached parse of the page). MemPage.isInit is marked
45660      ** "MUST BE FIRST" for this purpose.
45661      */
45662      memcpy(zOut, zIn, nCopy);
45663      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
45664    }
45665    sqlite3PagerUnref(pDestPg);
45666  }
45667
45668  return rc;
45669}
45670
45671/*
45672** If pFile is currently larger than iSize bytes, then truncate it to
45673** exactly iSize bytes. If pFile is not larger than iSize bytes, then
45674** this function is a no-op.
45675**
45676** Return SQLITE_OK if everything is successful, or an SQLite error
45677** code if an error occurs.
45678*/
45679static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
45680  i64 iCurrent;
45681  int rc = sqlite3OsFileSize(pFile, &iCurrent);
45682  if( rc==SQLITE_OK && iCurrent>iSize ){
45683    rc = sqlite3OsTruncate(pFile, iSize);
45684  }
45685  return rc;
45686}
45687
45688/*
45689** Register this backup object with the associated source pager for
45690** callbacks when pages are changed or the cache invalidated.
45691*/
45692static void attachBackupObject(sqlite3_backup *p){
45693  sqlite3_backup **pp;
45694  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
45695  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
45696  p->pNext = *pp;
45697  *pp = p;
45698  p->isAttached = 1;
45699}
45700
45701/*
45702** Copy nPage pages from the source b-tree to the destination.
45703*/
45704SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
45705  int rc;
45706
45707  sqlite3_mutex_enter(p->pSrcDb->mutex);
45708  sqlite3BtreeEnter(p->pSrc);
45709  if( p->pDestDb ){
45710    sqlite3_mutex_enter(p->pDestDb->mutex);
45711  }
45712
45713  rc = p->rc;
45714  if( !isFatalError(rc) ){
45715    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
45716    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
45717    int ii;                            /* Iterator variable */
45718    int nSrcPage = -1;                 /* Size of source db in pages */
45719    int bCloseTrans = 0;               /* True if src db requires unlocking */
45720
45721    /* If the source pager is currently in a write-transaction, return
45722    ** SQLITE_BUSY immediately.
45723    */
45724    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
45725      rc = SQLITE_BUSY;
45726    }else{
45727      rc = SQLITE_OK;
45728    }
45729
45730    /* Lock the destination database, if it is not locked already. */
45731    if( SQLITE_OK==rc && p->bDestLocked==0
45732     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
45733    ){
45734      p->bDestLocked = 1;
45735      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
45736    }
45737
45738    /* If there is no open read-transaction on the source database, open
45739    ** one now. If a transaction is opened here, then it will be closed
45740    ** before this function exits.
45741    */
45742    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
45743      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
45744      bCloseTrans = 1;
45745    }
45746
45747    /* Now that there is a read-lock on the source database, query the
45748    ** source pager for the number of pages in the database.
45749    */
45750    if( rc==SQLITE_OK ){
45751      rc = sqlite3PagerPagecount(pSrcPager, &nSrcPage);
45752    }
45753    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
45754      const Pgno iSrcPg = p->iNext;                 /* Source page number */
45755      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
45756        DbPage *pSrcPg;                             /* Source page object */
45757        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
45758        if( rc==SQLITE_OK ){
45759          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
45760          sqlite3PagerUnref(pSrcPg);
45761        }
45762      }
45763      p->iNext++;
45764    }
45765    if( rc==SQLITE_OK ){
45766      p->nPagecount = nSrcPage;
45767      p->nRemaining = nSrcPage+1-p->iNext;
45768      if( p->iNext>(Pgno)nSrcPage ){
45769        rc = SQLITE_DONE;
45770      }else if( !p->isAttached ){
45771        attachBackupObject(p);
45772      }
45773    }
45774
45775    /* Update the schema version field in the destination database. This
45776    ** is to make sure that the schema-version really does change in
45777    ** the case where the source and destination databases have the
45778    ** same schema version.
45779    */
45780    if( rc==SQLITE_DONE
45781     && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
45782    ){
45783      const int nSrcPagesize = sqlite3BtreeGetPageSize(p->pSrc);
45784      const int nDestPagesize = sqlite3BtreeGetPageSize(p->pDest);
45785      int nDestTruncate;
45786
45787      if( p->pDestDb ){
45788        sqlite3ResetInternalSchema(p->pDestDb, 0);
45789      }
45790
45791      /* Set nDestTruncate to the final number of pages in the destination
45792      ** database. The complication here is that the destination page
45793      ** size may be different to the source page size.
45794      **
45795      ** If the source page size is smaller than the destination page size,
45796      ** round up. In this case the call to sqlite3OsTruncate() below will
45797      ** fix the size of the file. However it is important to call
45798      ** sqlite3PagerTruncateImage() here so that any pages in the
45799      ** destination file that lie beyond the nDestTruncate page mark are
45800      ** journalled by PagerCommitPhaseOne() before they are destroyed
45801      ** by the file truncation.
45802      */
45803      if( nSrcPagesize<nDestPagesize ){
45804        int ratio = nDestPagesize/nSrcPagesize;
45805        nDestTruncate = (nSrcPage+ratio-1)/ratio;
45806        if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
45807          nDestTruncate--;
45808        }
45809      }else{
45810        nDestTruncate = nSrcPage * (nSrcPagesize/nDestPagesize);
45811      }
45812      sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
45813
45814      if( nSrcPagesize<nDestPagesize ){
45815        /* If the source page-size is smaller than the destination page-size,
45816        ** two extra things may need to happen:
45817        **
45818        **   * The destination may need to be truncated, and
45819        **
45820        **   * Data stored on the pages immediately following the
45821        **     pending-byte page in the source database may need to be
45822        **     copied into the destination database.
45823        */
45824        const i64 iSize = (i64)nSrcPagesize * (i64)nSrcPage;
45825        sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
45826
45827        assert( pFile );
45828        assert( (i64)nDestTruncate*(i64)nDestPagesize >= iSize || (
45829              nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
45830           && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+nDestPagesize
45831        ));
45832        if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
45833         && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
45834         && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
45835        ){
45836          i64 iOff;
45837          i64 iEnd = MIN(PENDING_BYTE + nDestPagesize, iSize);
45838          for(
45839            iOff=PENDING_BYTE+nSrcPagesize;
45840            rc==SQLITE_OK && iOff<iEnd;
45841            iOff+=nSrcPagesize
45842          ){
45843            PgHdr *pSrcPg = 0;
45844            const Pgno iSrcPg = (Pgno)((iOff/nSrcPagesize)+1);
45845            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
45846            if( rc==SQLITE_OK ){
45847              u8 *zData = sqlite3PagerGetData(pSrcPg);
45848              rc = sqlite3OsWrite(pFile, zData, nSrcPagesize, iOff);
45849            }
45850            sqlite3PagerUnref(pSrcPg);
45851          }
45852        }
45853      }else{
45854        rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
45855      }
45856
45857      /* Finish committing the transaction to the destination database. */
45858      if( SQLITE_OK==rc
45859       && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
45860      ){
45861        rc = SQLITE_DONE;
45862      }
45863    }
45864
45865    /* If bCloseTrans is true, then this function opened a read transaction
45866    ** on the source database. Close the read transaction here. There is
45867    ** no need to check the return values of the btree methods here, as
45868    ** "committing" a read-only transaction cannot fail.
45869    */
45870    if( bCloseTrans ){
45871      TESTONLY( int rc2 );
45872      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
45873      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
45874      assert( rc2==SQLITE_OK );
45875    }
45876
45877    p->rc = rc;
45878  }
45879  if( p->pDestDb ){
45880    sqlite3_mutex_leave(p->pDestDb->mutex);
45881  }
45882  sqlite3BtreeLeave(p->pSrc);
45883  sqlite3_mutex_leave(p->pSrcDb->mutex);
45884  return rc;
45885}
45886
45887/*
45888** Release all resources associated with an sqlite3_backup* handle.
45889*/
45890SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
45891  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
45892  sqlite3_mutex *mutex;                /* Mutex to protect source database */
45893  int rc;                              /* Value to return */
45894
45895  /* Enter the mutexes */
45896  if( p==0 ) return SQLITE_OK;
45897  sqlite3_mutex_enter(p->pSrcDb->mutex);
45898  sqlite3BtreeEnter(p->pSrc);
45899  mutex = p->pSrcDb->mutex;
45900  if( p->pDestDb ){
45901    sqlite3_mutex_enter(p->pDestDb->mutex);
45902  }
45903
45904  /* Detach this backup from the source pager. */
45905  if( p->pDestDb ){
45906    p->pSrc->nBackup--;
45907  }
45908  if( p->isAttached ){
45909    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
45910    while( *pp!=p ){
45911      pp = &(*pp)->pNext;
45912    }
45913    *pp = p->pNext;
45914  }
45915
45916  /* If a transaction is still open on the Btree, roll it back. */
45917  sqlite3BtreeRollback(p->pDest);
45918
45919  /* Set the error code of the destination database handle. */
45920  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
45921  sqlite3Error(p->pDestDb, rc, 0);
45922
45923  /* Exit the mutexes and free the backup context structure. */
45924  if( p->pDestDb ){
45925    sqlite3_mutex_leave(p->pDestDb->mutex);
45926  }
45927  sqlite3BtreeLeave(p->pSrc);
45928  if( p->pDestDb ){
45929    sqlite3_free(p);
45930  }
45931  sqlite3_mutex_leave(mutex);
45932  return rc;
45933}
45934
45935/*
45936** Return the number of pages still to be backed up as of the most recent
45937** call to sqlite3_backup_step().
45938*/
45939SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
45940  return p->nRemaining;
45941}
45942
45943/*
45944** Return the total number of pages in the source database as of the most
45945** recent call to sqlite3_backup_step().
45946*/
45947SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
45948  return p->nPagecount;
45949}
45950
45951/*
45952** This function is called after the contents of page iPage of the
45953** source database have been modified. If page iPage has already been
45954** copied into the destination database, then the data written to the
45955** destination is now invalidated. The destination copy of iPage needs
45956** to be updated with the new data before the backup operation is
45957** complete.
45958**
45959** It is assumed that the mutex associated with the BtShared object
45960** corresponding to the source database is held when this function is
45961** called.
45962*/
45963SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
45964  sqlite3_backup *p;                   /* Iterator variable */
45965  for(p=pBackup; p; p=p->pNext){
45966    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
45967    if( !isFatalError(p->rc) && iPage<p->iNext ){
45968      /* The backup process p has already copied page iPage. But now it
45969      ** has been modified by a transaction on the source pager. Copy
45970      ** the new data into the backup.
45971      */
45972      int rc = backupOnePage(p, iPage, aData);
45973      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
45974      if( rc!=SQLITE_OK ){
45975        p->rc = rc;
45976      }
45977    }
45978  }
45979}
45980
45981/*
45982** Restart the backup process. This is called when the pager layer
45983** detects that the database has been modified by an external database
45984** connection. In this case there is no way of knowing which of the
45985** pages that have been copied into the destination database are still
45986** valid and which are not, so the entire process needs to be restarted.
45987**
45988** It is assumed that the mutex associated with the BtShared object
45989** corresponding to the source database is held when this function is
45990** called.
45991*/
45992SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
45993  sqlite3_backup *p;                   /* Iterator variable */
45994  for(p=pBackup; p; p=p->pNext){
45995    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
45996    p->iNext = 1;
45997  }
45998}
45999
46000#ifndef SQLITE_OMIT_VACUUM
46001/*
46002** Copy the complete content of pBtFrom into pBtTo.  A transaction
46003** must be active for both files.
46004**
46005** The size of file pTo may be reduced by this operation. If anything
46006** goes wrong, the transaction on pTo is rolled back. If successful, the
46007** transaction is committed before returning.
46008*/
46009SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
46010  int rc;
46011  sqlite3_backup b;
46012  sqlite3BtreeEnter(pTo);
46013  sqlite3BtreeEnter(pFrom);
46014
46015  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
46016  ** to 0. This is used by the implementations of sqlite3_backup_step()
46017  ** and sqlite3_backup_finish() to detect that they are being called
46018  ** from this function, not directly by the user.
46019  */
46020  memset(&b, 0, sizeof(b));
46021  b.pSrcDb = pFrom->db;
46022  b.pSrc = pFrom;
46023  b.pDest = pTo;
46024  b.iNext = 1;
46025
46026  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
46027  ** file. By passing this as the number of pages to copy to
46028  ** sqlite3_backup_step(), we can guarantee that the copy finishes
46029  ** within a single call (unless an error occurs). The assert() statement
46030  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
46031  ** or an error code.
46032  */
46033  sqlite3_backup_step(&b, 0x7FFFFFFF);
46034  assert( b.rc!=SQLITE_OK );
46035  rc = sqlite3_backup_finish(&b);
46036  if( rc==SQLITE_OK ){
46037    pTo->pBt->pageSizeFixed = 0;
46038  }
46039
46040  sqlite3BtreeLeave(pFrom);
46041  sqlite3BtreeLeave(pTo);
46042  return rc;
46043}
46044#endif /* SQLITE_OMIT_VACUUM */
46045
46046/************** End of backup.c **********************************************/
46047/************** Begin file vdbemem.c *****************************************/
46048/*
46049** 2004 May 26
46050**
46051** The author disclaims copyright to this source code.  In place of
46052** a legal notice, here is a blessing:
46053**
46054**    May you do good and not evil.
46055**    May you find forgiveness for yourself and forgive others.
46056**    May you share freely, never taking more than you give.
46057**
46058*************************************************************************
46059**
46060** This file contains code use to manipulate "Mem" structure.  A "Mem"
46061** stores a single value in the VDBE.  Mem is an opaque structure visible
46062** only within the VDBE.  Interface routines refer to a Mem using the
46063** name sqlite_value
46064*/
46065
46066/*
46067** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
46068** P if required.
46069*/
46070#define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
46071
46072/*
46073** If pMem is an object with a valid string representation, this routine
46074** ensures the internal encoding for the string representation is
46075** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
46076**
46077** If pMem is not a string object, or the encoding of the string
46078** representation is already stored using the requested encoding, then this
46079** routine is a no-op.
46080**
46081** SQLITE_OK is returned if the conversion is successful (or not required).
46082** SQLITE_NOMEM may be returned if a malloc() fails during conversion
46083** between formats.
46084*/
46085SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
46086  int rc;
46087  assert( (pMem->flags&MEM_RowSet)==0 );
46088  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
46089           || desiredEnc==SQLITE_UTF16BE );
46090  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
46091    return SQLITE_OK;
46092  }
46093  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46094#ifdef SQLITE_OMIT_UTF16
46095  return SQLITE_ERROR;
46096#else
46097
46098  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
46099  ** then the encoding of the value may not have changed.
46100  */
46101  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
46102  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
46103  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
46104  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
46105  return rc;
46106#endif
46107}
46108
46109/*
46110** Make sure pMem->z points to a writable allocation of at least
46111** n bytes.
46112**
46113** If the memory cell currently contains string or blob data
46114** and the third argument passed to this function is true, the
46115** current content of the cell is preserved. Otherwise, it may
46116** be discarded.
46117**
46118** This function sets the MEM_Dyn flag and clears any xDel callback.
46119** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
46120** not set, Mem.n is zeroed.
46121*/
46122SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
46123  assert( 1 >=
46124    ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
46125    (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
46126    ((pMem->flags&MEM_Ephem) ? 1 : 0) +
46127    ((pMem->flags&MEM_Static) ? 1 : 0)
46128  );
46129  assert( (pMem->flags&MEM_RowSet)==0 );
46130
46131  if( n<32 ) n = 32;
46132  if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
46133    if( preserve && pMem->z==pMem->zMalloc ){
46134      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
46135      preserve = 0;
46136    }else{
46137      sqlite3DbFree(pMem->db, pMem->zMalloc);
46138      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
46139    }
46140  }
46141
46142  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
46143    memcpy(pMem->zMalloc, pMem->z, pMem->n);
46144  }
46145  if( pMem->flags&MEM_Dyn && pMem->xDel ){
46146    pMem->xDel((void *)(pMem->z));
46147  }
46148
46149  pMem->z = pMem->zMalloc;
46150  if( pMem->z==0 ){
46151    pMem->flags = MEM_Null;
46152  }else{
46153    pMem->flags &= ~(MEM_Ephem|MEM_Static);
46154  }
46155  pMem->xDel = 0;
46156  return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
46157}
46158
46159/*
46160** Make the given Mem object MEM_Dyn.  In other words, make it so
46161** that any TEXT or BLOB content is stored in memory obtained from
46162** malloc().  In this way, we know that the memory is safe to be
46163** overwritten or altered.
46164**
46165** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
46166*/
46167SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
46168  int f;
46169  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46170  assert( (pMem->flags&MEM_RowSet)==0 );
46171  expandBlob(pMem);
46172  f = pMem->flags;
46173  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
46174    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
46175      return SQLITE_NOMEM;
46176    }
46177    pMem->z[pMem->n] = 0;
46178    pMem->z[pMem->n+1] = 0;
46179    pMem->flags |= MEM_Term;
46180  }
46181
46182  return SQLITE_OK;
46183}
46184
46185/*
46186** If the given Mem* has a zero-filled tail, turn it into an ordinary
46187** blob stored in dynamically allocated space.
46188*/
46189#ifndef SQLITE_OMIT_INCRBLOB
46190SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
46191  if( pMem->flags & MEM_Zero ){
46192    int nByte;
46193    assert( pMem->flags&MEM_Blob );
46194    assert( (pMem->flags&MEM_RowSet)==0 );
46195    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46196
46197    /* Set nByte to the number of bytes required to store the expanded blob. */
46198    nByte = pMem->n + pMem->u.nZero;
46199    if( nByte<=0 ){
46200      nByte = 1;
46201    }
46202    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
46203      return SQLITE_NOMEM;
46204    }
46205
46206    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
46207    pMem->n += pMem->u.nZero;
46208    pMem->flags &= ~(MEM_Zero|MEM_Term);
46209  }
46210  return SQLITE_OK;
46211}
46212#endif
46213
46214
46215/*
46216** Make sure the given Mem is \u0000 terminated.
46217*/
46218SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
46219  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46220  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
46221    return SQLITE_OK;   /* Nothing to do */
46222  }
46223  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
46224    return SQLITE_NOMEM;
46225  }
46226  pMem->z[pMem->n] = 0;
46227  pMem->z[pMem->n+1] = 0;
46228  pMem->flags |= MEM_Term;
46229  return SQLITE_OK;
46230}
46231
46232/*
46233** Add MEM_Str to the set of representations for the given Mem.  Numbers
46234** are converted using sqlite3_snprintf().  Converting a BLOB to a string
46235** is a no-op.
46236**
46237** Existing representations MEM_Int and MEM_Real are *not* invalidated.
46238**
46239** A MEM_Null value will never be passed to this function. This function is
46240** used for converting values to text for returning to the user (i.e. via
46241** sqlite3_value_text()), or for ensuring that values to be used as btree
46242** keys are strings. In the former case a NULL pointer is returned the
46243** user and the later is an internal programming error.
46244*/
46245SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
46246  int rc = SQLITE_OK;
46247  int fg = pMem->flags;
46248  const int nByte = 32;
46249
46250  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46251  assert( !(fg&MEM_Zero) );
46252  assert( !(fg&(MEM_Str|MEM_Blob)) );
46253  assert( fg&(MEM_Int|MEM_Real) );
46254  assert( (pMem->flags&MEM_RowSet)==0 );
46255  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46256
46257
46258  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
46259    return SQLITE_NOMEM;
46260  }
46261
46262  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
46263  ** string representation of the value. Then, if the required encoding
46264  ** is UTF-16le or UTF-16be do a translation.
46265  **
46266  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
46267  */
46268  if( fg & MEM_Int ){
46269    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
46270  }else{
46271    assert( fg & MEM_Real );
46272    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
46273  }
46274  pMem->n = sqlite3Strlen30(pMem->z);
46275  pMem->enc = SQLITE_UTF8;
46276  pMem->flags |= MEM_Str|MEM_Term;
46277  sqlite3VdbeChangeEncoding(pMem, enc);
46278  return rc;
46279}
46280
46281/*
46282** Memory cell pMem contains the context of an aggregate function.
46283** This routine calls the finalize method for that function.  The
46284** result of the aggregate is stored back into pMem.
46285**
46286** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
46287** otherwise.
46288*/
46289SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
46290  int rc = SQLITE_OK;
46291  if( ALWAYS(pFunc && pFunc->xFinalize) ){
46292    sqlite3_context ctx;
46293    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
46294    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46295    memset(&ctx, 0, sizeof(ctx));
46296    ctx.s.flags = MEM_Null;
46297    ctx.s.db = pMem->db;
46298    ctx.pMem = pMem;
46299    ctx.pFunc = pFunc;
46300    pFunc->xFinalize(&ctx);
46301    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
46302    sqlite3DbFree(pMem->db, pMem->zMalloc);
46303    memcpy(pMem, &ctx.s, sizeof(ctx.s));
46304    rc = ctx.isError;
46305  }
46306  return rc;
46307}
46308
46309/*
46310** If the memory cell contains a string value that must be freed by
46311** invoking an external callback, free it now. Calling this function
46312** does not free any Mem.zMalloc buffer.
46313*/
46314SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
46315  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
46316  testcase( p->flags & MEM_Agg );
46317  testcase( p->flags & MEM_Dyn );
46318  testcase( p->flags & MEM_RowSet );
46319  testcase( p->flags & MEM_Frame );
46320  if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
46321    if( p->flags&MEM_Agg ){
46322      sqlite3VdbeMemFinalize(p, p->u.pDef);
46323      assert( (p->flags & MEM_Agg)==0 );
46324      sqlite3VdbeMemRelease(p);
46325    }else if( p->flags&MEM_Dyn && p->xDel ){
46326      assert( (p->flags&MEM_RowSet)==0 );
46327      p->xDel((void *)p->z);
46328      p->xDel = 0;
46329    }else if( p->flags&MEM_RowSet ){
46330      sqlite3RowSetClear(p->u.pRowSet);
46331    }else if( p->flags&MEM_Frame ){
46332      sqlite3VdbeMemSetNull(p);
46333    }
46334  }
46335}
46336
46337/*
46338** Release any memory held by the Mem. This may leave the Mem in an
46339** inconsistent state, for example with (Mem.z==0) and
46340** (Mem.type==SQLITE_TEXT).
46341*/
46342SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
46343  sqlite3VdbeMemReleaseExternal(p);
46344  sqlite3DbFree(p->db, p->zMalloc);
46345  p->z = 0;
46346  p->zMalloc = 0;
46347  p->xDel = 0;
46348}
46349
46350/*
46351** Convert a 64-bit IEEE double into a 64-bit signed integer.
46352** If the double is too large, return 0x8000000000000000.
46353**
46354** Most systems appear to do this simply by assigning
46355** variables and without the extra range tests.  But
46356** there are reports that windows throws an expection
46357** if the floating point value is out of range. (See ticket #2880.)
46358** Because we do not completely understand the problem, we will
46359** take the conservative approach and always do range tests
46360** before attempting the conversion.
46361*/
46362static i64 doubleToInt64(double r){
46363  /*
46364  ** Many compilers we encounter do not define constants for the
46365  ** minimum and maximum 64-bit integers, or they define them
46366  ** inconsistently.  And many do not understand the "LL" notation.
46367  ** So we define our own static constants here using nothing
46368  ** larger than a 32-bit integer constant.
46369  */
46370  static const i64 maxInt = LARGEST_INT64;
46371  static const i64 minInt = SMALLEST_INT64;
46372
46373  if( r<(double)minInt ){
46374    return minInt;
46375  }else if( r>(double)maxInt ){
46376    /* minInt is correct here - not maxInt.  It turns out that assigning
46377    ** a very large positive number to an integer results in a very large
46378    ** negative integer.  This makes no sense, but it is what x86 hardware
46379    ** does so for compatibility we will do the same in software. */
46380    return minInt;
46381  }else{
46382    return (i64)r;
46383  }
46384}
46385
46386/*
46387** Return some kind of integer value which is the best we can do
46388** at representing the value that *pMem describes as an integer.
46389** If pMem is an integer, then the value is exact.  If pMem is
46390** a floating-point then the value returned is the integer part.
46391** If pMem is a string or blob, then we make an attempt to convert
46392** it into a integer and return that.  If pMem represents an
46393** an SQL-NULL value, return 0.
46394**
46395** If pMem represents a string value, its encoding might be changed.
46396*/
46397SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
46398  int flags;
46399  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46400  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46401  flags = pMem->flags;
46402  if( flags & MEM_Int ){
46403    return pMem->u.i;
46404  }else if( flags & MEM_Real ){
46405    return doubleToInt64(pMem->r);
46406  }else if( flags & (MEM_Str|MEM_Blob) ){
46407    i64 value;
46408    pMem->flags |= MEM_Str;
46409    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
46410       || sqlite3VdbeMemNulTerminate(pMem) ){
46411      return 0;
46412    }
46413    assert( pMem->z );
46414    sqlite3Atoi64(pMem->z, &value);
46415    return value;
46416  }else{
46417    return 0;
46418  }
46419}
46420
46421/*
46422** Return the best representation of pMem that we can get into a
46423** double.  If pMem is already a double or an integer, return its
46424** value.  If it is a string or blob, try to convert it to a double.
46425** If it is a NULL, return 0.0.
46426*/
46427SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
46428  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46429  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46430  if( pMem->flags & MEM_Real ){
46431    return pMem->r;
46432  }else if( pMem->flags & MEM_Int ){
46433    return (double)pMem->u.i;
46434  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
46435    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46436    double val = (double)0;
46437    pMem->flags |= MEM_Str;
46438    if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
46439       || sqlite3VdbeMemNulTerminate(pMem) ){
46440      /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46441      return (double)0;
46442    }
46443    assert( pMem->z );
46444    sqlite3AtoF(pMem->z, &val);
46445    return val;
46446  }else{
46447    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
46448    return (double)0;
46449  }
46450}
46451
46452/*
46453** The MEM structure is already a MEM_Real.  Try to also make it a
46454** MEM_Int if we can.
46455*/
46456SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
46457  assert( pMem->flags & MEM_Real );
46458  assert( (pMem->flags & MEM_RowSet)==0 );
46459  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46460  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46461
46462  pMem->u.i = doubleToInt64(pMem->r);
46463
46464  /* Only mark the value as an integer if
46465  **
46466  **    (1) the round-trip conversion real->int->real is a no-op, and
46467  **    (2) The integer is neither the largest nor the smallest
46468  **        possible integer (ticket #3922)
46469  **
46470  ** The second and third terms in the following conditional enforces
46471  ** the second condition under the assumption that addition overflow causes
46472  ** values to wrap around.  On x86 hardware, the third term is always
46473  ** true and could be omitted.  But we leave it in because other
46474  ** architectures might behave differently.
46475  */
46476  if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
46477      && ALWAYS(pMem->u.i<LARGEST_INT64) ){
46478    pMem->flags |= MEM_Int;
46479  }
46480}
46481
46482/*
46483** Convert pMem to type integer.  Invalidate any prior representations.
46484*/
46485SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
46486  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46487  assert( (pMem->flags & MEM_RowSet)==0 );
46488  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46489
46490  pMem->u.i = sqlite3VdbeIntValue(pMem);
46491  MemSetTypeFlag(pMem, MEM_Int);
46492  return SQLITE_OK;
46493}
46494
46495/*
46496** Convert pMem so that it is of type MEM_Real.
46497** Invalidate any prior representations.
46498*/
46499SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
46500  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46501  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
46502
46503  pMem->r = sqlite3VdbeRealValue(pMem);
46504  MemSetTypeFlag(pMem, MEM_Real);
46505  return SQLITE_OK;
46506}
46507
46508/*
46509** Convert pMem so that it has types MEM_Real or MEM_Int or both.
46510** Invalidate any prior representations.
46511*/
46512SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
46513  double r1, r2;
46514  i64 i;
46515  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
46516  assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
46517  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46518  r1 = sqlite3VdbeRealValue(pMem);
46519  i = doubleToInt64(r1);
46520  r2 = (double)i;
46521  if( r1==r2 ){
46522    sqlite3VdbeMemIntegerify(pMem);
46523  }else{
46524    pMem->r = r1;
46525    MemSetTypeFlag(pMem, MEM_Real);
46526  }
46527  return SQLITE_OK;
46528}
46529
46530/*
46531** Delete any previous value and set the value stored in *pMem to NULL.
46532*/
46533SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
46534  if( pMem->flags & MEM_Frame ){
46535    sqlite3VdbeFrameDelete(pMem->u.pFrame);
46536  }
46537  if( pMem->flags & MEM_RowSet ){
46538    sqlite3RowSetClear(pMem->u.pRowSet);
46539  }
46540  MemSetTypeFlag(pMem, MEM_Null);
46541  pMem->type = SQLITE_NULL;
46542}
46543
46544/*
46545** Delete any previous value and set the value to be a BLOB of length
46546** n containing all zeros.
46547*/
46548SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
46549  sqlite3VdbeMemRelease(pMem);
46550  pMem->flags = MEM_Blob|MEM_Zero;
46551  pMem->type = SQLITE_BLOB;
46552  pMem->n = 0;
46553  if( n<0 ) n = 0;
46554  pMem->u.nZero = n;
46555  pMem->enc = SQLITE_UTF8;
46556
46557#ifdef SQLITE_OMIT_INCRBLOB
46558  sqlite3VdbeMemGrow(pMem, n, 0);
46559  if( pMem->z ){
46560    pMem->n = n;
46561    memset(pMem->z, 0, n);
46562  }
46563#endif
46564}
46565
46566/*
46567** Delete any previous value and set the value stored in *pMem to val,
46568** manifest type INTEGER.
46569*/
46570SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
46571  sqlite3VdbeMemRelease(pMem);
46572  pMem->u.i = val;
46573  pMem->flags = MEM_Int;
46574  pMem->type = SQLITE_INTEGER;
46575}
46576
46577/*
46578** Delete any previous value and set the value stored in *pMem to val,
46579** manifest type REAL.
46580*/
46581SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
46582  if( sqlite3IsNaN(val) ){
46583    sqlite3VdbeMemSetNull(pMem);
46584  }else{
46585    sqlite3VdbeMemRelease(pMem);
46586    pMem->r = val;
46587    pMem->flags = MEM_Real;
46588    pMem->type = SQLITE_FLOAT;
46589  }
46590}
46591
46592/*
46593** Delete any previous value and set the value of pMem to be an
46594** empty boolean index.
46595*/
46596SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
46597  sqlite3 *db = pMem->db;
46598  assert( db!=0 );
46599  assert( (pMem->flags & MEM_RowSet)==0 );
46600  sqlite3VdbeMemRelease(pMem);
46601  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
46602  if( db->mallocFailed ){
46603    pMem->flags = MEM_Null;
46604  }else{
46605    assert( pMem->zMalloc );
46606    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
46607                                       sqlite3DbMallocSize(db, pMem->zMalloc));
46608    assert( pMem->u.pRowSet!=0 );
46609    pMem->flags = MEM_RowSet;
46610  }
46611}
46612
46613/*
46614** Return true if the Mem object contains a TEXT or BLOB that is
46615** too large - whose size exceeds SQLITE_MAX_LENGTH.
46616*/
46617SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
46618  assert( p->db!=0 );
46619  if( p->flags & (MEM_Str|MEM_Blob) ){
46620    int n = p->n;
46621    if( p->flags & MEM_Zero ){
46622      n += p->u.nZero;
46623    }
46624    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
46625  }
46626  return 0;
46627}
46628
46629/*
46630** Size of struct Mem not including the Mem.zMalloc member.
46631*/
46632#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
46633
46634/*
46635** Make an shallow copy of pFrom into pTo.  Prior contents of
46636** pTo are freed.  The pFrom->z field is not duplicated.  If
46637** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
46638** and flags gets srcType (either MEM_Ephem or MEM_Static).
46639*/
46640SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
46641  assert( (pFrom->flags & MEM_RowSet)==0 );
46642  sqlite3VdbeMemReleaseExternal(pTo);
46643  memcpy(pTo, pFrom, MEMCELLSIZE);
46644  pTo->xDel = 0;
46645  if( (pFrom->flags&MEM_Dyn)!=0 || pFrom->z==pFrom->zMalloc ){
46646    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
46647    assert( srcType==MEM_Ephem || srcType==MEM_Static );
46648    pTo->flags |= srcType;
46649  }
46650}
46651
46652/*
46653** Make a full copy of pFrom into pTo.  Prior contents of pTo are
46654** freed before the copy is made.
46655*/
46656SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
46657  int rc = SQLITE_OK;
46658
46659  assert( (pFrom->flags & MEM_RowSet)==0 );
46660  sqlite3VdbeMemReleaseExternal(pTo);
46661  memcpy(pTo, pFrom, MEMCELLSIZE);
46662  pTo->flags &= ~MEM_Dyn;
46663
46664  if( pTo->flags&(MEM_Str|MEM_Blob) ){
46665    if( 0==(pFrom->flags&MEM_Static) ){
46666      pTo->flags |= MEM_Ephem;
46667      rc = sqlite3VdbeMemMakeWriteable(pTo);
46668    }
46669  }
46670
46671  return rc;
46672}
46673
46674/*
46675** Transfer the contents of pFrom to pTo. Any existing value in pTo is
46676** freed. If pFrom contains ephemeral data, a copy is made.
46677**
46678** pFrom contains an SQL NULL when this routine returns.
46679*/
46680SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
46681  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
46682  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
46683  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
46684
46685  sqlite3VdbeMemRelease(pTo);
46686  memcpy(pTo, pFrom, sizeof(Mem));
46687  pFrom->flags = MEM_Null;
46688  pFrom->xDel = 0;
46689  pFrom->zMalloc = 0;
46690}
46691
46692/*
46693** Change the value of a Mem to be a string or a BLOB.
46694**
46695** The memory management strategy depends on the value of the xDel
46696** parameter. If the value passed is SQLITE_TRANSIENT, then the
46697** string is copied into a (possibly existing) buffer managed by the
46698** Mem structure. Otherwise, any existing buffer is freed and the
46699** pointer copied.
46700**
46701** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
46702** size limit) then no memory allocation occurs.  If the string can be
46703** stored without allocating memory, then it is.  If a memory allocation
46704** is required to store the string, then value of pMem is unchanged.  In
46705** either case, SQLITE_TOOBIG is returned.
46706*/
46707SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
46708  Mem *pMem,          /* Memory cell to set to string value */
46709  const char *z,      /* String pointer */
46710  int n,              /* Bytes in string, or negative */
46711  u8 enc,             /* Encoding of z.  0 for BLOBs */
46712  void (*xDel)(void*) /* Destructor function */
46713){
46714  int nByte = n;      /* New value for pMem->n */
46715  int iLimit;         /* Maximum allowed string or blob size */
46716  u16 flags = 0;      /* New value for pMem->flags */
46717
46718  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
46719  assert( (pMem->flags & MEM_RowSet)==0 );
46720
46721  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
46722  if( !z ){
46723    sqlite3VdbeMemSetNull(pMem);
46724    return SQLITE_OK;
46725  }
46726
46727  if( pMem->db ){
46728    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
46729  }else{
46730    iLimit = SQLITE_MAX_LENGTH;
46731  }
46732  flags = (enc==0?MEM_Blob:MEM_Str);
46733  if( nByte<0 ){
46734    assert( enc!=0 );
46735    if( enc==SQLITE_UTF8 ){
46736      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
46737    }else{
46738      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
46739    }
46740    flags |= MEM_Term;
46741  }
46742
46743  /* The following block sets the new values of Mem.z and Mem.xDel. It
46744  ** also sets a flag in local variable "flags" to indicate the memory
46745  ** management (one of MEM_Dyn or MEM_Static).
46746  */
46747  if( xDel==SQLITE_TRANSIENT ){
46748    int nAlloc = nByte;
46749    if( flags&MEM_Term ){
46750      nAlloc += (enc==SQLITE_UTF8?1:2);
46751    }
46752    if( nByte>iLimit ){
46753      return SQLITE_TOOBIG;
46754    }
46755    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
46756      return SQLITE_NOMEM;
46757    }
46758    memcpy(pMem->z, z, nAlloc);
46759  }else if( xDel==SQLITE_DYNAMIC ){
46760    sqlite3VdbeMemRelease(pMem);
46761    pMem->zMalloc = pMem->z = (char *)z;
46762    pMem->xDel = 0;
46763  }else{
46764    sqlite3VdbeMemRelease(pMem);
46765    pMem->z = (char *)z;
46766    pMem->xDel = xDel;
46767    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
46768  }
46769
46770  pMem->n = nByte;
46771  pMem->flags = flags;
46772  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
46773  pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
46774
46775#ifndef SQLITE_OMIT_UTF16
46776  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
46777    return SQLITE_NOMEM;
46778  }
46779#endif
46780
46781  if( nByte>iLimit ){
46782    return SQLITE_TOOBIG;
46783  }
46784
46785  return SQLITE_OK;
46786}
46787
46788/*
46789** Compare the values contained by the two memory cells, returning
46790** negative, zero or positive if pMem1 is less than, equal to, or greater
46791** than pMem2. Sorting order is NULL's first, followed by numbers (integers
46792** and reals) sorted numerically, followed by text ordered by the collating
46793** sequence pColl and finally blob's ordered by memcmp().
46794**
46795** Two NULL values are considered equal by this function.
46796*/
46797SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
46798  int rc;
46799  int f1, f2;
46800  int combined_flags;
46801
46802  f1 = pMem1->flags;
46803  f2 = pMem2->flags;
46804  combined_flags = f1|f2;
46805  assert( (combined_flags & MEM_RowSet)==0 );
46806
46807  /* If one value is NULL, it is less than the other. If both values
46808  ** are NULL, return 0.
46809  */
46810  if( combined_flags&MEM_Null ){
46811    return (f2&MEM_Null) - (f1&MEM_Null);
46812  }
46813
46814  /* If one value is a number and the other is not, the number is less.
46815  ** If both are numbers, compare as reals if one is a real, or as integers
46816  ** if both values are integers.
46817  */
46818  if( combined_flags&(MEM_Int|MEM_Real) ){
46819    if( !(f1&(MEM_Int|MEM_Real)) ){
46820      return 1;
46821    }
46822    if( !(f2&(MEM_Int|MEM_Real)) ){
46823      return -1;
46824    }
46825    if( (f1 & f2 & MEM_Int)==0 ){
46826      double r1, r2;
46827      if( (f1&MEM_Real)==0 ){
46828        r1 = (double)pMem1->u.i;
46829      }else{
46830        r1 = pMem1->r;
46831      }
46832      if( (f2&MEM_Real)==0 ){
46833        r2 = (double)pMem2->u.i;
46834      }else{
46835        r2 = pMem2->r;
46836      }
46837      if( r1<r2 ) return -1;
46838      if( r1>r2 ) return 1;
46839      return 0;
46840    }else{
46841      assert( f1&MEM_Int );
46842      assert( f2&MEM_Int );
46843      if( pMem1->u.i < pMem2->u.i ) return -1;
46844      if( pMem1->u.i > pMem2->u.i ) return 1;
46845      return 0;
46846    }
46847  }
46848
46849  /* If one value is a string and the other is a blob, the string is less.
46850  ** If both are strings, compare using the collating functions.
46851  */
46852  if( combined_flags&MEM_Str ){
46853    if( (f1 & MEM_Str)==0 ){
46854      return 1;
46855    }
46856    if( (f2 & MEM_Str)==0 ){
46857      return -1;
46858    }
46859
46860    assert( pMem1->enc==pMem2->enc );
46861    assert( pMem1->enc==SQLITE_UTF8 ||
46862            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
46863
46864    /* The collation sequence must be defined at this point, even if
46865    ** the user deletes the collation sequence after the vdbe program is
46866    ** compiled (this was not always the case).
46867    */
46868    assert( !pColl || pColl->xCmp );
46869
46870    if( pColl ){
46871      if( pMem1->enc==pColl->enc ){
46872        /* The strings are already in the correct encoding.  Call the
46873        ** comparison function directly */
46874        return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
46875      }else{
46876        const void *v1, *v2;
46877        int n1, n2;
46878        Mem c1;
46879        Mem c2;
46880        memset(&c1, 0, sizeof(c1));
46881        memset(&c2, 0, sizeof(c2));
46882        sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
46883        sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
46884        v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
46885        n1 = v1==0 ? 0 : c1.n;
46886        v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
46887        n2 = v2==0 ? 0 : c2.n;
46888        rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
46889        sqlite3VdbeMemRelease(&c1);
46890        sqlite3VdbeMemRelease(&c2);
46891        return rc;
46892      }
46893    }
46894    /* If a NULL pointer was passed as the collate function, fall through
46895    ** to the blob case and use memcmp().  */
46896  }
46897
46898  /* Both values must be blobs.  Compare using memcmp().  */
46899  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
46900  if( rc==0 ){
46901    rc = pMem1->n - pMem2->n;
46902  }
46903  return rc;
46904}
46905
46906/*
46907** Move data out of a btree key or data field and into a Mem structure.
46908** The data or key is taken from the entry that pCur is currently pointing
46909** to.  offset and amt determine what portion of the data or key to retrieve.
46910** key is true to get the key or false to get data.  The result is written
46911** into the pMem element.
46912**
46913** The pMem structure is assumed to be uninitialized.  Any prior content
46914** is overwritten without being freed.
46915**
46916** If this routine fails for any reason (malloc returns NULL or unable
46917** to read from the disk) then the pMem is left in an inconsistent state.
46918*/
46919SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
46920  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
46921  int offset,       /* Offset from the start of data to return bytes from. */
46922  int amt,          /* Number of bytes to return. */
46923  int key,          /* If true, retrieve from the btree key, not data. */
46924  Mem *pMem         /* OUT: Return data in this Mem structure. */
46925){
46926  char *zData;        /* Data from the btree layer */
46927  int available = 0;  /* Number of bytes available on the local btree page */
46928  int rc = SQLITE_OK; /* Return code */
46929
46930  assert( sqlite3BtreeCursorIsValid(pCur) );
46931
46932  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
46933  ** that both the BtShared and database handle mutexes are held. */
46934  assert( (pMem->flags & MEM_RowSet)==0 );
46935  if( key ){
46936    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
46937  }else{
46938    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
46939  }
46940  assert( zData!=0 );
46941
46942  if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
46943    sqlite3VdbeMemRelease(pMem);
46944    pMem->z = &zData[offset];
46945    pMem->flags = MEM_Blob|MEM_Ephem;
46946  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
46947    pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
46948    pMem->enc = 0;
46949    pMem->type = SQLITE_BLOB;
46950    if( key ){
46951      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
46952    }else{
46953      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
46954    }
46955    pMem->z[amt] = 0;
46956    pMem->z[amt+1] = 0;
46957    if( rc!=SQLITE_OK ){
46958      sqlite3VdbeMemRelease(pMem);
46959    }
46960  }
46961  pMem->n = amt;
46962
46963  return rc;
46964}
46965
46966/* This function is only available internally, it is not part of the
46967** external API. It works in a similar way to sqlite3_value_text(),
46968** except the data returned is in the encoding specified by the second
46969** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
46970** SQLITE_UTF8.
46971**
46972** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
46973** If that is the case, then the result must be aligned on an even byte
46974** boundary.
46975*/
46976SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
46977  if( !pVal ) return 0;
46978
46979  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
46980  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
46981  assert( (pVal->flags & MEM_RowSet)==0 );
46982
46983  if( pVal->flags&MEM_Null ){
46984    return 0;
46985  }
46986  assert( (MEM_Blob>>3) == MEM_Str );
46987  pVal->flags |= (pVal->flags & MEM_Blob)>>3;
46988  expandBlob(pVal);
46989  if( pVal->flags&MEM_Str ){
46990    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
46991    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
46992      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
46993      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
46994        return 0;
46995      }
46996    }
46997    sqlite3VdbeMemNulTerminate(pVal);
46998  }else{
46999    assert( (pVal->flags&MEM_Blob)==0 );
47000    sqlite3VdbeMemStringify(pVal, enc);
47001    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
47002  }
47003  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
47004              || pVal->db->mallocFailed );
47005  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
47006    return pVal->z;
47007  }else{
47008    return 0;
47009  }
47010}
47011
47012/*
47013** Create a new sqlite3_value object.
47014*/
47015SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
47016  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
47017  if( p ){
47018    p->flags = MEM_Null;
47019    p->type = SQLITE_NULL;
47020    p->db = db;
47021  }
47022  return p;
47023}
47024
47025/*
47026** Create a new sqlite3_value object, containing the value of pExpr.
47027**
47028** This only works for very simple expressions that consist of one constant
47029** token (i.e. "5", "5.1", "'a string'"). If the expression can
47030** be converted directly into a value, then the value is allocated and
47031** a pointer written to *ppVal. The caller is responsible for deallocating
47032** the value by passing it to sqlite3ValueFree() later on. If the expression
47033** cannot be converted to a value, then *ppVal is set to NULL.
47034*/
47035SQLITE_PRIVATE int sqlite3ValueFromExpr(
47036  sqlite3 *db,              /* The database connection */
47037  Expr *pExpr,              /* The expression to evaluate */
47038  u8 enc,                   /* Encoding to use */
47039  u8 affinity,              /* Affinity to use */
47040  sqlite3_value **ppVal     /* Write the new value here */
47041){
47042  int op;
47043  char *zVal = 0;
47044  sqlite3_value *pVal = 0;
47045
47046  if( !pExpr ){
47047    *ppVal = 0;
47048    return SQLITE_OK;
47049  }
47050  op = pExpr->op;
47051  if( op==TK_REGISTER ){
47052    op = pExpr->op2;  /* This only happens with SQLITE_ENABLE_STAT2 */
47053  }
47054
47055  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
47056    pVal = sqlite3ValueNew(db);
47057    if( pVal==0 ) goto no_mem;
47058    if( ExprHasProperty(pExpr, EP_IntValue) ){
47059      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue);
47060    }else{
47061      zVal = sqlite3DbStrDup(db, pExpr->u.zToken);
47062      if( zVal==0 ) goto no_mem;
47063      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
47064      if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
47065    }
47066    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
47067      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
47068    }else{
47069      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
47070    }
47071    if( enc!=SQLITE_UTF8 ){
47072      sqlite3VdbeChangeEncoding(pVal, enc);
47073    }
47074  }else if( op==TK_UMINUS ) {
47075    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
47076      pVal->u.i = -1 * pVal->u.i;
47077      /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
47078      pVal->r = (double)-1 * pVal->r;
47079    }
47080  }
47081#ifndef SQLITE_OMIT_BLOB_LITERAL
47082  else if( op==TK_BLOB ){
47083    int nVal;
47084    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
47085    assert( pExpr->u.zToken[1]=='\'' );
47086    pVal = sqlite3ValueNew(db);
47087    if( !pVal ) goto no_mem;
47088    zVal = &pExpr->u.zToken[2];
47089    nVal = sqlite3Strlen30(zVal)-1;
47090    assert( zVal[nVal]=='\'' );
47091    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
47092                         0, SQLITE_DYNAMIC);
47093  }
47094#endif
47095
47096  if( pVal ){
47097    sqlite3VdbeMemStoreType(pVal);
47098  }
47099  *ppVal = pVal;
47100  return SQLITE_OK;
47101
47102no_mem:
47103  db->mallocFailed = 1;
47104  sqlite3DbFree(db, zVal);
47105  sqlite3ValueFree(pVal);
47106  *ppVal = 0;
47107  return SQLITE_NOMEM;
47108}
47109
47110/*
47111** Change the string value of an sqlite3_value object
47112*/
47113SQLITE_PRIVATE void sqlite3ValueSetStr(
47114  sqlite3_value *v,     /* Value to be set */
47115  int n,                /* Length of string z */
47116  const void *z,        /* Text of the new string */
47117  u8 enc,               /* Encoding to use */
47118  void (*xDel)(void*)   /* Destructor for the string */
47119){
47120  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
47121}
47122
47123/*
47124** Free an sqlite3_value object
47125*/
47126SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
47127  if( !v ) return;
47128  sqlite3VdbeMemRelease((Mem *)v);
47129  sqlite3DbFree(((Mem*)v)->db, v);
47130}
47131
47132/*
47133** Return the number of bytes in the sqlite3_value object assuming
47134** that it uses the encoding "enc"
47135*/
47136SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
47137  Mem *p = (Mem*)pVal;
47138  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
47139    if( p->flags & MEM_Zero ){
47140      return p->n + p->u.nZero;
47141    }else{
47142      return p->n;
47143    }
47144  }
47145  return 0;
47146}
47147
47148/************** End of vdbemem.c *********************************************/
47149/************** Begin file vdbeaux.c *****************************************/
47150/*
47151** 2003 September 6
47152**
47153** The author disclaims copyright to this source code.  In place of
47154** a legal notice, here is a blessing:
47155**
47156**    May you do good and not evil.
47157**    May you find forgiveness for yourself and forgive others.
47158**    May you share freely, never taking more than you give.
47159**
47160*************************************************************************
47161** This file contains code used for creating, destroying, and populating
47162** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
47163** to version 2.8.7, all this code was combined into the vdbe.c source file.
47164** But that file was getting too big so this subroutines were split out.
47165*/
47166
47167
47168
47169/*
47170** When debugging the code generator in a symbolic debugger, one can
47171** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
47172** as they are added to the instruction stream.
47173*/
47174#ifdef SQLITE_DEBUG
47175SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
47176#endif
47177
47178
47179/*
47180** Create a new virtual database engine.
47181*/
47182SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
47183  Vdbe *p;
47184  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
47185  if( p==0 ) return 0;
47186  p->db = db;
47187  if( db->pVdbe ){
47188    db->pVdbe->pPrev = p;
47189  }
47190  p->pNext = db->pVdbe;
47191  p->pPrev = 0;
47192  db->pVdbe = p;
47193  p->magic = VDBE_MAGIC_INIT;
47194  return p;
47195}
47196
47197/*
47198** Remember the SQL string for a prepared statement.
47199*/
47200SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
47201  assert( isPrepareV2==1 || isPrepareV2==0 );
47202  if( p==0 ) return;
47203#ifdef SQLITE_OMIT_TRACE
47204  if( !isPrepareV2 ) return;
47205#endif
47206  assert( p->zSql==0 );
47207  p->zSql = sqlite3DbStrNDup(p->db, z, n);
47208  p->isPrepareV2 = (u8)isPrepareV2;
47209}
47210
47211/*
47212** Return the SQL associated with a prepared statement
47213*/
47214SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
47215  Vdbe *p = (Vdbe *)pStmt;
47216  return (p->isPrepareV2 ? p->zSql : 0);
47217}
47218
47219/*
47220** Swap all content between two VDBE structures.
47221*/
47222SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
47223  Vdbe tmp, *pTmp;
47224  char *zTmp;
47225  tmp = *pA;
47226  *pA = *pB;
47227  *pB = tmp;
47228  pTmp = pA->pNext;
47229  pA->pNext = pB->pNext;
47230  pB->pNext = pTmp;
47231  pTmp = pA->pPrev;
47232  pA->pPrev = pB->pPrev;
47233  pB->pPrev = pTmp;
47234  zTmp = pA->zSql;
47235  pA->zSql = pB->zSql;
47236  pB->zSql = zTmp;
47237  pB->isPrepareV2 = pA->isPrepareV2;
47238}
47239
47240#ifdef SQLITE_DEBUG
47241/*
47242** Turn tracing on or off
47243*/
47244SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
47245  p->trace = trace;
47246}
47247#endif
47248
47249/*
47250** Resize the Vdbe.aOp array so that it is at least one op larger than
47251** it was.
47252**
47253** If an out-of-memory error occurs while resizing the array, return
47254** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
47255** unchanged (this is so that any opcodes already allocated can be
47256** correctly deallocated along with the rest of the Vdbe).
47257*/
47258static int growOpArray(Vdbe *p){
47259  VdbeOp *pNew;
47260  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
47261  pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
47262  if( pNew ){
47263    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
47264    p->aOp = pNew;
47265  }
47266  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
47267}
47268
47269/*
47270** Add a new instruction to the list of instructions current in the
47271** VDBE.  Return the address of the new instruction.
47272**
47273** Parameters:
47274**
47275**    p               Pointer to the VDBE
47276**
47277**    op              The opcode for this instruction
47278**
47279**    p1, p2, p3      Operands
47280**
47281** Use the sqlite3VdbeResolveLabel() function to fix an address and
47282** the sqlite3VdbeChangeP4() function to change the value of the P4
47283** operand.
47284*/
47285SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
47286  int i;
47287  VdbeOp *pOp;
47288
47289  i = p->nOp;
47290  assert( p->magic==VDBE_MAGIC_INIT );
47291  assert( op>0 && op<0xff );
47292  if( p->nOpAlloc<=i ){
47293    if( growOpArray(p) ){
47294      return 1;
47295    }
47296  }
47297  p->nOp++;
47298  pOp = &p->aOp[i];
47299  pOp->opcode = (u8)op;
47300  pOp->p5 = 0;
47301  pOp->p1 = p1;
47302  pOp->p2 = p2;
47303  pOp->p3 = p3;
47304  pOp->p4.p = 0;
47305  pOp->p4type = P4_NOTUSED;
47306  p->expired = 0;
47307#ifdef SQLITE_DEBUG
47308  pOp->zComment = 0;
47309  if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
47310#endif
47311#ifdef VDBE_PROFILE
47312  pOp->cycles = 0;
47313  pOp->cnt = 0;
47314#endif
47315  return i;
47316}
47317SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
47318  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
47319}
47320SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
47321  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
47322}
47323SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
47324  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
47325}
47326
47327
47328/*
47329** Add an opcode that includes the p4 value as a pointer.
47330*/
47331SQLITE_PRIVATE int sqlite3VdbeAddOp4(
47332  Vdbe *p,            /* Add the opcode to this VM */
47333  int op,             /* The new opcode */
47334  int p1,             /* The P1 operand */
47335  int p2,             /* The P2 operand */
47336  int p3,             /* The P3 operand */
47337  const char *zP4,    /* The P4 operand */
47338  int p4type          /* P4 operand type */
47339){
47340  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
47341  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
47342  return addr;
47343}
47344
47345/*
47346** Add an opcode that includes the p4 value as an integer.
47347*/
47348SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
47349  Vdbe *p,            /* Add the opcode to this VM */
47350  int op,             /* The new opcode */
47351  int p1,             /* The P1 operand */
47352  int p2,             /* The P2 operand */
47353  int p3,             /* The P3 operand */
47354  int p4              /* The P4 operand as an integer */
47355){
47356  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
47357  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
47358  return addr;
47359}
47360
47361/*
47362** Create a new symbolic label for an instruction that has yet to be
47363** coded.  The symbolic label is really just a negative number.  The
47364** label can be used as the P2 value of an operation.  Later, when
47365** the label is resolved to a specific address, the VDBE will scan
47366** through its operation list and change all values of P2 which match
47367** the label into the resolved address.
47368**
47369** The VDBE knows that a P2 value is a label because labels are
47370** always negative and P2 values are suppose to be non-negative.
47371** Hence, a negative P2 value is a label that has yet to be resolved.
47372**
47373** Zero is returned if a malloc() fails.
47374*/
47375SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
47376  int i;
47377  i = p->nLabel++;
47378  assert( p->magic==VDBE_MAGIC_INIT );
47379  if( i>=p->nLabelAlloc ){
47380    int n = p->nLabelAlloc*2 + 5;
47381    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
47382                                       n*sizeof(p->aLabel[0]));
47383    p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
47384  }
47385  if( p->aLabel ){
47386    p->aLabel[i] = -1;
47387  }
47388  return -1-i;
47389}
47390
47391/*
47392** Resolve label "x" to be the address of the next instruction to
47393** be inserted.  The parameter "x" must have been obtained from
47394** a prior call to sqlite3VdbeMakeLabel().
47395*/
47396SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
47397  int j = -1-x;
47398  assert( p->magic==VDBE_MAGIC_INIT );
47399  assert( j>=0 && j<p->nLabel );
47400  if( p->aLabel ){
47401    p->aLabel[j] = p->nOp;
47402  }
47403}
47404
47405#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
47406
47407/*
47408** The following type and function are used to iterate through all opcodes
47409** in a Vdbe main program and each of the sub-programs (triggers) it may
47410** invoke directly or indirectly. It should be used as follows:
47411**
47412**   Op *pOp;
47413**   VdbeOpIter sIter;
47414**
47415**   memset(&sIter, 0, sizeof(sIter));
47416**   sIter.v = v;                            // v is of type Vdbe*
47417**   while( (pOp = opIterNext(&sIter)) ){
47418**     // Do something with pOp
47419**   }
47420**   sqlite3DbFree(v->db, sIter.apSub);
47421**
47422*/
47423typedef struct VdbeOpIter VdbeOpIter;
47424struct VdbeOpIter {
47425  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
47426  SubProgram **apSub;        /* Array of subprograms */
47427  int nSub;                  /* Number of entries in apSub */
47428  int iAddr;                 /* Address of next instruction to return */
47429  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
47430};
47431static Op *opIterNext(VdbeOpIter *p){
47432  Vdbe *v = p->v;
47433  Op *pRet = 0;
47434  Op *aOp;
47435  int nOp;
47436
47437  if( p->iSub<=p->nSub ){
47438
47439    if( p->iSub==0 ){
47440      aOp = v->aOp;
47441      nOp = v->nOp;
47442    }else{
47443      aOp = p->apSub[p->iSub-1]->aOp;
47444      nOp = p->apSub[p->iSub-1]->nOp;
47445    }
47446    assert( p->iAddr<nOp );
47447
47448    pRet = &aOp[p->iAddr];
47449    p->iAddr++;
47450    if( p->iAddr==nOp ){
47451      p->iSub++;
47452      p->iAddr = 0;
47453    }
47454
47455    if( pRet->p4type==P4_SUBPROGRAM ){
47456      int nByte = (p->nSub+1)*sizeof(SubProgram*);
47457      int j;
47458      for(j=0; j<p->nSub; j++){
47459        if( p->apSub[j]==pRet->p4.pProgram ) break;
47460      }
47461      if( j==p->nSub ){
47462        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
47463        if( !p->apSub ){
47464          pRet = 0;
47465        }else{
47466          p->apSub[p->nSub++] = pRet->p4.pProgram;
47467        }
47468      }
47469    }
47470  }
47471
47472  return pRet;
47473}
47474
47475/*
47476** Check if the program stored in the VM associated with pParse may
47477** throw an ABORT exception (causing the statement, but not entire transaction
47478** to be rolled back). This condition is true if the main program or any
47479** sub-programs contains any of the following:
47480**
47481**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
47482**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
47483**   *  OP_Destroy
47484**   *  OP_VUpdate
47485**   *  OP_VRename
47486**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
47487**
47488** Then check that the value of Parse.mayAbort is true if an
47489** ABORT may be thrown, or false otherwise. Return true if it does
47490** match, or false otherwise. This function is intended to be used as
47491** part of an assert statement in the compiler. Similar to:
47492**
47493**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
47494*/
47495SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
47496  int hasAbort = 0;
47497  Op *pOp;
47498  VdbeOpIter sIter;
47499  memset(&sIter, 0, sizeof(sIter));
47500  sIter.v = v;
47501
47502  while( (pOp = opIterNext(&sIter))!=0 ){
47503    int opcode = pOp->opcode;
47504    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
47505#ifndef SQLITE_OMIT_FOREIGN_KEY
47506     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
47507#endif
47508     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
47509      && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
47510    ){
47511      hasAbort = 1;
47512      break;
47513    }
47514  }
47515  sqlite3DbFree(v->db, sIter.apSub);
47516
47517  /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
47518  ** If malloc failed, then the while() loop above may not have iterated
47519  ** through all opcodes and hasAbort may be set incorrectly. Return
47520  ** true for this case to prevent the assert() in the callers frame
47521  ** from failing.  */
47522  return ( v->db->mallocFailed || hasAbort==mayAbort );
47523}
47524#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
47525
47526/*
47527** Loop through the program looking for P2 values that are negative
47528** on jump instructions.  Each such value is a label.  Resolve the
47529** label by setting the P2 value to its correct non-zero value.
47530**
47531** This routine is called once after all opcodes have been inserted.
47532**
47533** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
47534** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
47535** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
47536**
47537** The Op.opflags field is set on all opcodes.
47538*/
47539static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
47540  int i;
47541  int nMaxArgs = *pMaxFuncArgs;
47542  Op *pOp;
47543  int *aLabel = p->aLabel;
47544  p->readOnly = 1;
47545  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
47546    u8 opcode = pOp->opcode;
47547
47548    pOp->opflags = sqlite3OpcodeProperty[opcode];
47549    if( opcode==OP_Function || opcode==OP_AggStep ){
47550      if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
47551    }else if( opcode==OP_Transaction && pOp->p2!=0 ){
47552      p->readOnly = 0;
47553#ifndef SQLITE_OMIT_VIRTUALTABLE
47554    }else if( opcode==OP_VUpdate ){
47555      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
47556    }else if( opcode==OP_VFilter ){
47557      int n;
47558      assert( p->nOp - i >= 3 );
47559      assert( pOp[-1].opcode==OP_Integer );
47560      n = pOp[-1].p1;
47561      if( n>nMaxArgs ) nMaxArgs = n;
47562#endif
47563    }
47564
47565    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
47566      assert( -1-pOp->p2<p->nLabel );
47567      pOp->p2 = aLabel[-1-pOp->p2];
47568    }
47569  }
47570  sqlite3DbFree(p->db, p->aLabel);
47571  p->aLabel = 0;
47572
47573  *pMaxFuncArgs = nMaxArgs;
47574}
47575
47576/*
47577** Return the address of the next instruction to be inserted.
47578*/
47579SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
47580  assert( p->magic==VDBE_MAGIC_INIT );
47581  return p->nOp;
47582}
47583
47584/*
47585** This function returns a pointer to the array of opcodes associated with
47586** the Vdbe passed as the first argument. It is the callers responsibility
47587** to arrange for the returned array to be eventually freed using the
47588** vdbeFreeOpArray() function.
47589**
47590** Before returning, *pnOp is set to the number of entries in the returned
47591** array. Also, *pnMaxArg is set to the larger of its current value and
47592** the number of entries in the Vdbe.apArg[] array required to execute the
47593** returned program.
47594*/
47595SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
47596  VdbeOp *aOp = p->aOp;
47597  assert( aOp && !p->db->mallocFailed );
47598
47599  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
47600  assert( p->aMutex.nMutex==0 );
47601
47602  resolveP2Values(p, pnMaxArg);
47603  *pnOp = p->nOp;
47604  p->aOp = 0;
47605  return aOp;
47606}
47607
47608/*
47609** Add a whole list of operations to the operation stack.  Return the
47610** address of the first operation added.
47611*/
47612SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
47613  int addr;
47614  assert( p->magic==VDBE_MAGIC_INIT );
47615  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
47616    return 0;
47617  }
47618  addr = p->nOp;
47619  if( ALWAYS(nOp>0) ){
47620    int i;
47621    VdbeOpList const *pIn = aOp;
47622    for(i=0; i<nOp; i++, pIn++){
47623      int p2 = pIn->p2;
47624      VdbeOp *pOut = &p->aOp[i+addr];
47625      pOut->opcode = pIn->opcode;
47626      pOut->p1 = pIn->p1;
47627      if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
47628        pOut->p2 = addr + ADDR(p2);
47629      }else{
47630        pOut->p2 = p2;
47631      }
47632      pOut->p3 = pIn->p3;
47633      pOut->p4type = P4_NOTUSED;
47634      pOut->p4.p = 0;
47635      pOut->p5 = 0;
47636#ifdef SQLITE_DEBUG
47637      pOut->zComment = 0;
47638      if( sqlite3VdbeAddopTrace ){
47639        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
47640      }
47641#endif
47642    }
47643    p->nOp += nOp;
47644  }
47645  return addr;
47646}
47647
47648/*
47649** Change the value of the P1 operand for a specific instruction.
47650** This routine is useful when a large program is loaded from a
47651** static array using sqlite3VdbeAddOpList but we want to make a
47652** few minor changes to the program.
47653*/
47654SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
47655  assert( p!=0 );
47656  assert( addr>=0 );
47657  if( p->nOp>addr ){
47658    p->aOp[addr].p1 = val;
47659  }
47660}
47661
47662/*
47663** Change the value of the P2 operand for a specific instruction.
47664** This routine is useful for setting a jump destination.
47665*/
47666SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
47667  assert( p!=0 );
47668  assert( addr>=0 );
47669  if( p->nOp>addr ){
47670    p->aOp[addr].p2 = val;
47671  }
47672}
47673
47674/*
47675** Change the value of the P3 operand for a specific instruction.
47676*/
47677SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
47678  assert( p!=0 );
47679  assert( addr>=0 );
47680  if( p->nOp>addr ){
47681    p->aOp[addr].p3 = val;
47682  }
47683}
47684
47685/*
47686** Change the value of the P5 operand for the most recently
47687** added operation.
47688*/
47689SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
47690  assert( p!=0 );
47691  if( p->aOp ){
47692    assert( p->nOp>0 );
47693    p->aOp[p->nOp-1].p5 = val;
47694  }
47695}
47696
47697/*
47698** Change the P2 operand of instruction addr so that it points to
47699** the address of the next instruction to be coded.
47700*/
47701SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
47702  sqlite3VdbeChangeP2(p, addr, p->nOp);
47703}
47704
47705
47706/*
47707** If the input FuncDef structure is ephemeral, then free it.  If
47708** the FuncDef is not ephermal, then do nothing.
47709*/
47710static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
47711  if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
47712    sqlite3DbFree(db, pDef);
47713  }
47714}
47715
47716/*
47717** Delete a P4 value if necessary.
47718*/
47719static void freeP4(sqlite3 *db, int p4type, void *p4){
47720  if( p4 ){
47721    switch( p4type ){
47722      case P4_REAL:
47723      case P4_INT64:
47724      case P4_MPRINTF:
47725      case P4_DYNAMIC:
47726      case P4_KEYINFO:
47727      case P4_INTARRAY:
47728      case P4_KEYINFO_HANDOFF: {
47729        sqlite3DbFree(db, p4);
47730        break;
47731      }
47732      case P4_VDBEFUNC: {
47733        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
47734        freeEphemeralFunction(db, pVdbeFunc->pFunc);
47735        sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
47736        sqlite3DbFree(db, pVdbeFunc);
47737        break;
47738      }
47739      case P4_FUNCDEF: {
47740        freeEphemeralFunction(db, (FuncDef*)p4);
47741        break;
47742      }
47743      case P4_MEM: {
47744        sqlite3ValueFree((sqlite3_value*)p4);
47745        break;
47746      }
47747      case P4_VTAB : {
47748        sqlite3VtabUnlock((VTable *)p4);
47749        break;
47750      }
47751      case P4_SUBPROGRAM : {
47752        sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
47753        break;
47754      }
47755    }
47756  }
47757}
47758
47759/*
47760** Free the space allocated for aOp and any p4 values allocated for the
47761** opcodes contained within. If aOp is not NULL it is assumed to contain
47762** nOp entries.
47763*/
47764static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
47765  if( aOp ){
47766    Op *pOp;
47767    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
47768      freeP4(db, pOp->p4type, pOp->p4.p);
47769#ifdef SQLITE_DEBUG
47770      sqlite3DbFree(db, pOp->zComment);
47771#endif
47772    }
47773  }
47774  sqlite3DbFree(db, aOp);
47775}
47776
47777/*
47778** Decrement the ref-count on the SubProgram structure passed as the
47779** second argument. If the ref-count reaches zero, free the structure.
47780**
47781** The array of VDBE opcodes stored as SubProgram.aOp is freed if
47782** either the ref-count reaches zero or parameter freeop is non-zero.
47783**
47784** Since the array of opcodes pointed to by SubProgram.aOp may directly
47785** or indirectly contain a reference to the SubProgram structure itself.
47786** By passing a non-zero freeop parameter, the caller may ensure that all
47787** SubProgram structures and their aOp arrays are freed, even when there
47788** are such circular references.
47789*/
47790SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
47791  if( p ){
47792    assert( p->nRef>0 );
47793    if( freeop || p->nRef==1 ){
47794      Op *aOp = p->aOp;
47795      p->aOp = 0;
47796      vdbeFreeOpArray(db, aOp, p->nOp);
47797      p->nOp = 0;
47798    }
47799    p->nRef--;
47800    if( p->nRef==0 ){
47801      sqlite3DbFree(db, p);
47802    }
47803  }
47804}
47805
47806
47807/*
47808** Change N opcodes starting at addr to No-ops.
47809*/
47810SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
47811  if( p->aOp ){
47812    VdbeOp *pOp = &p->aOp[addr];
47813    sqlite3 *db = p->db;
47814    while( N-- ){
47815      freeP4(db, pOp->p4type, pOp->p4.p);
47816      memset(pOp, 0, sizeof(pOp[0]));
47817      pOp->opcode = OP_Noop;
47818      pOp++;
47819    }
47820  }
47821}
47822
47823/*
47824** Change the value of the P4 operand for a specific instruction.
47825** This routine is useful when a large program is loaded from a
47826** static array using sqlite3VdbeAddOpList but we want to make a
47827** few minor changes to the program.
47828**
47829** If n>=0 then the P4 operand is dynamic, meaning that a copy of
47830** the string is made into memory obtained from sqlite3_malloc().
47831** A value of n==0 means copy bytes of zP4 up to and including the
47832** first null byte.  If n>0 then copy n+1 bytes of zP4.
47833**
47834** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
47835** A copy is made of the KeyInfo structure into memory obtained from
47836** sqlite3_malloc, to be freed when the Vdbe is finalized.
47837** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
47838** stored in memory that the caller has obtained from sqlite3_malloc. The
47839** caller should not free the allocation, it will be freed when the Vdbe is
47840** finalized.
47841**
47842** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
47843** to a string or structure that is guaranteed to exist for the lifetime of
47844** the Vdbe. In these cases we can just copy the pointer.
47845**
47846** If addr<0 then change P4 on the most recently inserted instruction.
47847*/
47848SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
47849  Op *pOp;
47850  sqlite3 *db;
47851  assert( p!=0 );
47852  db = p->db;
47853  assert( p->magic==VDBE_MAGIC_INIT );
47854  if( p->aOp==0 || db->mallocFailed ){
47855    if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
47856      freeP4(db, n, (void*)*(char**)&zP4);
47857    }
47858    return;
47859  }
47860  assert( p->nOp>0 );
47861  assert( addr<p->nOp );
47862  if( addr<0 ){
47863    addr = p->nOp - 1;
47864  }
47865  pOp = &p->aOp[addr];
47866  freeP4(db, pOp->p4type, pOp->p4.p);
47867  pOp->p4.p = 0;
47868  if( n==P4_INT32 ){
47869    /* Note: this cast is safe, because the origin data point was an int
47870    ** that was cast to a (const char *). */
47871    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
47872    pOp->p4type = P4_INT32;
47873  }else if( zP4==0 ){
47874    pOp->p4.p = 0;
47875    pOp->p4type = P4_NOTUSED;
47876  }else if( n==P4_KEYINFO ){
47877    KeyInfo *pKeyInfo;
47878    int nField, nByte;
47879
47880    nField = ((KeyInfo*)zP4)->nField;
47881    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
47882    pKeyInfo = sqlite3Malloc( nByte );
47883    pOp->p4.pKeyInfo = pKeyInfo;
47884    if( pKeyInfo ){
47885      u8 *aSortOrder;
47886      memcpy(pKeyInfo, zP4, nByte);
47887      aSortOrder = pKeyInfo->aSortOrder;
47888      if( aSortOrder ){
47889        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
47890        memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
47891      }
47892      pOp->p4type = P4_KEYINFO;
47893    }else{
47894      p->db->mallocFailed = 1;
47895      pOp->p4type = P4_NOTUSED;
47896    }
47897  }else if( n==P4_KEYINFO_HANDOFF ){
47898    pOp->p4.p = (void*)zP4;
47899    pOp->p4type = P4_KEYINFO;
47900  }else if( n==P4_VTAB ){
47901    pOp->p4.p = (void*)zP4;
47902    pOp->p4type = P4_VTAB;
47903    sqlite3VtabLock((VTable *)zP4);
47904    assert( ((VTable *)zP4)->db==p->db );
47905  }else if( n<0 ){
47906    pOp->p4.p = (void*)zP4;
47907    pOp->p4type = (signed char)n;
47908  }else{
47909    if( n==0 ) n = sqlite3Strlen30(zP4);
47910    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
47911    pOp->p4type = P4_DYNAMIC;
47912  }
47913}
47914
47915#ifndef NDEBUG
47916/*
47917** Change the comment on the the most recently coded instruction.  Or
47918** insert a No-op and add the comment to that new instruction.  This
47919** makes the code easier to read during debugging.  None of this happens
47920** in a production build.
47921*/
47922SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
47923  va_list ap;
47924  if( !p ) return;
47925  assert( p->nOp>0 || p->aOp==0 );
47926  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
47927  if( p->nOp ){
47928    char **pz = &p->aOp[p->nOp-1].zComment;
47929    va_start(ap, zFormat);
47930    sqlite3DbFree(p->db, *pz);
47931    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
47932    va_end(ap);
47933  }
47934}
47935SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
47936  va_list ap;
47937  if( !p ) return;
47938  sqlite3VdbeAddOp0(p, OP_Noop);
47939  assert( p->nOp>0 || p->aOp==0 );
47940  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
47941  if( p->nOp ){
47942    char **pz = &p->aOp[p->nOp-1].zComment;
47943    va_start(ap, zFormat);
47944    sqlite3DbFree(p->db, *pz);
47945    *pz = sqlite3VMPrintf(p->db, zFormat, ap);
47946    va_end(ap);
47947  }
47948}
47949#endif  /* NDEBUG */
47950
47951/*
47952** Return the opcode for a given address.  If the address is -1, then
47953** return the most recently inserted opcode.
47954**
47955** If a memory allocation error has occurred prior to the calling of this
47956** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
47957** is readable and writable, but it has no effect.  The return of a dummy
47958** opcode allows the call to continue functioning after a OOM fault without
47959** having to check to see if the return from this routine is a valid pointer.
47960**
47961** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
47962** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
47963** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
47964** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
47965** having to double-check to make sure that the result is non-negative. But
47966** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
47967** check the value of p->nOp-1 before continuing.
47968*/
47969SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
47970  static VdbeOp dummy;
47971  assert( p->magic==VDBE_MAGIC_INIT );
47972  if( addr<0 ){
47973#ifdef SQLITE_OMIT_TRACE
47974    if( p->nOp==0 ) return &dummy;
47975#endif
47976    addr = p->nOp - 1;
47977  }
47978  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
47979  if( p->db->mallocFailed ){
47980    return &dummy;
47981  }else{
47982    return &p->aOp[addr];
47983  }
47984}
47985
47986#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
47987     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
47988/*
47989** Compute a string that describes the P4 parameter for an opcode.
47990** Use zTemp for any required temporary buffer space.
47991*/
47992static char *displayP4(Op *pOp, char *zTemp, int nTemp){
47993  char *zP4 = zTemp;
47994  assert( nTemp>=20 );
47995  switch( pOp->p4type ){
47996    case P4_KEYINFO_STATIC:
47997    case P4_KEYINFO: {
47998      int i, j;
47999      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
48000      sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
48001      i = sqlite3Strlen30(zTemp);
48002      for(j=0; j<pKeyInfo->nField; j++){
48003        CollSeq *pColl = pKeyInfo->aColl[j];
48004        if( pColl ){
48005          int n = sqlite3Strlen30(pColl->zName);
48006          if( i+n>nTemp-6 ){
48007            memcpy(&zTemp[i],",...",4);
48008            break;
48009          }
48010          zTemp[i++] = ',';
48011          if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
48012            zTemp[i++] = '-';
48013          }
48014          memcpy(&zTemp[i], pColl->zName,n+1);
48015          i += n;
48016        }else if( i+4<nTemp-6 ){
48017          memcpy(&zTemp[i],",nil",4);
48018          i += 4;
48019        }
48020      }
48021      zTemp[i++] = ')';
48022      zTemp[i] = 0;
48023      assert( i<nTemp );
48024      break;
48025    }
48026    case P4_COLLSEQ: {
48027      CollSeq *pColl = pOp->p4.pColl;
48028      sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
48029      break;
48030    }
48031    case P4_FUNCDEF: {
48032      FuncDef *pDef = pOp->p4.pFunc;
48033      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
48034      break;
48035    }
48036    case P4_INT64: {
48037      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
48038      break;
48039    }
48040    case P4_INT32: {
48041      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
48042      break;
48043    }
48044    case P4_REAL: {
48045      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
48046      break;
48047    }
48048    case P4_MEM: {
48049      Mem *pMem = pOp->p4.pMem;
48050      assert( (pMem->flags & MEM_Null)==0 );
48051      if( pMem->flags & MEM_Str ){
48052        zP4 = pMem->z;
48053      }else if( pMem->flags & MEM_Int ){
48054        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
48055      }else if( pMem->flags & MEM_Real ){
48056        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
48057      }else{
48058        assert( pMem->flags & MEM_Blob );
48059        zP4 = "(blob)";
48060      }
48061      break;
48062    }
48063#ifndef SQLITE_OMIT_VIRTUALTABLE
48064    case P4_VTAB: {
48065      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
48066      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
48067      break;
48068    }
48069#endif
48070    case P4_INTARRAY: {
48071      sqlite3_snprintf(nTemp, zTemp, "intarray");
48072      break;
48073    }
48074    case P4_SUBPROGRAM: {
48075      sqlite3_snprintf(nTemp, zTemp, "program");
48076      break;
48077    }
48078    default: {
48079      zP4 = pOp->p4.z;
48080      if( zP4==0 ){
48081        zP4 = zTemp;
48082        zTemp[0] = 0;
48083      }
48084    }
48085  }
48086  assert( zP4!=0 );
48087  return zP4;
48088}
48089#endif
48090
48091/*
48092** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
48093*/
48094SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
48095  int mask;
48096  assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
48097  assert( i<(int)sizeof(p->btreeMask)*8 );
48098  mask = ((u32)1)<<i;
48099  if( (p->btreeMask & mask)==0 ){
48100    p->btreeMask |= mask;
48101    sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
48102  }
48103}
48104
48105
48106#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
48107/*
48108** Print a single opcode.  This routine is used for debugging only.
48109*/
48110SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
48111  char *zP4;
48112  char zPtr[50];
48113  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
48114  if( pOut==0 ) pOut = stdout;
48115  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
48116  fprintf(pOut, zFormat1, pc,
48117      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
48118#ifdef SQLITE_DEBUG
48119      pOp->zComment ? pOp->zComment : ""
48120#else
48121      ""
48122#endif
48123  );
48124  fflush(pOut);
48125}
48126#endif
48127
48128/*
48129** Release an array of N Mem elements
48130*/
48131static void releaseMemArray(Mem *p, int N){
48132  if( p && N ){
48133    Mem *pEnd;
48134    sqlite3 *db = p->db;
48135    u8 malloc_failed = db->mallocFailed;
48136    for(pEnd=&p[N]; p<pEnd; p++){
48137      assert( (&p[1])==pEnd || p[0].db==p[1].db );
48138
48139      /* This block is really an inlined version of sqlite3VdbeMemRelease()
48140      ** that takes advantage of the fact that the memory cell value is
48141      ** being set to NULL after releasing any dynamic resources.
48142      **
48143      ** The justification for duplicating code is that according to
48144      ** callgrind, this causes a certain test case to hit the CPU 4.7
48145      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
48146      ** sqlite3MemRelease() were called from here. With -O2, this jumps
48147      ** to 6.6 percent. The test case is inserting 1000 rows into a table
48148      ** with no indexes using a single prepared INSERT statement, bind()
48149      ** and reset(). Inserts are grouped into a transaction.
48150      */
48151      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
48152        sqlite3VdbeMemRelease(p);
48153      }else if( p->zMalloc ){
48154        sqlite3DbFree(db, p->zMalloc);
48155        p->zMalloc = 0;
48156      }
48157
48158      p->flags = MEM_Null;
48159    }
48160    db->mallocFailed = malloc_failed;
48161  }
48162}
48163
48164/*
48165** Delete a VdbeFrame object and its contents. VdbeFrame objects are
48166** allocated by the OP_Program opcode in sqlite3VdbeExec().
48167*/
48168SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
48169  int i;
48170  Mem *aMem = VdbeFrameMem(p);
48171  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
48172  for(i=0; i<p->nChildCsr; i++){
48173    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
48174  }
48175  releaseMemArray(aMem, p->nChildMem);
48176  sqlite3DbFree(p->v->db, p);
48177}
48178
48179#ifndef SQLITE_OMIT_EXPLAIN
48180/*
48181** Give a listing of the program in the virtual machine.
48182**
48183** The interface is the same as sqlite3VdbeExec().  But instead of
48184** running the code, it invokes the callback once for each instruction.
48185** This feature is used to implement "EXPLAIN".
48186**
48187** When p->explain==1, each instruction is listed.  When
48188** p->explain==2, only OP_Explain instructions are listed and these
48189** are shown in a different format.  p->explain==2 is used to implement
48190** EXPLAIN QUERY PLAN.
48191**
48192** When p->explain==1, first the main program is listed, then each of
48193** the trigger subprograms are listed one by one.
48194*/
48195SQLITE_PRIVATE int sqlite3VdbeList(
48196  Vdbe *p                   /* The VDBE */
48197){
48198  int nRow;                            /* Stop when row count reaches this */
48199  int nSub = 0;                        /* Number of sub-vdbes seen so far */
48200  SubProgram **apSub = 0;              /* Array of sub-vdbes */
48201  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
48202  sqlite3 *db = p->db;                 /* The database connection */
48203  int i;                               /* Loop counter */
48204  int rc = SQLITE_OK;                  /* Return code */
48205  Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
48206
48207  assert( p->explain );
48208  assert( p->magic==VDBE_MAGIC_RUN );
48209  assert( db->magic==SQLITE_MAGIC_BUSY );
48210  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
48211
48212  /* Even though this opcode does not use dynamic strings for
48213  ** the result, result columns may become dynamic if the user calls
48214  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
48215  */
48216  releaseMemArray(pMem, 8);
48217
48218  if( p->rc==SQLITE_NOMEM ){
48219    /* This happens if a malloc() inside a call to sqlite3_column_text() or
48220    ** sqlite3_column_text16() failed.  */
48221    db->mallocFailed = 1;
48222    return SQLITE_ERROR;
48223  }
48224
48225  /* When the number of output rows reaches nRow, that means the
48226  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
48227  ** nRow is the sum of the number of rows in the main program, plus
48228  ** the sum of the number of rows in all trigger subprograms encountered
48229  ** so far.  The nRow value will increase as new trigger subprograms are
48230  ** encountered, but p->pc will eventually catch up to nRow.
48231  */
48232  nRow = p->nOp;
48233  if( p->explain==1 ){
48234    /* The first 8 memory cells are used for the result set.  So we will
48235    ** commandeer the 9th cell to use as storage for an array of pointers
48236    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
48237    ** cells.  */
48238    assert( p->nMem>9 );
48239    pSub = &p->aMem[9];
48240    if( pSub->flags&MEM_Blob ){
48241      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
48242      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
48243      nSub = pSub->n/sizeof(Vdbe*);
48244      apSub = (SubProgram **)pSub->z;
48245    }
48246    for(i=0; i<nSub; i++){
48247      nRow += apSub[i]->nOp;
48248    }
48249  }
48250
48251  do{
48252    i = p->pc++;
48253  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
48254  if( i>=nRow ){
48255    p->rc = SQLITE_OK;
48256    rc = SQLITE_DONE;
48257  }else if( db->u1.isInterrupted ){
48258    p->rc = SQLITE_INTERRUPT;
48259    rc = SQLITE_ERROR;
48260    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
48261  }else{
48262    char *z;
48263    Op *pOp;
48264    if( i<p->nOp ){
48265      /* The output line number is small enough that we are still in the
48266      ** main program. */
48267      pOp = &p->aOp[i];
48268    }else{
48269      /* We are currently listing subprograms.  Figure out which one and
48270      ** pick up the appropriate opcode. */
48271      int j;
48272      i -= p->nOp;
48273      for(j=0; i>=apSub[j]->nOp; j++){
48274        i -= apSub[j]->nOp;
48275      }
48276      pOp = &apSub[j]->aOp[i];
48277    }
48278    if( p->explain==1 ){
48279      pMem->flags = MEM_Int;
48280      pMem->type = SQLITE_INTEGER;
48281      pMem->u.i = i;                                /* Program counter */
48282      pMem++;
48283
48284      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
48285      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
48286      assert( pMem->z!=0 );
48287      pMem->n = sqlite3Strlen30(pMem->z);
48288      pMem->type = SQLITE_TEXT;
48289      pMem->enc = SQLITE_UTF8;
48290      pMem++;
48291
48292      /* When an OP_Program opcode is encounter (the only opcode that has
48293      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
48294      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
48295      ** has not already been seen.
48296      */
48297      if( pOp->p4type==P4_SUBPROGRAM ){
48298        int nByte = (nSub+1)*sizeof(SubProgram*);
48299        int j;
48300        for(j=0; j<nSub; j++){
48301          if( apSub[j]==pOp->p4.pProgram ) break;
48302        }
48303        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
48304          apSub = (SubProgram **)pSub->z;
48305          apSub[nSub++] = pOp->p4.pProgram;
48306          pSub->flags |= MEM_Blob;
48307          pSub->n = nSub*sizeof(SubProgram*);
48308        }
48309      }
48310    }
48311
48312    pMem->flags = MEM_Int;
48313    pMem->u.i = pOp->p1;                          /* P1 */
48314    pMem->type = SQLITE_INTEGER;
48315    pMem++;
48316
48317    pMem->flags = MEM_Int;
48318    pMem->u.i = pOp->p2;                          /* P2 */
48319    pMem->type = SQLITE_INTEGER;
48320    pMem++;
48321
48322    if( p->explain==1 ){
48323      pMem->flags = MEM_Int;
48324      pMem->u.i = pOp->p3;                          /* P3 */
48325      pMem->type = SQLITE_INTEGER;
48326      pMem++;
48327    }
48328
48329    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
48330      assert( p->db->mallocFailed );
48331      return SQLITE_ERROR;
48332    }
48333    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
48334    z = displayP4(pOp, pMem->z, 32);
48335    if( z!=pMem->z ){
48336      sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
48337    }else{
48338      assert( pMem->z!=0 );
48339      pMem->n = sqlite3Strlen30(pMem->z);
48340      pMem->enc = SQLITE_UTF8;
48341    }
48342    pMem->type = SQLITE_TEXT;
48343    pMem++;
48344
48345    if( p->explain==1 ){
48346      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
48347        assert( p->db->mallocFailed );
48348        return SQLITE_ERROR;
48349      }
48350      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
48351      pMem->n = 2;
48352      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
48353      pMem->type = SQLITE_TEXT;
48354      pMem->enc = SQLITE_UTF8;
48355      pMem++;
48356
48357#ifdef SQLITE_DEBUG
48358      if( pOp->zComment ){
48359        pMem->flags = MEM_Str|MEM_Term;
48360        pMem->z = pOp->zComment;
48361        pMem->n = sqlite3Strlen30(pMem->z);
48362        pMem->enc = SQLITE_UTF8;
48363        pMem->type = SQLITE_TEXT;
48364      }else
48365#endif
48366      {
48367        pMem->flags = MEM_Null;                       /* Comment */
48368        pMem->type = SQLITE_NULL;
48369      }
48370    }
48371
48372    p->nResColumn = 8 - 5*(p->explain-1);
48373    p->rc = SQLITE_OK;
48374    rc = SQLITE_ROW;
48375  }
48376  return rc;
48377}
48378#endif /* SQLITE_OMIT_EXPLAIN */
48379
48380#ifdef SQLITE_DEBUG
48381/*
48382** Print the SQL that was used to generate a VDBE program.
48383*/
48384SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
48385  int nOp = p->nOp;
48386  VdbeOp *pOp;
48387  if( nOp<1 ) return;
48388  pOp = &p->aOp[0];
48389  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
48390    const char *z = pOp->p4.z;
48391    while( sqlite3Isspace(*z) ) z++;
48392    printf("SQL: [%s]\n", z);
48393  }
48394}
48395#endif
48396
48397#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
48398/*
48399** Print an IOTRACE message showing SQL content.
48400*/
48401SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
48402  int nOp = p->nOp;
48403  VdbeOp *pOp;
48404  if( sqlite3IoTrace==0 ) return;
48405  if( nOp<1 ) return;
48406  pOp = &p->aOp[0];
48407  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
48408    int i, j;
48409    char z[1000];
48410    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
48411    for(i=0; sqlite3Isspace(z[i]); i++){}
48412    for(j=0; z[i]; i++){
48413      if( sqlite3Isspace(z[i]) ){
48414        if( z[i-1]!=' ' ){
48415          z[j++] = ' ';
48416        }
48417      }else{
48418        z[j++] = z[i];
48419      }
48420    }
48421    z[j] = 0;
48422    sqlite3IoTrace("SQL %s\n", z);
48423  }
48424}
48425#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
48426
48427/*
48428** Allocate space from a fixed size buffer and return a pointer to
48429** that space.  If insufficient space is available, return NULL.
48430**
48431** The pBuf parameter is the initial value of a pointer which will
48432** receive the new memory.  pBuf is normally NULL.  If pBuf is not
48433** NULL, it means that memory space has already been allocated and that
48434** this routine should not allocate any new memory.  When pBuf is not
48435** NULL simply return pBuf.  Only allocate new memory space when pBuf
48436** is NULL.
48437**
48438** nByte is the number of bytes of space needed.
48439**
48440** *ppFrom points to available space and pEnd points to the end of the
48441** available space.  When space is allocated, *ppFrom is advanced past
48442** the end of the allocated space.
48443**
48444** *pnByte is a counter of the number of bytes of space that have failed
48445** to allocate.  If there is insufficient space in *ppFrom to satisfy the
48446** request, then increment *pnByte by the amount of the request.
48447*/
48448static void *allocSpace(
48449  void *pBuf,          /* Where return pointer will be stored */
48450  int nByte,           /* Number of bytes to allocate */
48451  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
48452  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
48453  int *pnByte          /* If allocation cannot be made, increment *pnByte */
48454){
48455  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
48456  if( pBuf ) return pBuf;
48457  nByte = ROUND8(nByte);
48458  if( &(*ppFrom)[nByte] <= pEnd ){
48459    pBuf = (void*)*ppFrom;
48460    *ppFrom += nByte;
48461  }else{
48462    *pnByte += nByte;
48463  }
48464  return pBuf;
48465}
48466
48467/*
48468** Prepare a virtual machine for execution.  This involves things such
48469** as allocating stack space and initializing the program counter.
48470** After the VDBE has be prepped, it can be executed by one or more
48471** calls to sqlite3VdbeExec().
48472**
48473** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
48474** VDBE_MAGIC_RUN.
48475**
48476** This function may be called more than once on a single virtual machine.
48477** The first call is made while compiling the SQL statement. Subsequent
48478** calls are made as part of the process of resetting a statement to be
48479** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor
48480** and isExplain parameters are only passed correct values the first time
48481** the function is called. On subsequent calls, from sqlite3_reset(), nVar
48482** is passed -1 and nMem, nCursor and isExplain are all passed zero.
48483*/
48484SQLITE_PRIVATE void sqlite3VdbeMakeReady(
48485  Vdbe *p,                       /* The VDBE */
48486  int nVar,                      /* Number of '?' see in the SQL statement */
48487  int nMem,                      /* Number of memory cells to allocate */
48488  int nCursor,                   /* Number of cursors to allocate */
48489  int nArg,                      /* Maximum number of args in SubPrograms */
48490  int isExplain,                 /* True if the EXPLAIN keywords is present */
48491  int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
48492){
48493  int n;
48494  sqlite3 *db = p->db;
48495
48496  assert( p!=0 );
48497  assert( p->magic==VDBE_MAGIC_INIT );
48498
48499  /* There should be at least one opcode.
48500  */
48501  assert( p->nOp>0 );
48502
48503  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
48504  p->magic = VDBE_MAGIC_RUN;
48505
48506  /* For each cursor required, also allocate a memory cell. Memory
48507  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
48508  ** the vdbe program. Instead they are used to allocate space for
48509  ** VdbeCursor/BtCursor structures. The blob of memory associated with
48510  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
48511  ** stores the blob of memory associated with cursor 1, etc.
48512  **
48513  ** See also: allocateCursor().
48514  */
48515  nMem += nCursor;
48516
48517  /* Allocate space for memory registers, SQL variables, VDBE cursors and
48518  ** an array to marshal SQL function arguments in. This is only done the
48519  ** first time this function is called for a given VDBE, not when it is
48520  ** being called from sqlite3_reset() to reset the virtual machine.
48521  */
48522  if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
48523    u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
48524    u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
48525    int nByte;                              /* How much extra memory needed */
48526
48527    resolveP2Values(p, &nArg);
48528    p->usesStmtJournal = (u8)usesStmtJournal;
48529    if( isExplain && nMem<10 ){
48530      nMem = 10;
48531    }
48532    memset(zCsr, 0, zEnd-zCsr);
48533    zCsr += (zCsr - (u8*)0)&7;
48534    assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
48535
48536    /* Memory for registers, parameters, cursor, etc, is allocated in two
48537    ** passes.  On the first pass, we try to reuse unused space at the
48538    ** end of the opcode array.  If we are unable to satisfy all memory
48539    ** requirements by reusing the opcode array tail, then the second
48540    ** pass will fill in the rest using a fresh allocation.
48541    **
48542    ** This two-pass approach that reuses as much memory as possible from
48543    ** the leftover space at the end of the opcode array can significantly
48544    ** reduce the amount of memory held by a prepared statement.
48545    */
48546    do {
48547      nByte = 0;
48548      p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
48549      p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
48550      p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
48551      p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
48552      p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
48553                            &zCsr, zEnd, &nByte);
48554      if( nByte ){
48555        p->pFree = sqlite3DbMallocZero(db, nByte);
48556      }
48557      zCsr = p->pFree;
48558      zEnd = &zCsr[nByte];
48559    }while( nByte && !db->mallocFailed );
48560
48561    p->nCursor = (u16)nCursor;
48562    if( p->aVar ){
48563      p->nVar = (ynVar)nVar;
48564      for(n=0; n<nVar; n++){
48565        p->aVar[n].flags = MEM_Null;
48566        p->aVar[n].db = db;
48567      }
48568    }
48569    if( p->aMem ){
48570      p->aMem--;                      /* aMem[] goes from 1..nMem */
48571      p->nMem = nMem;                 /*       not from 0..nMem-1 */
48572      for(n=1; n<=nMem; n++){
48573        p->aMem[n].flags = MEM_Null;
48574        p->aMem[n].db = db;
48575      }
48576    }
48577  }
48578#ifdef SQLITE_DEBUG
48579  for(n=1; n<p->nMem; n++){
48580    assert( p->aMem[n].db==db );
48581  }
48582#endif
48583
48584  p->pc = -1;
48585  p->rc = SQLITE_OK;
48586  p->errorAction = OE_Abort;
48587  p->explain |= isExplain;
48588  p->magic = VDBE_MAGIC_RUN;
48589  p->nChange = 0;
48590  p->cacheCtr = 1;
48591  p->minWriteFileFormat = 255;
48592  p->iStatement = 0;
48593#ifdef VDBE_PROFILE
48594  {
48595    int i;
48596    for(i=0; i<p->nOp; i++){
48597      p->aOp[i].cnt = 0;
48598      p->aOp[i].cycles = 0;
48599    }
48600  }
48601#endif
48602}
48603
48604/*
48605** Close a VDBE cursor and release all the resources that cursor
48606** happens to hold.
48607*/
48608SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
48609  if( pCx==0 ){
48610    return;
48611  }
48612  if( pCx->pBt ){
48613    sqlite3BtreeClose(pCx->pBt);
48614    /* The pCx->pCursor will be close automatically, if it exists, by
48615    ** the call above. */
48616  }else if( pCx->pCursor ){
48617    sqlite3BtreeCloseCursor(pCx->pCursor);
48618  }
48619#ifndef SQLITE_OMIT_VIRTUALTABLE
48620  if( pCx->pVtabCursor ){
48621    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
48622    const sqlite3_module *pModule = pCx->pModule;
48623    p->inVtabMethod = 1;
48624    (void)sqlite3SafetyOff(p->db);
48625    pModule->xClose(pVtabCursor);
48626    (void)sqlite3SafetyOn(p->db);
48627    p->inVtabMethod = 0;
48628  }
48629#endif
48630}
48631
48632/*
48633** Copy the values stored in the VdbeFrame structure to its Vdbe. This
48634** is used, for example, when a trigger sub-program is halted to restore
48635** control to the main program.
48636*/
48637SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
48638  Vdbe *v = pFrame->v;
48639  v->aOp = pFrame->aOp;
48640  v->nOp = pFrame->nOp;
48641  v->aMem = pFrame->aMem;
48642  v->nMem = pFrame->nMem;
48643  v->apCsr = pFrame->apCsr;
48644  v->nCursor = pFrame->nCursor;
48645  v->db->lastRowid = pFrame->lastRowid;
48646  v->nChange = pFrame->nChange;
48647  return pFrame->pc;
48648}
48649
48650/*
48651** Close all cursors.
48652**
48653** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
48654** cell array. This is necessary as the memory cell array may contain
48655** pointers to VdbeFrame objects, which may in turn contain pointers to
48656** open cursors.
48657*/
48658static void closeAllCursors(Vdbe *p){
48659  if( p->pFrame ){
48660    VdbeFrame *pFrame = p->pFrame;
48661    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
48662    sqlite3VdbeFrameRestore(pFrame);
48663  }
48664  p->pFrame = 0;
48665  p->nFrame = 0;
48666
48667  if( p->apCsr ){
48668    int i;
48669    for(i=0; i<p->nCursor; i++){
48670      VdbeCursor *pC = p->apCsr[i];
48671      if( pC ){
48672        sqlite3VdbeFreeCursor(p, pC);
48673        p->apCsr[i] = 0;
48674      }
48675    }
48676  }
48677  if( p->aMem ){
48678    releaseMemArray(&p->aMem[1], p->nMem);
48679  }
48680}
48681
48682/*
48683** Clean up the VM after execution.
48684**
48685** This routine will automatically close any cursors, lists, and/or
48686** sorters that were left open.  It also deletes the values of
48687** variables in the aVar[] array.
48688*/
48689static void Cleanup(Vdbe *p){
48690  sqlite3 *db = p->db;
48691
48692#ifdef SQLITE_DEBUG
48693  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
48694  ** Vdbe.aMem[] arrays have already been cleaned up.  */
48695  int i;
48696  for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
48697  for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
48698#endif
48699
48700  sqlite3DbFree(db, p->zErrMsg);
48701  p->zErrMsg = 0;
48702  p->pResultSet = 0;
48703}
48704
48705/*
48706** Set the number of result columns that will be returned by this SQL
48707** statement. This is now set at compile time, rather than during
48708** execution of the vdbe program so that sqlite3_column_count() can
48709** be called on an SQL statement before sqlite3_step().
48710*/
48711SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
48712  Mem *pColName;
48713  int n;
48714  sqlite3 *db = p->db;
48715
48716  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
48717  sqlite3DbFree(db, p->aColName);
48718  n = nResColumn*COLNAME_N;
48719  p->nResColumn = (u16)nResColumn;
48720  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
48721  if( p->aColName==0 ) return;
48722  while( n-- > 0 ){
48723    pColName->flags = MEM_Null;
48724    pColName->db = p->db;
48725    pColName++;
48726  }
48727}
48728
48729/*
48730** Set the name of the idx'th column to be returned by the SQL statement.
48731** zName must be a pointer to a nul terminated string.
48732**
48733** This call must be made after a call to sqlite3VdbeSetNumCols().
48734**
48735** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
48736** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
48737** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
48738*/
48739SQLITE_PRIVATE int sqlite3VdbeSetColName(
48740  Vdbe *p,                         /* Vdbe being configured */
48741  int idx,                         /* Index of column zName applies to */
48742  int var,                         /* One of the COLNAME_* constants */
48743  const char *zName,               /* Pointer to buffer containing name */
48744  void (*xDel)(void*)              /* Memory management strategy for zName */
48745){
48746  int rc;
48747  Mem *pColName;
48748  assert( idx<p->nResColumn );
48749  assert( var<COLNAME_N );
48750  if( p->db->mallocFailed ){
48751    assert( !zName || xDel!=SQLITE_DYNAMIC );
48752    return SQLITE_NOMEM;
48753  }
48754  assert( p->aColName!=0 );
48755  pColName = &(p->aColName[idx+var*p->nResColumn]);
48756  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
48757  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
48758  return rc;
48759}
48760
48761/*
48762** A read or write transaction may or may not be active on database handle
48763** db. If a transaction is active, commit it. If there is a
48764** write-transaction spanning more than one database file, this routine
48765** takes care of the master journal trickery.
48766*/
48767static int vdbeCommit(sqlite3 *db, Vdbe *p){
48768  int i;
48769  int nTrans = 0;  /* Number of databases with an active write-transaction */
48770  int rc = SQLITE_OK;
48771  int needXcommit = 0;
48772
48773#ifdef SQLITE_OMIT_VIRTUALTABLE
48774  /* With this option, sqlite3VtabSync() is defined to be simply
48775  ** SQLITE_OK so p is not used.
48776  */
48777  UNUSED_PARAMETER(p);
48778#endif
48779
48780  /* Before doing anything else, call the xSync() callback for any
48781  ** virtual module tables written in this transaction. This has to
48782  ** be done before determining whether a master journal file is
48783  ** required, as an xSync() callback may add an attached database
48784  ** to the transaction.
48785  */
48786  rc = sqlite3VtabSync(db, &p->zErrMsg);
48787  if( rc!=SQLITE_OK ){
48788    return rc;
48789  }
48790
48791  /* This loop determines (a) if the commit hook should be invoked and
48792  ** (b) how many database files have open write transactions, not
48793  ** including the temp database. (b) is important because if more than
48794  ** one database file has an open write transaction, a master journal
48795  ** file is required for an atomic commit.
48796  */
48797  for(i=0; i<db->nDb; i++){
48798    Btree *pBt = db->aDb[i].pBt;
48799    if( sqlite3BtreeIsInTrans(pBt) ){
48800      needXcommit = 1;
48801      if( i!=1 ) nTrans++;
48802    }
48803  }
48804
48805  /* If there are any write-transactions at all, invoke the commit hook */
48806  if( needXcommit && db->xCommitCallback ){
48807    (void)sqlite3SafetyOff(db);
48808    rc = db->xCommitCallback(db->pCommitArg);
48809    (void)sqlite3SafetyOn(db);
48810    if( rc ){
48811      return SQLITE_CONSTRAINT;
48812    }
48813  }
48814
48815  /* The simple case - no more than one database file (not counting the
48816  ** TEMP database) has a transaction active.   There is no need for the
48817  ** master-journal.
48818  **
48819  ** If the return value of sqlite3BtreeGetFilename() is a zero length
48820  ** string, it means the main database is :memory: or a temp file.  In
48821  ** that case we do not support atomic multi-file commits, so use the
48822  ** simple case then too.
48823  */
48824  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
48825   || nTrans<=1
48826  ){
48827    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
48828      Btree *pBt = db->aDb[i].pBt;
48829      if( pBt ){
48830        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
48831      }
48832    }
48833
48834    /* Do the commit only if all databases successfully complete phase 1.
48835    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
48836    ** IO error while deleting or truncating a journal file. It is unlikely,
48837    ** but could happen. In this case abandon processing and return the error.
48838    */
48839    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
48840      Btree *pBt = db->aDb[i].pBt;
48841      if( pBt ){
48842        rc = sqlite3BtreeCommitPhaseTwo(pBt);
48843      }
48844    }
48845    if( rc==SQLITE_OK ){
48846      sqlite3VtabCommit(db);
48847    }
48848  }
48849
48850  /* The complex case - There is a multi-file write-transaction active.
48851  ** This requires a master journal file to ensure the transaction is
48852  ** committed atomicly.
48853  */
48854#ifndef SQLITE_OMIT_DISKIO
48855  else{
48856    sqlite3_vfs *pVfs = db->pVfs;
48857    int needSync = 0;
48858    char *zMaster = 0;   /* File-name for the master journal */
48859    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
48860    sqlite3_file *pMaster = 0;
48861    i64 offset = 0;
48862    int res;
48863
48864    /* Select a master journal file name */
48865    do {
48866      u32 iRandom;
48867      sqlite3DbFree(db, zMaster);
48868      sqlite3_randomness(sizeof(iRandom), &iRandom);
48869      zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
48870      if( !zMaster ){
48871        return SQLITE_NOMEM;
48872      }
48873      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
48874    }while( rc==SQLITE_OK && res );
48875    if( rc==SQLITE_OK ){
48876      /* Open the master journal. */
48877      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
48878          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
48879          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
48880      );
48881    }
48882    if( rc!=SQLITE_OK ){
48883      sqlite3DbFree(db, zMaster);
48884      return rc;
48885    }
48886
48887    /* Write the name of each database file in the transaction into the new
48888    ** master journal file. If an error occurs at this point close
48889    ** and delete the master journal file. All the individual journal files
48890    ** still have 'null' as the master journal pointer, so they will roll
48891    ** back independently if a failure occurs.
48892    */
48893    for(i=0; i<db->nDb; i++){
48894      Btree *pBt = db->aDb[i].pBt;
48895      if( sqlite3BtreeIsInTrans(pBt) ){
48896        char const *zFile = sqlite3BtreeGetJournalname(pBt);
48897        if( zFile==0 || zFile[0]==0 ){
48898          continue;  /* Ignore TEMP and :memory: databases */
48899        }
48900        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
48901          needSync = 1;
48902        }
48903        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
48904        offset += sqlite3Strlen30(zFile)+1;
48905        if( rc!=SQLITE_OK ){
48906          sqlite3OsCloseFree(pMaster);
48907          sqlite3OsDelete(pVfs, zMaster, 0);
48908          sqlite3DbFree(db, zMaster);
48909          return rc;
48910        }
48911      }
48912    }
48913
48914    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
48915    ** flag is set this is not required.
48916    */
48917    if( needSync
48918     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
48919     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
48920    ){
48921      sqlite3OsCloseFree(pMaster);
48922      sqlite3OsDelete(pVfs, zMaster, 0);
48923      sqlite3DbFree(db, zMaster);
48924      return rc;
48925    }
48926
48927    /* Sync all the db files involved in the transaction. The same call
48928    ** sets the master journal pointer in each individual journal. If
48929    ** an error occurs here, do not delete the master journal file.
48930    **
48931    ** If the error occurs during the first call to
48932    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
48933    ** master journal file will be orphaned. But we cannot delete it,
48934    ** in case the master journal file name was written into the journal
48935    ** file before the failure occurred.
48936    */
48937    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
48938      Btree *pBt = db->aDb[i].pBt;
48939      if( pBt ){
48940        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
48941      }
48942    }
48943    sqlite3OsCloseFree(pMaster);
48944    if( rc!=SQLITE_OK ){
48945      sqlite3DbFree(db, zMaster);
48946      return rc;
48947    }
48948
48949    /* Delete the master journal file. This commits the transaction. After
48950    ** doing this the directory is synced again before any individual
48951    ** transaction files are deleted.
48952    */
48953    rc = sqlite3OsDelete(pVfs, zMaster, 1);
48954    sqlite3DbFree(db, zMaster);
48955    zMaster = 0;
48956    if( rc ){
48957      return rc;
48958    }
48959
48960    /* All files and directories have already been synced, so the following
48961    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
48962    ** deleting or truncating journals. If something goes wrong while
48963    ** this is happening we don't really care. The integrity of the
48964    ** transaction is already guaranteed, but some stray 'cold' journals
48965    ** may be lying around. Returning an error code won't help matters.
48966    */
48967    disable_simulated_io_errors();
48968    sqlite3BeginBenignMalloc();
48969    for(i=0; i<db->nDb; i++){
48970      Btree *pBt = db->aDb[i].pBt;
48971      if( pBt ){
48972        sqlite3BtreeCommitPhaseTwo(pBt);
48973      }
48974    }
48975    sqlite3EndBenignMalloc();
48976    enable_simulated_io_errors();
48977
48978    sqlite3VtabCommit(db);
48979  }
48980#endif
48981
48982  return rc;
48983}
48984
48985/*
48986** This routine checks that the sqlite3.activeVdbeCnt count variable
48987** matches the number of vdbe's in the list sqlite3.pVdbe that are
48988** currently active. An assertion fails if the two counts do not match.
48989** This is an internal self-check only - it is not an essential processing
48990** step.
48991**
48992** This is a no-op if NDEBUG is defined.
48993*/
48994#ifndef NDEBUG
48995static void checkActiveVdbeCnt(sqlite3 *db){
48996  Vdbe *p;
48997  int cnt = 0;
48998  int nWrite = 0;
48999  p = db->pVdbe;
49000  while( p ){
49001    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
49002      cnt++;
49003      if( p->readOnly==0 ) nWrite++;
49004    }
49005    p = p->pNext;
49006  }
49007  assert( cnt==db->activeVdbeCnt );
49008  assert( nWrite==db->writeVdbeCnt );
49009}
49010#else
49011#define checkActiveVdbeCnt(x)
49012#endif
49013
49014/*
49015** For every Btree that in database connection db which
49016** has been modified, "trip" or invalidate each cursor in
49017** that Btree might have been modified so that the cursor
49018** can never be used again.  This happens when a rollback
49019*** occurs.  We have to trip all the other cursors, even
49020** cursor from other VMs in different database connections,
49021** so that none of them try to use the data at which they
49022** were pointing and which now may have been changed due
49023** to the rollback.
49024**
49025** Remember that a rollback can delete tables complete and
49026** reorder rootpages.  So it is not sufficient just to save
49027** the state of the cursor.  We have to invalidate the cursor
49028** so that it is never used again.
49029*/
49030static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
49031  int i;
49032  for(i=0; i<db->nDb; i++){
49033    Btree *p = db->aDb[i].pBt;
49034    if( p && sqlite3BtreeIsInTrans(p) ){
49035      sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
49036    }
49037  }
49038}
49039
49040/*
49041** If the Vdbe passed as the first argument opened a statement-transaction,
49042** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
49043** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
49044** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
49045** statement transaction is commtted.
49046**
49047** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
49048** Otherwise SQLITE_OK.
49049*/
49050SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
49051  sqlite3 *const db = p->db;
49052  int rc = SQLITE_OK;
49053
49054  /* If p->iStatement is greater than zero, then this Vdbe opened a
49055  ** statement transaction that should be closed here. The only exception
49056  ** is that an IO error may have occured, causing an emergency rollback.
49057  ** In this case (db->nStatement==0), and there is nothing to do.
49058  */
49059  if( db->nStatement && p->iStatement ){
49060    int i;
49061    const int iSavepoint = p->iStatement-1;
49062
49063    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
49064    assert( db->nStatement>0 );
49065    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
49066
49067    for(i=0; i<db->nDb; i++){
49068      int rc2 = SQLITE_OK;
49069      Btree *pBt = db->aDb[i].pBt;
49070      if( pBt ){
49071        if( eOp==SAVEPOINT_ROLLBACK ){
49072          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
49073        }
49074        if( rc2==SQLITE_OK ){
49075          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
49076        }
49077        if( rc==SQLITE_OK ){
49078          rc = rc2;
49079        }
49080      }
49081    }
49082    db->nStatement--;
49083    p->iStatement = 0;
49084
49085    /* If the statement transaction is being rolled back, also restore the
49086    ** database handles deferred constraint counter to the value it had when
49087    ** the statement transaction was opened.  */
49088    if( eOp==SAVEPOINT_ROLLBACK ){
49089      db->nDeferredCons = p->nStmtDefCons;
49090    }
49091  }
49092  return rc;
49093}
49094
49095/*
49096** If SQLite is compiled to support shared-cache mode and to be threadsafe,
49097** this routine obtains the mutex associated with each BtShared structure
49098** that may be accessed by the VM passed as an argument. In doing so it
49099** sets the BtShared.db member of each of the BtShared structures, ensuring
49100** that the correct busy-handler callback is invoked if required.
49101**
49102** If SQLite is not threadsafe but does support shared-cache mode, then
49103** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
49104** of all of BtShared structures accessible via the database handle
49105** associated with the VM. Of course only a subset of these structures
49106** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
49107** that subset out, but there is no advantage to doing so.
49108**
49109** If SQLite is not threadsafe and does not support shared-cache mode, this
49110** function is a no-op.
49111*/
49112#ifndef SQLITE_OMIT_SHARED_CACHE
49113SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
49114#if SQLITE_THREADSAFE
49115  sqlite3BtreeMutexArrayEnter(&p->aMutex);
49116#else
49117  sqlite3BtreeEnterAll(p->db);
49118#endif
49119}
49120#endif
49121
49122/*
49123** This function is called when a transaction opened by the database
49124** handle associated with the VM passed as an argument is about to be
49125** committed. If there are outstanding deferred foreign key constraint
49126** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
49127**
49128** If there are outstanding FK violations and this function returns
49129** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
49130** an error message to it. Then return SQLITE_ERROR.
49131*/
49132#ifndef SQLITE_OMIT_FOREIGN_KEY
49133SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
49134  sqlite3 *db = p->db;
49135  if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
49136    p->rc = SQLITE_CONSTRAINT;
49137    p->errorAction = OE_Abort;
49138    sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
49139    return SQLITE_ERROR;
49140  }
49141  return SQLITE_OK;
49142}
49143#endif
49144
49145/*
49146** This routine is called the when a VDBE tries to halt.  If the VDBE
49147** has made changes and is in autocommit mode, then commit those
49148** changes.  If a rollback is needed, then do the rollback.
49149**
49150** This routine is the only way to move the state of a VM from
49151** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
49152** call this on a VM that is in the SQLITE_MAGIC_HALT state.
49153**
49154** Return an error code.  If the commit could not complete because of
49155** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
49156** means the close did not happen and needs to be repeated.
49157*/
49158SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
49159  int rc;                         /* Used to store transient return codes */
49160  sqlite3 *db = p->db;
49161
49162  /* This function contains the logic that determines if a statement or
49163  ** transaction will be committed or rolled back as a result of the
49164  ** execution of this virtual machine.
49165  **
49166  ** If any of the following errors occur:
49167  **
49168  **     SQLITE_NOMEM
49169  **     SQLITE_IOERR
49170  **     SQLITE_FULL
49171  **     SQLITE_INTERRUPT
49172  **
49173  ** Then the internal cache might have been left in an inconsistent
49174  ** state.  We need to rollback the statement transaction, if there is
49175  ** one, or the complete transaction if there is no statement transaction.
49176  */
49177
49178  if( p->db->mallocFailed ){
49179    p->rc = SQLITE_NOMEM;
49180  }
49181  closeAllCursors(p);
49182  if( p->magic!=VDBE_MAGIC_RUN ){
49183    return SQLITE_OK;
49184  }
49185  checkActiveVdbeCnt(db);
49186
49187  /* No commit or rollback needed if the program never started */
49188  if( p->pc>=0 ){
49189    int mrc;   /* Primary error code from p->rc */
49190    int eStatementOp = 0;
49191    int isSpecialError;            /* Set to true if a 'special' error */
49192
49193    /* Lock all btrees used by the statement */
49194    sqlite3VdbeMutexArrayEnter(p);
49195
49196    /* Check for one of the special errors */
49197    mrc = p->rc & 0xff;
49198    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
49199    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
49200                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
49201    if( isSpecialError ){
49202      /* If the query was read-only, we need do no rollback at all. Otherwise,
49203      ** proceed with the special handling.
49204      */
49205      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
49206        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
49207          eStatementOp = SAVEPOINT_ROLLBACK;
49208        }else{
49209          /* We are forced to roll back the active transaction. Before doing
49210          ** so, abort any other statements this handle currently has active.
49211          */
49212          invalidateCursorsOnModifiedBtrees(db);
49213          sqlite3RollbackAll(db);
49214          sqlite3CloseSavepoints(db);
49215          db->autoCommit = 1;
49216        }
49217      }
49218    }
49219
49220    /* Check for immediate foreign key violations. */
49221    if( p->rc==SQLITE_OK ){
49222      sqlite3VdbeCheckFk(p, 0);
49223    }
49224
49225    /* If the auto-commit flag is set and this is the only active writer
49226    ** VM, then we do either a commit or rollback of the current transaction.
49227    **
49228    ** Note: This block also runs if one of the special errors handled
49229    ** above has occurred.
49230    */
49231    if( !sqlite3VtabInSync(db)
49232     && db->autoCommit
49233     && db->writeVdbeCnt==(p->readOnly==0)
49234    ){
49235      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
49236        if( sqlite3VdbeCheckFk(p, 1) ){
49237          sqlite3BtreeMutexArrayLeave(&p->aMutex);
49238          return SQLITE_ERROR;
49239        }
49240        /* The auto-commit flag is true, the vdbe program was successful
49241        ** or hit an 'OR FAIL' constraint and there are no deferred foreign
49242        ** key constraints to hold up the transaction. This means a commit
49243        ** is required.  */
49244        rc = vdbeCommit(db, p);
49245        if( rc==SQLITE_BUSY ){
49246          sqlite3BtreeMutexArrayLeave(&p->aMutex);
49247          return SQLITE_BUSY;
49248        }else if( rc!=SQLITE_OK ){
49249          p->rc = rc;
49250          sqlite3RollbackAll(db);
49251        }else{
49252          db->nDeferredCons = 0;
49253          sqlite3CommitInternalChanges(db);
49254        }
49255      }else{
49256        sqlite3RollbackAll(db);
49257      }
49258      db->nStatement = 0;
49259    }else if( eStatementOp==0 ){
49260      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
49261        eStatementOp = SAVEPOINT_RELEASE;
49262      }else if( p->errorAction==OE_Abort ){
49263        eStatementOp = SAVEPOINT_ROLLBACK;
49264      }else{
49265        invalidateCursorsOnModifiedBtrees(db);
49266        sqlite3RollbackAll(db);
49267        sqlite3CloseSavepoints(db);
49268        db->autoCommit = 1;
49269      }
49270    }
49271
49272    /* If eStatementOp is non-zero, then a statement transaction needs to
49273    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
49274    ** do so. If this operation returns an error, and the current statement
49275    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then set the error
49276    ** code to the new value.
49277    */
49278    if( eStatementOp ){
49279      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
49280      if( rc && (p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT) ){
49281        p->rc = rc;
49282        sqlite3DbFree(db, p->zErrMsg);
49283        p->zErrMsg = 0;
49284      }
49285    }
49286
49287    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
49288    ** has been rolled back, update the database connection change-counter.
49289    */
49290    if( p->changeCntOn ){
49291      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
49292        sqlite3VdbeSetChanges(db, p->nChange);
49293      }else{
49294        sqlite3VdbeSetChanges(db, 0);
49295      }
49296      p->nChange = 0;
49297    }
49298
49299    /* Rollback or commit any schema changes that occurred. */
49300    if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
49301      sqlite3ResetInternalSchema(db, 0);
49302      db->flags = (db->flags | SQLITE_InternChanges);
49303    }
49304
49305    /* Release the locks */
49306    sqlite3BtreeMutexArrayLeave(&p->aMutex);
49307  }
49308
49309  /* We have successfully halted and closed the VM.  Record this fact. */
49310  if( p->pc>=0 ){
49311    db->activeVdbeCnt--;
49312    if( !p->readOnly ){
49313      db->writeVdbeCnt--;
49314    }
49315    assert( db->activeVdbeCnt>=db->writeVdbeCnt );
49316  }
49317  p->magic = VDBE_MAGIC_HALT;
49318  checkActiveVdbeCnt(db);
49319  if( p->db->mallocFailed ){
49320    p->rc = SQLITE_NOMEM;
49321  }
49322
49323  /* If the auto-commit flag is set to true, then any locks that were held
49324  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
49325  ** to invoke any required unlock-notify callbacks.
49326  */
49327  if( db->autoCommit ){
49328    sqlite3ConnectionUnlocked(db);
49329  }
49330
49331  assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
49332  return SQLITE_OK;
49333}
49334
49335
49336/*
49337** Each VDBE holds the result of the most recent sqlite3_step() call
49338** in p->rc.  This routine sets that result back to SQLITE_OK.
49339*/
49340SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
49341  p->rc = SQLITE_OK;
49342}
49343
49344/*
49345** Clean up a VDBE after execution but do not delete the VDBE just yet.
49346** Write any error messages into *pzErrMsg.  Return the result code.
49347**
49348** After this routine is run, the VDBE should be ready to be executed
49349** again.
49350**
49351** To look at it another way, this routine resets the state of the
49352** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
49353** VDBE_MAGIC_INIT.
49354*/
49355SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
49356  sqlite3 *db;
49357  db = p->db;
49358
49359  /* If the VM did not run to completion or if it encountered an
49360  ** error, then it might not have been halted properly.  So halt
49361  ** it now.
49362  */
49363  (void)sqlite3SafetyOn(db);
49364  sqlite3VdbeHalt(p);
49365  (void)sqlite3SafetyOff(db);
49366
49367  /* If the VDBE has be run even partially, then transfer the error code
49368  ** and error message from the VDBE into the main database structure.  But
49369  ** if the VDBE has just been set to run but has not actually executed any
49370  ** instructions yet, leave the main database error information unchanged.
49371  */
49372  if( p->pc>=0 ){
49373    if( p->zErrMsg ){
49374      sqlite3BeginBenignMalloc();
49375      sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
49376      sqlite3EndBenignMalloc();
49377      db->errCode = p->rc;
49378      sqlite3DbFree(db, p->zErrMsg);
49379      p->zErrMsg = 0;
49380    }else if( p->rc ){
49381      sqlite3Error(db, p->rc, 0);
49382    }else{
49383      sqlite3Error(db, SQLITE_OK, 0);
49384    }
49385  }else if( p->rc && p->expired ){
49386    /* The expired flag was set on the VDBE before the first call
49387    ** to sqlite3_step(). For consistency (since sqlite3_step() was
49388    ** called), set the database error in this case as well.
49389    */
49390    sqlite3Error(db, p->rc, 0);
49391    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
49392    sqlite3DbFree(db, p->zErrMsg);
49393    p->zErrMsg = 0;
49394  }
49395
49396  /* Reclaim all memory used by the VDBE
49397  */
49398  Cleanup(p);
49399
49400  /* Save profiling information from this VDBE run.
49401  */
49402#ifdef VDBE_PROFILE
49403  {
49404    FILE *out = fopen("vdbe_profile.out", "a");
49405    if( out ){
49406      int i;
49407      fprintf(out, "---- ");
49408      for(i=0; i<p->nOp; i++){
49409        fprintf(out, "%02x", p->aOp[i].opcode);
49410      }
49411      fprintf(out, "\n");
49412      for(i=0; i<p->nOp; i++){
49413        fprintf(out, "%6d %10lld %8lld ",
49414           p->aOp[i].cnt,
49415           p->aOp[i].cycles,
49416           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
49417        );
49418        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
49419      }
49420      fclose(out);
49421    }
49422  }
49423#endif
49424  p->magic = VDBE_MAGIC_INIT;
49425  return p->rc & db->errMask;
49426}
49427
49428/*
49429** Clean up and delete a VDBE after execution.  Return an integer which is
49430** the result code.  Write any error message text into *pzErrMsg.
49431*/
49432SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
49433  int rc = SQLITE_OK;
49434  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
49435    rc = sqlite3VdbeReset(p);
49436    assert( (rc & p->db->errMask)==rc );
49437  }
49438  sqlite3VdbeDelete(p);
49439  return rc;
49440}
49441
49442/*
49443** Call the destructor for each auxdata entry in pVdbeFunc for which
49444** the corresponding bit in mask is clear.  Auxdata entries beyond 31
49445** are always destroyed.  To destroy all auxdata entries, call this
49446** routine with mask==0.
49447*/
49448SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
49449  int i;
49450  for(i=0; i<pVdbeFunc->nAux; i++){
49451    struct AuxData *pAux = &pVdbeFunc->apAux[i];
49452    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
49453      if( pAux->xDelete ){
49454        pAux->xDelete(pAux->pAux);
49455      }
49456      pAux->pAux = 0;
49457    }
49458  }
49459}
49460
49461/*
49462** Delete an entire VDBE.
49463*/
49464SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
49465  sqlite3 *db;
49466
49467  if( NEVER(p==0) ) return;
49468  db = p->db;
49469  if( p->pPrev ){
49470    p->pPrev->pNext = p->pNext;
49471  }else{
49472    assert( db->pVdbe==p );
49473    db->pVdbe = p->pNext;
49474  }
49475  if( p->pNext ){
49476    p->pNext->pPrev = p->pPrev;
49477  }
49478  releaseMemArray(p->aVar, p->nVar);
49479  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
49480  vdbeFreeOpArray(db, p->aOp, p->nOp);
49481  sqlite3DbFree(db, p->aLabel);
49482  sqlite3DbFree(db, p->aColName);
49483  sqlite3DbFree(db, p->zSql);
49484  p->magic = VDBE_MAGIC_DEAD;
49485  sqlite3DbFree(db, p->pFree);
49486  sqlite3DbFree(db, p);
49487}
49488
49489/*
49490** Make sure the cursor p is ready to read or write the row to which it
49491** was last positioned.  Return an error code if an OOM fault or I/O error
49492** prevents us from positioning the cursor to its correct position.
49493**
49494** If a MoveTo operation is pending on the given cursor, then do that
49495** MoveTo now.  If no move is pending, check to see if the row has been
49496** deleted out from under the cursor and if it has, mark the row as
49497** a NULL row.
49498**
49499** If the cursor is already pointing to the correct row and that row has
49500** not been deleted out from under the cursor, then this routine is a no-op.
49501*/
49502SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
49503  if( p->deferredMoveto ){
49504    int res, rc;
49505#ifdef SQLITE_TEST
49506    extern int sqlite3_search_count;
49507#endif
49508    assert( p->isTable );
49509    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
49510    if( rc ) return rc;
49511    p->lastRowid = p->movetoTarget;
49512    p->rowidIsValid = ALWAYS(res==0) ?1:0;
49513    if( NEVER(res<0) ){
49514      rc = sqlite3BtreeNext(p->pCursor, &res);
49515      if( rc ) return rc;
49516    }
49517#ifdef SQLITE_TEST
49518    sqlite3_search_count++;
49519#endif
49520    p->deferredMoveto = 0;
49521    p->cacheStatus = CACHE_STALE;
49522  }else if( ALWAYS(p->pCursor) ){
49523    int hasMoved;
49524    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
49525    if( rc ) return rc;
49526    if( hasMoved ){
49527      p->cacheStatus = CACHE_STALE;
49528      p->nullRow = 1;
49529    }
49530  }
49531  return SQLITE_OK;
49532}
49533
49534/*
49535** The following functions:
49536**
49537** sqlite3VdbeSerialType()
49538** sqlite3VdbeSerialTypeLen()
49539** sqlite3VdbeSerialLen()
49540** sqlite3VdbeSerialPut()
49541** sqlite3VdbeSerialGet()
49542**
49543** encapsulate the code that serializes values for storage in SQLite
49544** data and index records. Each serialized value consists of a
49545** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
49546** integer, stored as a varint.
49547**
49548** In an SQLite index record, the serial type is stored directly before
49549** the blob of data that it corresponds to. In a table record, all serial
49550** types are stored at the start of the record, and the blobs of data at
49551** the end. Hence these functions allow the caller to handle the
49552** serial-type and data blob seperately.
49553**
49554** The following table describes the various storage classes for data:
49555**
49556**   serial type        bytes of data      type
49557**   --------------     ---------------    ---------------
49558**      0                     0            NULL
49559**      1                     1            signed integer
49560**      2                     2            signed integer
49561**      3                     3            signed integer
49562**      4                     4            signed integer
49563**      5                     6            signed integer
49564**      6                     8            signed integer
49565**      7                     8            IEEE float
49566**      8                     0            Integer constant 0
49567**      9                     0            Integer constant 1
49568**     10,11                               reserved for expansion
49569**    N>=12 and even       (N-12)/2        BLOB
49570**    N>=13 and odd        (N-13)/2        text
49571**
49572** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
49573** of SQLite will not understand those serial types.
49574*/
49575
49576/*
49577** Return the serial-type for the value stored in pMem.
49578*/
49579SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
49580  int flags = pMem->flags;
49581  int n;
49582
49583  if( flags&MEM_Null ){
49584    return 0;
49585  }
49586  if( flags&MEM_Int ){
49587    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
49588#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
49589    i64 i = pMem->u.i;
49590    u64 u;
49591    if( file_format>=4 && (i&1)==i ){
49592      return 8+(u32)i;
49593    }
49594    u = i<0 ? -i : i;
49595    if( u<=127 ) return 1;
49596    if( u<=32767 ) return 2;
49597    if( u<=8388607 ) return 3;
49598    if( u<=2147483647 ) return 4;
49599    if( u<=MAX_6BYTE ) return 5;
49600    return 6;
49601  }
49602  if( flags&MEM_Real ){
49603    return 7;
49604  }
49605  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
49606  n = pMem->n;
49607  if( flags & MEM_Zero ){
49608    n += pMem->u.nZero;
49609  }
49610  assert( n>=0 );
49611  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
49612}
49613
49614/*
49615** Return the length of the data corresponding to the supplied serial-type.
49616*/
49617SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
49618  if( serial_type>=12 ){
49619    return (serial_type-12)/2;
49620  }else{
49621    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
49622    return aSize[serial_type];
49623  }
49624}
49625
49626/*
49627** If we are on an architecture with mixed-endian floating
49628** points (ex: ARM7) then swap the lower 4 bytes with the
49629** upper 4 bytes.  Return the result.
49630**
49631** For most architectures, this is a no-op.
49632**
49633** (later):  It is reported to me that the mixed-endian problem
49634** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
49635** that early versions of GCC stored the two words of a 64-bit
49636** float in the wrong order.  And that error has been propagated
49637** ever since.  The blame is not necessarily with GCC, though.
49638** GCC might have just copying the problem from a prior compiler.
49639** I am also told that newer versions of GCC that follow a different
49640** ABI get the byte order right.
49641**
49642** Developers using SQLite on an ARM7 should compile and run their
49643** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
49644** enabled, some asserts below will ensure that the byte order of
49645** floating point values is correct.
49646**
49647** (2007-08-30)  Frank van Vugt has studied this problem closely
49648** and has send his findings to the SQLite developers.  Frank
49649** writes that some Linux kernels offer floating point hardware
49650** emulation that uses only 32-bit mantissas instead of a full
49651** 48-bits as required by the IEEE standard.  (This is the
49652** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
49653** byte swapping becomes very complicated.  To avoid problems,
49654** the necessary byte swapping is carried out using a 64-bit integer
49655** rather than a 64-bit float.  Frank assures us that the code here
49656** works for him.  We, the developers, have no way to independently
49657** verify this, but Frank seems to know what he is talking about
49658** so we trust him.
49659*/
49660#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
49661static u64 floatSwap(u64 in){
49662  union {
49663    u64 r;
49664    u32 i[2];
49665  } u;
49666  u32 t;
49667
49668  u.r = in;
49669  t = u.i[0];
49670  u.i[0] = u.i[1];
49671  u.i[1] = t;
49672  return u.r;
49673}
49674# define swapMixedEndianFloat(X)  X = floatSwap(X)
49675#else
49676# define swapMixedEndianFloat(X)
49677#endif
49678
49679/*
49680** Write the serialized data blob for the value stored in pMem into
49681** buf. It is assumed that the caller has allocated sufficient space.
49682** Return the number of bytes written.
49683**
49684** nBuf is the amount of space left in buf[].  nBuf must always be
49685** large enough to hold the entire field.  Except, if the field is
49686** a blob with a zero-filled tail, then buf[] might be just the right
49687** size to hold everything except for the zero-filled tail.  If buf[]
49688** is only big enough to hold the non-zero prefix, then only write that
49689** prefix into buf[].  But if buf[] is large enough to hold both the
49690** prefix and the tail then write the prefix and set the tail to all
49691** zeros.
49692**
49693** Return the number of bytes actually written into buf[].  The number
49694** of bytes in the zero-filled tail is included in the return value only
49695** if those bytes were zeroed in buf[].
49696*/
49697SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
49698  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
49699  u32 len;
49700
49701  /* Integer and Real */
49702  if( serial_type<=7 && serial_type>0 ){
49703    u64 v;
49704    u32 i;
49705    if( serial_type==7 ){
49706      assert( sizeof(v)==sizeof(pMem->r) );
49707      memcpy(&v, &pMem->r, sizeof(v));
49708      swapMixedEndianFloat(v);
49709    }else{
49710      v = pMem->u.i;
49711    }
49712    len = i = sqlite3VdbeSerialTypeLen(serial_type);
49713    assert( len<=(u32)nBuf );
49714    while( i-- ){
49715      buf[i] = (u8)(v&0xFF);
49716      v >>= 8;
49717    }
49718    return len;
49719  }
49720
49721  /* String or blob */
49722  if( serial_type>=12 ){
49723    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
49724             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
49725    assert( pMem->n<=nBuf );
49726    len = pMem->n;
49727    memcpy(buf, pMem->z, len);
49728    if( pMem->flags & MEM_Zero ){
49729      len += pMem->u.nZero;
49730      assert( nBuf>=0 );
49731      if( len > (u32)nBuf ){
49732        len = (u32)nBuf;
49733      }
49734      memset(&buf[pMem->n], 0, len-pMem->n);
49735    }
49736    return len;
49737  }
49738
49739  /* NULL or constants 0 or 1 */
49740  return 0;
49741}
49742
49743/*
49744** Deserialize the data blob pointed to by buf as serial type serial_type
49745** and store the result in pMem.  Return the number of bytes read.
49746*/
49747SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
49748  const unsigned char *buf,     /* Buffer to deserialize from */
49749  u32 serial_type,              /* Serial type to deserialize */
49750  Mem *pMem                     /* Memory cell to write value into */
49751){
49752  switch( serial_type ){
49753    case 10:   /* Reserved for future use */
49754    case 11:   /* Reserved for future use */
49755    case 0: {  /* NULL */
49756      pMem->flags = MEM_Null;
49757      break;
49758    }
49759    case 1: { /* 1-byte signed integer */
49760      pMem->u.i = (signed char)buf[0];
49761      pMem->flags = MEM_Int;
49762      return 1;
49763    }
49764    case 2: { /* 2-byte signed integer */
49765      pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
49766      pMem->flags = MEM_Int;
49767      return 2;
49768    }
49769    case 3: { /* 3-byte signed integer */
49770      pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
49771      pMem->flags = MEM_Int;
49772      return 3;
49773    }
49774    case 4: { /* 4-byte signed integer */
49775      pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
49776      pMem->flags = MEM_Int;
49777      return 4;
49778    }
49779    case 5: { /* 6-byte signed integer */
49780      u64 x = (((signed char)buf[0])<<8) | buf[1];
49781      u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
49782      x = (x<<32) | y;
49783      pMem->u.i = *(i64*)&x;
49784      pMem->flags = MEM_Int;
49785      return 6;
49786    }
49787    case 6:   /* 8-byte signed integer */
49788    case 7: { /* IEEE floating point */
49789      u64 x;
49790      u32 y;
49791#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
49792      /* Verify that integers and floating point values use the same
49793      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
49794      ** defined that 64-bit floating point values really are mixed
49795      ** endian.
49796      */
49797      static const u64 t1 = ((u64)0x3ff00000)<<32;
49798      static const double r1 = 1.0;
49799      u64 t2 = t1;
49800      swapMixedEndianFloat(t2);
49801      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
49802#endif
49803
49804      x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
49805      y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
49806      x = (x<<32) | y;
49807      if( serial_type==6 ){
49808        pMem->u.i = *(i64*)&x;
49809        pMem->flags = MEM_Int;
49810      }else{
49811        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
49812        swapMixedEndianFloat(x);
49813        memcpy(&pMem->r, &x, sizeof(x));
49814        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
49815      }
49816      return 8;
49817    }
49818    case 8:    /* Integer 0 */
49819    case 9: {  /* Integer 1 */
49820      pMem->u.i = serial_type-8;
49821      pMem->flags = MEM_Int;
49822      return 0;
49823    }
49824    default: {
49825      u32 len = (serial_type-12)/2;
49826      pMem->z = (char *)buf;
49827      pMem->n = len;
49828      pMem->xDel = 0;
49829      if( serial_type&0x01 ){
49830        pMem->flags = MEM_Str | MEM_Ephem;
49831      }else{
49832        pMem->flags = MEM_Blob | MEM_Ephem;
49833      }
49834      return len;
49835    }
49836  }
49837  return 0;
49838}
49839
49840
49841/*
49842** Given the nKey-byte encoding of a record in pKey[], parse the
49843** record into a UnpackedRecord structure.  Return a pointer to
49844** that structure.
49845**
49846** The calling function might provide szSpace bytes of memory
49847** space at pSpace.  This space can be used to hold the returned
49848** VDbeParsedRecord structure if it is large enough.  If it is
49849** not big enough, space is obtained from sqlite3_malloc().
49850**
49851** The returned structure should be closed by a call to
49852** sqlite3VdbeDeleteUnpackedRecord().
49853*/
49854SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
49855  KeyInfo *pKeyInfo,     /* Information about the record format */
49856  int nKey,              /* Size of the binary record */
49857  const void *pKey,      /* The binary record */
49858  char *pSpace,          /* Unaligned space available to hold the object */
49859  int szSpace            /* Size of pSpace[] in bytes */
49860){
49861  const unsigned char *aKey = (const unsigned char *)pKey;
49862  UnpackedRecord *p;  /* The unpacked record that we will return */
49863  int nByte;          /* Memory space needed to hold p, in bytes */
49864  int d;
49865  u32 idx;
49866  u16 u;              /* Unsigned loop counter */
49867  u32 szHdr;
49868  Mem *pMem;
49869  int nOff;           /* Increase pSpace by this much to 8-byte align it */
49870
49871  /*
49872  ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
49873  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
49874  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
49875  */
49876  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
49877  pSpace += nOff;
49878  szSpace -= nOff;
49879  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
49880  if( nByte>szSpace ){
49881    p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
49882    if( p==0 ) return 0;
49883    p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
49884  }else{
49885    p = (UnpackedRecord*)pSpace;
49886    p->flags = UNPACKED_NEED_DESTROY;
49887  }
49888  p->pKeyInfo = pKeyInfo;
49889  p->nField = pKeyInfo->nField + 1;
49890  p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
49891  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
49892  idx = getVarint32(aKey, szHdr);
49893  d = szHdr;
49894  u = 0;
49895  while( idx<szHdr && u<p->nField && d<=nKey ){
49896    u32 serial_type;
49897
49898    idx += getVarint32(&aKey[idx], serial_type);
49899    pMem->enc = pKeyInfo->enc;
49900    pMem->db = pKeyInfo->db;
49901    pMem->flags = 0;
49902    pMem->zMalloc = 0;
49903    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
49904    pMem++;
49905    u++;
49906  }
49907  assert( u<=pKeyInfo->nField + 1 );
49908  p->nField = u;
49909  return (void*)p;
49910}
49911
49912/*
49913** This routine destroys a UnpackedRecord object.
49914*/
49915SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
49916  int i;
49917  Mem *pMem;
49918
49919  assert( p!=0 );
49920  assert( p->flags & UNPACKED_NEED_DESTROY );
49921  for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
49922    /* The unpacked record is always constructed by the
49923    ** sqlite3VdbeUnpackRecord() function above, which makes all
49924    ** strings and blobs static.  And none of the elements are
49925    ** ever transformed, so there is never anything to delete.
49926    */
49927    if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
49928  }
49929  if( p->flags & UNPACKED_NEED_FREE ){
49930    sqlite3DbFree(p->pKeyInfo->db, p);
49931  }
49932}
49933
49934/*
49935** This function compares the two table rows or index records
49936** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
49937** or positive integer if key1 is less than, equal to or
49938** greater than key2.  The {nKey1, pKey1} key must be a blob
49939** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
49940** key must be a parsed key such as obtained from
49941** sqlite3VdbeParseRecord.
49942**
49943** Key1 and Key2 do not have to contain the same number of fields.
49944** The key with fewer fields is usually compares less than the
49945** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
49946** and the common prefixes are equal, then key1 is less than key2.
49947** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
49948** equal, then the keys are considered to be equal and
49949** the parts beyond the common prefix are ignored.
49950**
49951** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
49952** the header of pKey1 is ignored.  It is assumed that pKey1 is
49953** an index key, and thus ends with a rowid value.  The last byte
49954** of the header will therefore be the serial type of the rowid:
49955** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
49956** The serial type of the final rowid will always be a single byte.
49957** By ignoring this last byte of the header, we force the comparison
49958** to ignore the rowid at the end of key1.
49959*/
49960SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
49961  int nKey1, const void *pKey1, /* Left key */
49962  UnpackedRecord *pPKey2        /* Right key */
49963){
49964  int d1;            /* Offset into aKey[] of next data element */
49965  u32 idx1;          /* Offset into aKey[] of next header element */
49966  u32 szHdr1;        /* Number of bytes in header */
49967  int i = 0;
49968  int nField;
49969  int rc = 0;
49970  const unsigned char *aKey1 = (const unsigned char *)pKey1;
49971  KeyInfo *pKeyInfo;
49972  Mem mem1;
49973
49974  pKeyInfo = pPKey2->pKeyInfo;
49975  mem1.enc = pKeyInfo->enc;
49976  mem1.db = pKeyInfo->db;
49977  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
49978  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
49979
49980  /* Compilers may complain that mem1.u.i is potentially uninitialized.
49981  ** We could initialize it, as shown here, to silence those complaints.
49982  ** But in fact, mem1.u.i will never actually be used initialized, and doing
49983  ** the unnecessary initialization has a measurable negative performance
49984  ** impact, since this routine is a very high runner.  And so, we choose
49985  ** to ignore the compiler warnings and leave this variable uninitialized.
49986  */
49987  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
49988
49989  idx1 = getVarint32(aKey1, szHdr1);
49990  d1 = szHdr1;
49991  if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
49992    szHdr1--;
49993  }
49994  nField = pKeyInfo->nField;
49995  while( idx1<szHdr1 && i<pPKey2->nField ){
49996    u32 serial_type1;
49997
49998    /* Read the serial types for the next element in each key. */
49999    idx1 += getVarint32( aKey1+idx1, serial_type1 );
50000    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
50001
50002    /* Extract the values to be compared.
50003    */
50004    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
50005
50006    /* Do the comparison
50007    */
50008    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
50009                           i<nField ? pKeyInfo->aColl[i] : 0);
50010    if( rc!=0 ){
50011      assert( mem1.zMalloc==0 );  /* See comment below */
50012
50013      /* Invert the result if we are using DESC sort order. */
50014      if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
50015        rc = -rc;
50016      }
50017
50018      /* If the PREFIX_SEARCH flag is set and all fields except the final
50019      ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
50020      ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
50021      ** This is used by the OP_IsUnique opcode.
50022      */
50023      if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
50024        assert( idx1==szHdr1 && rc );
50025        assert( mem1.flags & MEM_Int );
50026        pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
50027        pPKey2->rowid = mem1.u.i;
50028      }
50029
50030      return rc;
50031    }
50032    i++;
50033  }
50034
50035  /* No memory allocation is ever used on mem1.  Prove this using
50036  ** the following assert().  If the assert() fails, it indicates a
50037  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
50038  */
50039  assert( mem1.zMalloc==0 );
50040
50041  /* rc==0 here means that one of the keys ran out of fields and
50042  ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
50043  ** flag is set, then break the tie by treating key2 as larger.
50044  ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
50045  ** are considered to be equal.  Otherwise, the longer key is the
50046  ** larger.  As it happens, the pPKey2 will always be the longer
50047  ** if there is a difference.
50048  */
50049  assert( rc==0 );
50050  if( pPKey2->flags & UNPACKED_INCRKEY ){
50051    rc = -1;
50052  }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
50053    /* Leave rc==0 */
50054  }else if( idx1<szHdr1 ){
50055    rc = 1;
50056  }
50057  return rc;
50058}
50059
50060
50061/*
50062** pCur points at an index entry created using the OP_MakeRecord opcode.
50063** Read the rowid (the last field in the record) and store it in *rowid.
50064** Return SQLITE_OK if everything works, or an error code otherwise.
50065**
50066** pCur might be pointing to text obtained from a corrupt database file.
50067** So the content cannot be trusted.  Do appropriate checks on the content.
50068*/
50069SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
50070  i64 nCellKey = 0;
50071  int rc;
50072  u32 szHdr;        /* Size of the header */
50073  u32 typeRowid;    /* Serial type of the rowid */
50074  u32 lenRowid;     /* Size of the rowid */
50075  Mem m, v;
50076
50077  UNUSED_PARAMETER(db);
50078
50079  /* Get the size of the index entry.  Only indices entries of less
50080  ** than 2GiB are support - anything large must be database corruption.
50081  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
50082  ** this code can safely assume that nCellKey is 32-bits
50083  */
50084  assert( sqlite3BtreeCursorIsValid(pCur) );
50085  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
50086  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
50087  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
50088
50089  /* Read in the complete content of the index entry */
50090  memset(&m, 0, sizeof(m));
50091  rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
50092  if( rc ){
50093    return rc;
50094  }
50095
50096  /* The index entry must begin with a header size */
50097  (void)getVarint32((u8*)m.z, szHdr);
50098  testcase( szHdr==3 );
50099  testcase( szHdr==m.n );
50100  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
50101    goto idx_rowid_corruption;
50102  }
50103
50104  /* The last field of the index should be an integer - the ROWID.
50105  ** Verify that the last entry really is an integer. */
50106  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
50107  testcase( typeRowid==1 );
50108  testcase( typeRowid==2 );
50109  testcase( typeRowid==3 );
50110  testcase( typeRowid==4 );
50111  testcase( typeRowid==5 );
50112  testcase( typeRowid==6 );
50113  testcase( typeRowid==8 );
50114  testcase( typeRowid==9 );
50115  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
50116    goto idx_rowid_corruption;
50117  }
50118  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
50119  testcase( (u32)m.n==szHdr+lenRowid );
50120  if( unlikely((u32)m.n<szHdr+lenRowid) ){
50121    goto idx_rowid_corruption;
50122  }
50123
50124  /* Fetch the integer off the end of the index record */
50125  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
50126  *rowid = v.u.i;
50127  sqlite3VdbeMemRelease(&m);
50128  return SQLITE_OK;
50129
50130  /* Jump here if database corruption is detected after m has been
50131  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
50132idx_rowid_corruption:
50133  testcase( m.zMalloc!=0 );
50134  sqlite3VdbeMemRelease(&m);
50135  return SQLITE_CORRUPT_BKPT;
50136}
50137
50138/*
50139** Compare the key of the index entry that cursor pC is pointing to against
50140** the key string in pUnpacked.  Write into *pRes a number
50141** that is negative, zero, or positive if pC is less than, equal to,
50142** or greater than pUnpacked.  Return SQLITE_OK on success.
50143**
50144** pUnpacked is either created without a rowid or is truncated so that it
50145** omits the rowid at the end.  The rowid at the end of the index entry
50146** is ignored as well.  Hence, this routine only compares the prefixes
50147** of the keys prior to the final rowid, not the entire key.
50148*/
50149SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
50150  VdbeCursor *pC,             /* The cursor to compare against */
50151  UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
50152  int *res                    /* Write the comparison result here */
50153){
50154  i64 nCellKey = 0;
50155  int rc;
50156  BtCursor *pCur = pC->pCursor;
50157  Mem m;
50158
50159  assert( sqlite3BtreeCursorIsValid(pCur) );
50160  rc = sqlite3BtreeKeySize(pCur, &nCellKey);
50161  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
50162  /* nCellKey will always be between 0 and 0xffffffff because of the say
50163  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
50164  if( nCellKey<=0 || nCellKey>0x7fffffff ){
50165    *res = 0;
50166    return SQLITE_CORRUPT;
50167  }
50168  memset(&m, 0, sizeof(m));
50169  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
50170  if( rc ){
50171    return rc;
50172  }
50173  assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
50174  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
50175  sqlite3VdbeMemRelease(&m);
50176  return SQLITE_OK;
50177}
50178
50179/*
50180** This routine sets the value to be returned by subsequent calls to
50181** sqlite3_changes() on the database handle 'db'.
50182*/
50183SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
50184  assert( sqlite3_mutex_held(db->mutex) );
50185  db->nChange = nChange;
50186  db->nTotalChange += nChange;
50187}
50188
50189/*
50190** Set a flag in the vdbe to update the change counter when it is finalised
50191** or reset.
50192*/
50193SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
50194  v->changeCntOn = 1;
50195}
50196
50197/*
50198** Mark every prepared statement associated with a database connection
50199** as expired.
50200**
50201** An expired statement means that recompilation of the statement is
50202** recommend.  Statements expire when things happen that make their
50203** programs obsolete.  Removing user-defined functions or collating
50204** sequences, or changing an authorization function are the types of
50205** things that make prepared statements obsolete.
50206*/
50207SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
50208  Vdbe *p;
50209  for(p = db->pVdbe; p; p=p->pNext){
50210    p->expired = 1;
50211  }
50212}
50213
50214/*
50215** Return the database associated with the Vdbe.
50216*/
50217SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
50218  return v->db;
50219}
50220
50221/*
50222** Return a pointer to an sqlite3_value structure containing the value bound
50223** parameter iVar of VM v. Except, if the value is an SQL NULL, return
50224** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
50225** constants) to the value before returning it.
50226**
50227** The returned value must be freed by the caller using sqlite3ValueFree().
50228*/
50229SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
50230  assert( iVar>0 );
50231  if( v ){
50232    Mem *pMem = &v->aVar[iVar-1];
50233    if( 0==(pMem->flags & MEM_Null) ){
50234      sqlite3_value *pRet = sqlite3ValueNew(v->db);
50235      if( pRet ){
50236        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
50237        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
50238        sqlite3VdbeMemStoreType((Mem *)pRet);
50239      }
50240      return pRet;
50241    }
50242  }
50243  return 0;
50244}
50245
50246/*
50247** Configure SQL variable iVar so that binding a new value to it signals
50248** to sqlite3_reoptimize() that re-preparing the statement may result
50249** in a better query plan.
50250*/
50251SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
50252  assert( iVar>0 );
50253  if( iVar>32 ){
50254    v->expmask = 0xffffffff;
50255  }else{
50256    v->expmask |= ((u32)1 << (iVar-1));
50257  }
50258}
50259
50260/************** End of vdbeaux.c *********************************************/
50261/************** Begin file vdbeapi.c *****************************************/
50262/*
50263** 2004 May 26
50264**
50265** The author disclaims copyright to this source code.  In place of
50266** a legal notice, here is a blessing:
50267**
50268**    May you do good and not evil.
50269**    May you find forgiveness for yourself and forgive others.
50270**    May you share freely, never taking more than you give.
50271**
50272*************************************************************************
50273**
50274** This file contains code use to implement APIs that are part of the
50275** VDBE.
50276*/
50277
50278#ifndef SQLITE_OMIT_DEPRECATED
50279/*
50280** Return TRUE (non-zero) of the statement supplied as an argument needs
50281** to be recompiled.  A statement needs to be recompiled whenever the
50282** execution environment changes in a way that would alter the program
50283** that sqlite3_prepare() generates.  For example, if new functions or
50284** collating sequences are registered or if an authorizer function is
50285** added or changed.
50286*/
50287SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
50288  Vdbe *p = (Vdbe*)pStmt;
50289  return p==0 || p->expired;
50290}
50291#endif
50292
50293/*
50294** The following routine destroys a virtual machine that is created by
50295** the sqlite3_compile() routine. The integer returned is an SQLITE_
50296** success/failure code that describes the result of executing the virtual
50297** machine.
50298**
50299** This routine sets the error code and string returned by
50300** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
50301*/
50302SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
50303  int rc;
50304  if( pStmt==0 ){
50305    rc = SQLITE_OK;
50306  }else{
50307    Vdbe *v = (Vdbe*)pStmt;
50308    sqlite3 *db = v->db;
50309#if SQLITE_THREADSAFE
50310    sqlite3_mutex *mutex = v->db->mutex;
50311#endif
50312    sqlite3_mutex_enter(mutex);
50313    rc = sqlite3VdbeFinalize(v);
50314    rc = sqlite3ApiExit(db, rc);
50315    sqlite3_mutex_leave(mutex);
50316  }
50317  return rc;
50318}
50319
50320/*
50321** Terminate the current execution of an SQL statement and reset it
50322** back to its starting state so that it can be reused. A success code from
50323** the prior execution is returned.
50324**
50325** This routine sets the error code and string returned by
50326** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
50327*/
50328SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
50329  int rc;
50330  if( pStmt==0 ){
50331    rc = SQLITE_OK;
50332  }else{
50333    Vdbe *v = (Vdbe*)pStmt;
50334    sqlite3_mutex_enter(v->db->mutex);
50335    rc = sqlite3VdbeReset(v);
50336    sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
50337    assert( (rc & (v->db->errMask))==rc );
50338    rc = sqlite3ApiExit(v->db, rc);
50339    sqlite3_mutex_leave(v->db->mutex);
50340  }
50341  return rc;
50342}
50343
50344/*
50345** Set all the parameters in the compiled SQL statement to NULL.
50346*/
50347SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
50348  int i;
50349  int rc = SQLITE_OK;
50350  Vdbe *p = (Vdbe*)pStmt;
50351#if SQLITE_THREADSAFE
50352  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
50353#endif
50354  sqlite3_mutex_enter(mutex);
50355  for(i=0; i<p->nVar; i++){
50356    sqlite3VdbeMemRelease(&p->aVar[i]);
50357    p->aVar[i].flags = MEM_Null;
50358  }
50359  if( p->isPrepareV2 && p->expmask ){
50360    p->expired = 1;
50361  }
50362  sqlite3_mutex_leave(mutex);
50363  return rc;
50364}
50365
50366
50367/**************************** sqlite3_value_  *******************************
50368** The following routines extract information from a Mem or sqlite3_value
50369** structure.
50370*/
50371SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
50372  Mem *p = (Mem*)pVal;
50373  if( p->flags & (MEM_Blob|MEM_Str) ){
50374    sqlite3VdbeMemExpandBlob(p);
50375    p->flags &= ~MEM_Str;
50376    p->flags |= MEM_Blob;
50377    return p->z;
50378  }else{
50379    return sqlite3_value_text(pVal);
50380  }
50381}
50382SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
50383  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
50384}
50385SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
50386  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
50387}
50388SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
50389  return sqlite3VdbeRealValue((Mem*)pVal);
50390}
50391SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
50392  return (int)sqlite3VdbeIntValue((Mem*)pVal);
50393}
50394SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
50395  return sqlite3VdbeIntValue((Mem*)pVal);
50396}
50397SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
50398  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
50399}
50400#ifndef SQLITE_OMIT_UTF16
50401SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
50402  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
50403}
50404SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
50405  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
50406}
50407SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
50408  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
50409}
50410#endif /* SQLITE_OMIT_UTF16 */
50411SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
50412  return pVal->type;
50413}
50414
50415/**************************** sqlite3_result_  *******************************
50416** The following routines are used by user-defined functions to specify
50417** the function result.
50418**
50419** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
50420** result as a string or blob but if the string or blob is too large, it
50421** then sets the error code to SQLITE_TOOBIG
50422*/
50423static void setResultStrOrError(
50424  sqlite3_context *pCtx,  /* Function context */
50425  const char *z,          /* String pointer */
50426  int n,                  /* Bytes in string, or negative */
50427  u8 enc,                 /* Encoding of z.  0 for BLOBs */
50428  void (*xDel)(void*)     /* Destructor function */
50429){
50430  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
50431    sqlite3_result_error_toobig(pCtx);
50432  }
50433}
50434SQLITE_API void sqlite3_result_blob(
50435  sqlite3_context *pCtx,
50436  const void *z,
50437  int n,
50438  void (*xDel)(void *)
50439){
50440  assert( n>=0 );
50441  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50442  setResultStrOrError(pCtx, z, n, 0, xDel);
50443}
50444SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
50445  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50446  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
50447}
50448SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
50449  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50450  pCtx->isError = SQLITE_ERROR;
50451  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
50452}
50453#ifndef SQLITE_OMIT_UTF16
50454SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
50455  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50456  pCtx->isError = SQLITE_ERROR;
50457  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
50458}
50459#endif
50460SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
50461  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50462  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
50463}
50464SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
50465  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50466  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
50467}
50468SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
50469  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50470  sqlite3VdbeMemSetNull(&pCtx->s);
50471}
50472SQLITE_API void sqlite3_result_text(
50473  sqlite3_context *pCtx,
50474  const char *z,
50475  int n,
50476  void (*xDel)(void *)
50477){
50478  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50479  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
50480}
50481#ifndef SQLITE_OMIT_UTF16
50482SQLITE_API void sqlite3_result_text16(
50483  sqlite3_context *pCtx,
50484  const void *z,
50485  int n,
50486  void (*xDel)(void *)
50487){
50488  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50489  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
50490}
50491SQLITE_API void sqlite3_result_text16be(
50492  sqlite3_context *pCtx,
50493  const void *z,
50494  int n,
50495  void (*xDel)(void *)
50496){
50497  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50498  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
50499}
50500SQLITE_API void sqlite3_result_text16le(
50501  sqlite3_context *pCtx,
50502  const void *z,
50503  int n,
50504  void (*xDel)(void *)
50505){
50506  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50507  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
50508}
50509#endif /* SQLITE_OMIT_UTF16 */
50510SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
50511  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50512  sqlite3VdbeMemCopy(&pCtx->s, pValue);
50513}
50514SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
50515  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50516  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
50517}
50518SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
50519  pCtx->isError = errCode;
50520  if( pCtx->s.flags & MEM_Null ){
50521    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
50522                         SQLITE_UTF8, SQLITE_STATIC);
50523  }
50524}
50525
50526/* Force an SQLITE_TOOBIG error. */
50527SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
50528  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50529  pCtx->isError = SQLITE_TOOBIG;
50530  sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
50531                       SQLITE_UTF8, SQLITE_STATIC);
50532}
50533
50534/* An SQLITE_NOMEM error. */
50535SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
50536  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50537  sqlite3VdbeMemSetNull(&pCtx->s);
50538  pCtx->isError = SQLITE_NOMEM;
50539  pCtx->s.db->mallocFailed = 1;
50540}
50541
50542/*
50543** Execute the statement pStmt, either until a row of data is ready, the
50544** statement is completely executed or an error occurs.
50545**
50546** This routine implements the bulk of the logic behind the sqlite_step()
50547** API.  The only thing omitted is the automatic recompile if a
50548** schema change has occurred.  That detail is handled by the
50549** outer sqlite3_step() wrapper procedure.
50550*/
50551static int sqlite3Step(Vdbe *p){
50552  sqlite3 *db;
50553  int rc;
50554
50555  assert(p);
50556  if( p->magic!=VDBE_MAGIC_RUN ){
50557    return SQLITE_MISUSE;
50558  }
50559
50560  /* Assert that malloc() has not failed */
50561  db = p->db;
50562  if( db->mallocFailed ){
50563    return SQLITE_NOMEM;
50564  }
50565
50566  if( p->pc<=0 && p->expired ){
50567    if( ALWAYS(p->rc==SQLITE_OK || p->rc==SQLITE_SCHEMA) ){
50568      p->rc = SQLITE_SCHEMA;
50569    }
50570    rc = SQLITE_ERROR;
50571    goto end_of_step;
50572  }
50573  if( sqlite3SafetyOn(db) ){
50574    p->rc = SQLITE_MISUSE;
50575    return SQLITE_MISUSE;
50576  }
50577  if( p->pc<0 ){
50578    /* If there are no other statements currently running, then
50579    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
50580    ** from interrupting a statement that has not yet started.
50581    */
50582    if( db->activeVdbeCnt==0 ){
50583      db->u1.isInterrupted = 0;
50584    }
50585
50586    assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
50587
50588#ifndef SQLITE_OMIT_TRACE
50589    if( db->xProfile && !db->init.busy ){
50590      double rNow;
50591      sqlite3OsCurrentTime(db->pVfs, &rNow);
50592      p->startTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
50593    }
50594#endif
50595
50596    db->activeVdbeCnt++;
50597    if( p->readOnly==0 ) db->writeVdbeCnt++;
50598    p->pc = 0;
50599  }
50600#ifndef SQLITE_OMIT_EXPLAIN
50601  if( p->explain ){
50602    rc = sqlite3VdbeList(p);
50603  }else
50604#endif /* SQLITE_OMIT_EXPLAIN */
50605  {
50606    rc = sqlite3VdbeExec(p);
50607  }
50608
50609  if( sqlite3SafetyOff(db) ){
50610    rc = SQLITE_MISUSE;
50611  }
50612
50613#ifndef SQLITE_OMIT_TRACE
50614  /* Invoke the profile callback if there is one
50615  */
50616  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
50617    double rNow;
50618    u64 elapseTime;
50619
50620    sqlite3OsCurrentTime(db->pVfs, &rNow);
50621    elapseTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
50622    elapseTime -= p->startTime;
50623    db->xProfile(db->pProfileArg, p->zSql, elapseTime);
50624  }
50625#endif
50626
50627  db->errCode = rc;
50628  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
50629    p->rc = SQLITE_NOMEM;
50630  }
50631end_of_step:
50632  /* At this point local variable rc holds the value that should be
50633  ** returned if this statement was compiled using the legacy
50634  ** sqlite3_prepare() interface. According to the docs, this can only
50635  ** be one of the values in the first assert() below. Variable p->rc
50636  ** contains the value that would be returned if sqlite3_finalize()
50637  ** were called on statement p.
50638  */
50639  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
50640       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
50641  );
50642  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
50643  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
50644    /* If this statement was prepared using sqlite3_prepare_v2(), and an
50645    ** error has occured, then return the error code in p->rc to the
50646    ** caller. Set the error code in the database handle to the same value.
50647    */
50648    rc = db->errCode = p->rc;
50649  }
50650  return (rc&db->errMask);
50651}
50652
50653/*
50654** This is the top-level implementation of sqlite3_step().  Call
50655** sqlite3Step() to do most of the work.  If a schema error occurs,
50656** call sqlite3Reprepare() and try again.
50657*/
50658SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
50659  int rc = SQLITE_MISUSE;
50660  if( pStmt ){
50661    int cnt = 0;
50662    Vdbe *v = (Vdbe*)pStmt;
50663    sqlite3 *db = v->db;
50664    sqlite3_mutex_enter(db->mutex);
50665    while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
50666           && cnt++ < 5
50667           && (rc = sqlite3Reprepare(v))==SQLITE_OK ){
50668      sqlite3_reset(pStmt);
50669      v->expired = 0;
50670    }
50671    if( rc==SQLITE_SCHEMA && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
50672      /* This case occurs after failing to recompile an sql statement.
50673      ** The error message from the SQL compiler has already been loaded
50674      ** into the database handle. This block copies the error message
50675      ** from the database handle into the statement and sets the statement
50676      ** program counter to 0 to ensure that when the statement is
50677      ** finalized or reset the parser error message is available via
50678      ** sqlite3_errmsg() and sqlite3_errcode().
50679      */
50680      const char *zErr = (const char *)sqlite3_value_text(db->pErr);
50681      sqlite3DbFree(db, v->zErrMsg);
50682      if( !db->mallocFailed ){
50683        v->zErrMsg = sqlite3DbStrDup(db, zErr);
50684      } else {
50685        v->zErrMsg = 0;
50686        v->rc = SQLITE_NOMEM;
50687      }
50688    }
50689    rc = sqlite3ApiExit(db, rc);
50690    sqlite3_mutex_leave(db->mutex);
50691  }
50692  return rc;
50693}
50694
50695/*
50696** Extract the user data from a sqlite3_context structure and return a
50697** pointer to it.
50698*/
50699SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
50700  assert( p && p->pFunc );
50701  return p->pFunc->pUserData;
50702}
50703
50704/*
50705** Extract the user data from a sqlite3_context structure and return a
50706** pointer to it.
50707*/
50708SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
50709  assert( p && p->pFunc );
50710  return p->s.db;
50711}
50712
50713/*
50714** The following is the implementation of an SQL function that always
50715** fails with an error message stating that the function is used in the
50716** wrong context.  The sqlite3_overload_function() API might construct
50717** SQL function that use this routine so that the functions will exist
50718** for name resolution but are actually overloaded by the xFindFunction
50719** method of virtual tables.
50720*/
50721SQLITE_PRIVATE void sqlite3InvalidFunction(
50722  sqlite3_context *context,  /* The function calling context */
50723  int NotUsed,               /* Number of arguments to the function */
50724  sqlite3_value **NotUsed2   /* Value of each argument */
50725){
50726  const char *zName = context->pFunc->zName;
50727  char *zErr;
50728  UNUSED_PARAMETER2(NotUsed, NotUsed2);
50729  zErr = sqlite3_mprintf(
50730      "unable to use function %s in the requested context", zName);
50731  sqlite3_result_error(context, zErr, -1);
50732  sqlite3_free(zErr);
50733}
50734
50735/*
50736** Allocate or return the aggregate context for a user function.  A new
50737** context is allocated on the first call.  Subsequent calls return the
50738** same context that was returned on prior calls.
50739*/
50740SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
50741  Mem *pMem;
50742  assert( p && p->pFunc && p->pFunc->xStep );
50743  assert( sqlite3_mutex_held(p->s.db->mutex) );
50744  pMem = p->pMem;
50745  testcase( nByte<0 );
50746  if( (pMem->flags & MEM_Agg)==0 ){
50747    if( nByte<=0 ){
50748      sqlite3VdbeMemReleaseExternal(pMem);
50749      pMem->flags = MEM_Null;
50750      pMem->z = 0;
50751    }else{
50752      sqlite3VdbeMemGrow(pMem, nByte, 0);
50753      pMem->flags = MEM_Agg;
50754      pMem->u.pDef = p->pFunc;
50755      if( pMem->z ){
50756        memset(pMem->z, 0, nByte);
50757      }
50758    }
50759  }
50760  return (void*)pMem->z;
50761}
50762
50763/*
50764** Return the auxilary data pointer, if any, for the iArg'th argument to
50765** the user-function defined by pCtx.
50766*/
50767SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
50768  VdbeFunc *pVdbeFunc;
50769
50770  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50771  pVdbeFunc = pCtx->pVdbeFunc;
50772  if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
50773    return 0;
50774  }
50775  return pVdbeFunc->apAux[iArg].pAux;
50776}
50777
50778/*
50779** Set the auxilary data pointer and delete function, for the iArg'th
50780** argument to the user-function defined by pCtx. Any previous value is
50781** deleted by calling the delete function specified when it was set.
50782*/
50783SQLITE_API void sqlite3_set_auxdata(
50784  sqlite3_context *pCtx,
50785  int iArg,
50786  void *pAux,
50787  void (*xDelete)(void*)
50788){
50789  struct AuxData *pAuxData;
50790  VdbeFunc *pVdbeFunc;
50791  if( iArg<0 ) goto failed;
50792
50793  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
50794  pVdbeFunc = pCtx->pVdbeFunc;
50795  if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
50796    int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
50797    int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
50798    pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
50799    if( !pVdbeFunc ){
50800      goto failed;
50801    }
50802    pCtx->pVdbeFunc = pVdbeFunc;
50803    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
50804    pVdbeFunc->nAux = iArg+1;
50805    pVdbeFunc->pFunc = pCtx->pFunc;
50806  }
50807
50808  pAuxData = &pVdbeFunc->apAux[iArg];
50809  if( pAuxData->pAux && pAuxData->xDelete ){
50810    pAuxData->xDelete(pAuxData->pAux);
50811  }
50812  pAuxData->pAux = pAux;
50813  pAuxData->xDelete = xDelete;
50814  return;
50815
50816failed:
50817  if( xDelete ){
50818    xDelete(pAux);
50819  }
50820}
50821
50822#ifndef SQLITE_OMIT_DEPRECATED
50823/*
50824** Return the number of times the Step function of a aggregate has been
50825** called.
50826**
50827** This function is deprecated.  Do not use it for new code.  It is
50828** provide only to avoid breaking legacy code.  New aggregate function
50829** implementations should keep their own counts within their aggregate
50830** context.
50831*/
50832SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
50833  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
50834  return p->pMem->n;
50835}
50836#endif
50837
50838/*
50839** Return the number of columns in the result set for the statement pStmt.
50840*/
50841SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
50842  Vdbe *pVm = (Vdbe *)pStmt;
50843  return pVm ? pVm->nResColumn : 0;
50844}
50845
50846/*
50847** Return the number of values available from the current row of the
50848** currently executing statement pStmt.
50849*/
50850SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
50851  Vdbe *pVm = (Vdbe *)pStmt;
50852  if( pVm==0 || pVm->pResultSet==0 ) return 0;
50853  return pVm->nResColumn;
50854}
50855
50856
50857/*
50858** Check to see if column iCol of the given statement is valid.  If
50859** it is, return a pointer to the Mem for the value of that column.
50860** If iCol is not valid, return a pointer to a Mem which has a value
50861** of NULL.
50862*/
50863static Mem *columnMem(sqlite3_stmt *pStmt, int i){
50864  Vdbe *pVm;
50865  int vals;
50866  Mem *pOut;
50867
50868  pVm = (Vdbe *)pStmt;
50869  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
50870    sqlite3_mutex_enter(pVm->db->mutex);
50871    vals = sqlite3_data_count(pStmt);
50872    pOut = &pVm->pResultSet[i];
50873  }else{
50874    /* If the value passed as the second argument is out of range, return
50875    ** a pointer to the following static Mem object which contains the
50876    ** value SQL NULL. Even though the Mem structure contains an element
50877    ** of type i64, on certain architecture (x86) with certain compiler
50878    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
50879    ** instead of an 8-byte one. This all works fine, except that when
50880    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
50881    ** that a Mem structure is located on an 8-byte boundary. To prevent
50882    ** this assert() from failing, when building with SQLITE_DEBUG defined
50883    ** using gcc, force nullMem to be 8-byte aligned using the magical
50884    ** __attribute__((aligned(8))) macro.  */
50885    static const Mem nullMem
50886#if defined(SQLITE_DEBUG) && defined(__GNUC__)
50887      __attribute__((aligned(8)))
50888#endif
50889      = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
50890
50891    if( pVm && ALWAYS(pVm->db) ){
50892      sqlite3_mutex_enter(pVm->db->mutex);
50893      sqlite3Error(pVm->db, SQLITE_RANGE, 0);
50894    }
50895    pOut = (Mem*)&nullMem;
50896  }
50897  return pOut;
50898}
50899
50900/*
50901** This function is called after invoking an sqlite3_value_XXX function on a
50902** column value (i.e. a value returned by evaluating an SQL expression in the
50903** select list of a SELECT statement) that may cause a malloc() failure. If
50904** malloc() has failed, the threads mallocFailed flag is cleared and the result
50905** code of statement pStmt set to SQLITE_NOMEM.
50906**
50907** Specifically, this is called from within:
50908**
50909**     sqlite3_column_int()
50910**     sqlite3_column_int64()
50911**     sqlite3_column_text()
50912**     sqlite3_column_text16()
50913**     sqlite3_column_real()
50914**     sqlite3_column_bytes()
50915**     sqlite3_column_bytes16()
50916**
50917** But not for sqlite3_column_blob(), which never calls malloc().
50918*/
50919static void columnMallocFailure(sqlite3_stmt *pStmt)
50920{
50921  /* If malloc() failed during an encoding conversion within an
50922  ** sqlite3_column_XXX API, then set the return code of the statement to
50923  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
50924  ** and _finalize() will return NOMEM.
50925  */
50926  Vdbe *p = (Vdbe *)pStmt;
50927  if( p ){
50928    p->rc = sqlite3ApiExit(p->db, p->rc);
50929    sqlite3_mutex_leave(p->db->mutex);
50930  }
50931}
50932
50933/**************************** sqlite3_column_  *******************************
50934** The following routines are used to access elements of the current row
50935** in the result set.
50936*/
50937SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
50938  const void *val;
50939  val = sqlite3_value_blob( columnMem(pStmt,i) );
50940  /* Even though there is no encoding conversion, value_blob() might
50941  ** need to call malloc() to expand the result of a zeroblob()
50942  ** expression.
50943  */
50944  columnMallocFailure(pStmt);
50945  return val;
50946}
50947SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
50948  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
50949  columnMallocFailure(pStmt);
50950  return val;
50951}
50952SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
50953  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
50954  columnMallocFailure(pStmt);
50955  return val;
50956}
50957SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
50958  double val = sqlite3_value_double( columnMem(pStmt,i) );
50959  columnMallocFailure(pStmt);
50960  return val;
50961}
50962SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
50963  int val = sqlite3_value_int( columnMem(pStmt,i) );
50964  columnMallocFailure(pStmt);
50965  return val;
50966}
50967SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
50968  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
50969  columnMallocFailure(pStmt);
50970  return val;
50971}
50972SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
50973  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
50974  columnMallocFailure(pStmt);
50975  return val;
50976}
50977SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
50978  Mem *pOut = columnMem(pStmt, i);
50979  if( pOut->flags&MEM_Static ){
50980    pOut->flags &= ~MEM_Static;
50981    pOut->flags |= MEM_Ephem;
50982  }
50983  columnMallocFailure(pStmt);
50984  return (sqlite3_value *)pOut;
50985}
50986#ifndef SQLITE_OMIT_UTF16
50987SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
50988  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
50989  columnMallocFailure(pStmt);
50990  return val;
50991}
50992#endif /* SQLITE_OMIT_UTF16 */
50993SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
50994  int iType = sqlite3_value_type( columnMem(pStmt,i) );
50995  columnMallocFailure(pStmt);
50996  return iType;
50997}
50998
50999/* The following function is experimental and subject to change or
51000** removal */
51001/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
51002**  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
51003**}
51004*/
51005
51006/*
51007** Convert the N-th element of pStmt->pColName[] into a string using
51008** xFunc() then return that string.  If N is out of range, return 0.
51009**
51010** There are up to 5 names for each column.  useType determines which
51011** name is returned.  Here are the names:
51012**
51013**    0      The column name as it should be displayed for output
51014**    1      The datatype name for the column
51015**    2      The name of the database that the column derives from
51016**    3      The name of the table that the column derives from
51017**    4      The name of the table column that the result column derives from
51018**
51019** If the result is not a simple column reference (if it is an expression
51020** or a constant) then useTypes 2, 3, and 4 return NULL.
51021*/
51022static const void *columnName(
51023  sqlite3_stmt *pStmt,
51024  int N,
51025  const void *(*xFunc)(Mem*),
51026  int useType
51027){
51028  const void *ret = 0;
51029  Vdbe *p = (Vdbe *)pStmt;
51030  int n;
51031  sqlite3 *db = p->db;
51032
51033  assert( db!=0 );
51034  n = sqlite3_column_count(pStmt);
51035  if( N<n && N>=0 ){
51036    N += useType*n;
51037    sqlite3_mutex_enter(db->mutex);
51038    assert( db->mallocFailed==0 );
51039    ret = xFunc(&p->aColName[N]);
51040     /* A malloc may have failed inside of the xFunc() call. If this
51041    ** is the case, clear the mallocFailed flag and return NULL.
51042    */
51043    if( db->mallocFailed ){
51044      db->mallocFailed = 0;
51045      ret = 0;
51046    }
51047    sqlite3_mutex_leave(db->mutex);
51048  }
51049  return ret;
51050}
51051
51052/*
51053** Return the name of the Nth column of the result set returned by SQL
51054** statement pStmt.
51055*/
51056SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
51057  return columnName(
51058      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
51059}
51060#ifndef SQLITE_OMIT_UTF16
51061SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
51062  return columnName(
51063      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
51064}
51065#endif
51066
51067/*
51068** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
51069** not define OMIT_DECLTYPE.
51070*/
51071#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
51072# error "Must not define both SQLITE_OMIT_DECLTYPE \
51073         and SQLITE_ENABLE_COLUMN_METADATA"
51074#endif
51075
51076#ifndef SQLITE_OMIT_DECLTYPE
51077/*
51078** Return the column declaration type (if applicable) of the 'i'th column
51079** of the result set of SQL statement pStmt.
51080*/
51081SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
51082  return columnName(
51083      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
51084}
51085#ifndef SQLITE_OMIT_UTF16
51086SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
51087  return columnName(
51088      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
51089}
51090#endif /* SQLITE_OMIT_UTF16 */
51091#endif /* SQLITE_OMIT_DECLTYPE */
51092
51093#ifdef SQLITE_ENABLE_COLUMN_METADATA
51094/*
51095** Return the name of the database from which a result column derives.
51096** NULL is returned if the result column is an expression or constant or
51097** anything else which is not an unabiguous reference to a database column.
51098*/
51099SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
51100  return columnName(
51101      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
51102}
51103#ifndef SQLITE_OMIT_UTF16
51104SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
51105  return columnName(
51106      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
51107}
51108#endif /* SQLITE_OMIT_UTF16 */
51109
51110/*
51111** Return the name of the table from which a result column derives.
51112** NULL is returned if the result column is an expression or constant or
51113** anything else which is not an unabiguous reference to a database column.
51114*/
51115SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
51116  return columnName(
51117      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
51118}
51119#ifndef SQLITE_OMIT_UTF16
51120SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
51121  return columnName(
51122      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
51123}
51124#endif /* SQLITE_OMIT_UTF16 */
51125
51126/*
51127** Return the name of the table column from which a result column derives.
51128** NULL is returned if the result column is an expression or constant or
51129** anything else which is not an unabiguous reference to a database column.
51130*/
51131SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
51132  return columnName(
51133      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
51134}
51135#ifndef SQLITE_OMIT_UTF16
51136SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
51137  return columnName(
51138      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
51139}
51140#endif /* SQLITE_OMIT_UTF16 */
51141#endif /* SQLITE_ENABLE_COLUMN_METADATA */
51142
51143
51144/******************************* sqlite3_bind_  ***************************
51145**
51146** Routines used to attach values to wildcards in a compiled SQL statement.
51147*/
51148/*
51149** Unbind the value bound to variable i in virtual machine p. This is the
51150** the same as binding a NULL value to the column. If the "i" parameter is
51151** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
51152**
51153** A successful evaluation of this routine acquires the mutex on p.
51154** the mutex is released if any kind of error occurs.
51155**
51156** The error code stored in database p->db is overwritten with the return
51157** value in any case.
51158*/
51159static int vdbeUnbind(Vdbe *p, int i){
51160  Mem *pVar;
51161  if( p==0 ) return SQLITE_MISUSE;
51162  sqlite3_mutex_enter(p->db->mutex);
51163  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
51164    sqlite3Error(p->db, SQLITE_MISUSE, 0);
51165    sqlite3_mutex_leave(p->db->mutex);
51166    return SQLITE_MISUSE;
51167  }
51168  if( i<1 || i>p->nVar ){
51169    sqlite3Error(p->db, SQLITE_RANGE, 0);
51170    sqlite3_mutex_leave(p->db->mutex);
51171    return SQLITE_RANGE;
51172  }
51173  i--;
51174  pVar = &p->aVar[i];
51175  sqlite3VdbeMemRelease(pVar);
51176  pVar->flags = MEM_Null;
51177  sqlite3Error(p->db, SQLITE_OK, 0);
51178
51179  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
51180  ** binding a new value to this variable invalidates the current query plan.
51181  */
51182  if( p->isPrepareV2 &&
51183     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
51184  ){
51185    p->expired = 1;
51186  }
51187  return SQLITE_OK;
51188}
51189
51190/*
51191** Bind a text or BLOB value.
51192*/
51193static int bindText(
51194  sqlite3_stmt *pStmt,   /* The statement to bind against */
51195  int i,                 /* Index of the parameter to bind */
51196  const void *zData,     /* Pointer to the data to be bound */
51197  int nData,             /* Number of bytes of data to be bound */
51198  void (*xDel)(void*),   /* Destructor for the data */
51199  u8 encoding            /* Encoding for the data */
51200){
51201  Vdbe *p = (Vdbe *)pStmt;
51202  Mem *pVar;
51203  int rc;
51204
51205  rc = vdbeUnbind(p, i);
51206  if( rc==SQLITE_OK ){
51207    if( zData!=0 ){
51208      pVar = &p->aVar[i-1];
51209      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
51210      if( rc==SQLITE_OK && encoding!=0 ){
51211        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
51212      }
51213      sqlite3Error(p->db, rc, 0);
51214      rc = sqlite3ApiExit(p->db, rc);
51215    }
51216    sqlite3_mutex_leave(p->db->mutex);
51217  }
51218  return rc;
51219}
51220
51221
51222/*
51223** Bind a blob value to an SQL statement variable.
51224*/
51225SQLITE_API int sqlite3_bind_blob(
51226  sqlite3_stmt *pStmt,
51227  int i,
51228  const void *zData,
51229  int nData,
51230  void (*xDel)(void*)
51231){
51232  return bindText(pStmt, i, zData, nData, xDel, 0);
51233}
51234SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
51235  int rc;
51236  Vdbe *p = (Vdbe *)pStmt;
51237  rc = vdbeUnbind(p, i);
51238  if( rc==SQLITE_OK ){
51239    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
51240    sqlite3_mutex_leave(p->db->mutex);
51241  }
51242  return rc;
51243}
51244SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
51245  return sqlite3_bind_int64(p, i, (i64)iValue);
51246}
51247SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
51248  int rc;
51249  Vdbe *p = (Vdbe *)pStmt;
51250  rc = vdbeUnbind(p, i);
51251  if( rc==SQLITE_OK ){
51252    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
51253    sqlite3_mutex_leave(p->db->mutex);
51254  }
51255  return rc;
51256}
51257SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
51258  int rc;
51259  Vdbe *p = (Vdbe*)pStmt;
51260  rc = vdbeUnbind(p, i);
51261  if( rc==SQLITE_OK ){
51262    sqlite3_mutex_leave(p->db->mutex);
51263  }
51264  return rc;
51265}
51266SQLITE_API int sqlite3_bind_text(
51267  sqlite3_stmt *pStmt,
51268  int i,
51269  const char *zData,
51270  int nData,
51271  void (*xDel)(void*)
51272){
51273  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
51274}
51275#ifndef SQLITE_OMIT_UTF16
51276SQLITE_API int sqlite3_bind_text16(
51277  sqlite3_stmt *pStmt,
51278  int i,
51279  const void *zData,
51280  int nData,
51281  void (*xDel)(void*)
51282){
51283  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
51284}
51285#endif /* SQLITE_OMIT_UTF16 */
51286SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
51287  int rc;
51288  switch( pValue->type ){
51289    case SQLITE_INTEGER: {
51290      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
51291      break;
51292    }
51293    case SQLITE_FLOAT: {
51294      rc = sqlite3_bind_double(pStmt, i, pValue->r);
51295      break;
51296    }
51297    case SQLITE_BLOB: {
51298      if( pValue->flags & MEM_Zero ){
51299        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
51300      }else{
51301        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
51302      }
51303      break;
51304    }
51305    case SQLITE_TEXT: {
51306      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
51307                              pValue->enc);
51308      break;
51309    }
51310    default: {
51311      rc = sqlite3_bind_null(pStmt, i);
51312      break;
51313    }
51314  }
51315  return rc;
51316}
51317SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
51318  int rc;
51319  Vdbe *p = (Vdbe *)pStmt;
51320  rc = vdbeUnbind(p, i);
51321  if( rc==SQLITE_OK ){
51322    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
51323    sqlite3_mutex_leave(p->db->mutex);
51324  }
51325  return rc;
51326}
51327
51328/*
51329** Return the number of wildcards that can be potentially bound to.
51330** This routine is added to support DBD::SQLite.
51331*/
51332SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
51333  Vdbe *p = (Vdbe*)pStmt;
51334  return p ? p->nVar : 0;
51335}
51336
51337/*
51338** Create a mapping from variable numbers to variable names
51339** in the Vdbe.azVar[] array, if such a mapping does not already
51340** exist.
51341*/
51342static void createVarMap(Vdbe *p){
51343  if( !p->okVar ){
51344    int j;
51345    Op *pOp;
51346    sqlite3_mutex_enter(p->db->mutex);
51347    /* The race condition here is harmless.  If two threads call this
51348    ** routine on the same Vdbe at the same time, they both might end
51349    ** up initializing the Vdbe.azVar[] array.  That is a little extra
51350    ** work but it results in the same answer.
51351    */
51352    for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
51353      if( pOp->opcode==OP_Variable ){
51354        assert( pOp->p1>0 && pOp->p1<=p->nVar );
51355        p->azVar[pOp->p1-1] = pOp->p4.z;
51356      }
51357    }
51358    p->okVar = 1;
51359    sqlite3_mutex_leave(p->db->mutex);
51360  }
51361}
51362
51363/*
51364** Return the name of a wildcard parameter.  Return NULL if the index
51365** is out of range or if the wildcard is unnamed.
51366**
51367** The result is always UTF-8.
51368*/
51369SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
51370  Vdbe *p = (Vdbe*)pStmt;
51371  if( p==0 || i<1 || i>p->nVar ){
51372    return 0;
51373  }
51374  createVarMap(p);
51375  return p->azVar[i-1];
51376}
51377
51378/*
51379** Given a wildcard parameter name, return the index of the variable
51380** with that name.  If there is no variable with the given name,
51381** return 0.
51382*/
51383SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
51384  int i;
51385  if( p==0 ){
51386    return 0;
51387  }
51388  createVarMap(p);
51389  if( zName ){
51390    for(i=0; i<p->nVar; i++){
51391      const char *z = p->azVar[i];
51392      if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
51393        return i+1;
51394      }
51395    }
51396  }
51397  return 0;
51398}
51399SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
51400  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
51401}
51402
51403/*
51404** Transfer all bindings from the first statement over to the second.
51405*/
51406SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
51407  Vdbe *pFrom = (Vdbe*)pFromStmt;
51408  Vdbe *pTo = (Vdbe*)pToStmt;
51409  int i;
51410  assert( pTo->db==pFrom->db );
51411  assert( pTo->nVar==pFrom->nVar );
51412  sqlite3_mutex_enter(pTo->db->mutex);
51413  for(i=0; i<pFrom->nVar; i++){
51414    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
51415  }
51416  sqlite3_mutex_leave(pTo->db->mutex);
51417  return SQLITE_OK;
51418}
51419
51420#ifndef SQLITE_OMIT_DEPRECATED
51421/*
51422** Deprecated external interface.  Internal/core SQLite code
51423** should call sqlite3TransferBindings.
51424**
51425** Is is misuse to call this routine with statements from different
51426** database connections.  But as this is a deprecated interface, we
51427** will not bother to check for that condition.
51428**
51429** If the two statements contain a different number of bindings, then
51430** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
51431** SQLITE_OK is returned.
51432*/
51433SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
51434  Vdbe *pFrom = (Vdbe*)pFromStmt;
51435  Vdbe *pTo = (Vdbe*)pToStmt;
51436  if( pFrom->nVar!=pTo->nVar ){
51437    return SQLITE_ERROR;
51438  }
51439  if( pTo->isPrepareV2 && pTo->expmask ){
51440    pTo->expired = 1;
51441  }
51442  if( pFrom->isPrepareV2 && pFrom->expmask ){
51443    pFrom->expired = 1;
51444  }
51445  return sqlite3TransferBindings(pFromStmt, pToStmt);
51446}
51447#endif
51448
51449/*
51450** Return the sqlite3* database handle to which the prepared statement given
51451** in the argument belongs.  This is the same database handle that was
51452** the first argument to the sqlite3_prepare() that was used to create
51453** the statement in the first place.
51454*/
51455SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
51456  return pStmt ? ((Vdbe*)pStmt)->db : 0;
51457}
51458
51459/*
51460** Return a pointer to the next prepared statement after pStmt associated
51461** with database connection pDb.  If pStmt is NULL, return the first
51462** prepared statement for the database connection.  Return NULL if there
51463** are no more.
51464*/
51465SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
51466  sqlite3_stmt *pNext;
51467  sqlite3_mutex_enter(pDb->mutex);
51468  if( pStmt==0 ){
51469    pNext = (sqlite3_stmt*)pDb->pVdbe;
51470  }else{
51471    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
51472  }
51473  sqlite3_mutex_leave(pDb->mutex);
51474  return pNext;
51475}
51476
51477/*
51478** Return the value of a status counter for a prepared statement
51479*/
51480SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
51481  Vdbe *pVdbe = (Vdbe*)pStmt;
51482  int v = pVdbe->aCounter[op-1];
51483  if( resetFlag ) pVdbe->aCounter[op-1] = 0;
51484  return v;
51485}
51486
51487/************** End of vdbeapi.c *********************************************/
51488/************** Begin file vdbetrace.c ***************************************/
51489/*
51490** 2009 November 25
51491**
51492** The author disclaims copyright to this source code.  In place of
51493** a legal notice, here is a blessing:
51494**
51495**    May you do good and not evil.
51496**    May you find forgiveness for yourself and forgive others.
51497**    May you share freely, never taking more than you give.
51498**
51499*************************************************************************
51500**
51501** This file contains code used to insert the values of host parameters
51502** (aka "wildcards") into the SQL text output by sqlite3_trace().
51503*/
51504
51505#ifndef SQLITE_OMIT_TRACE
51506
51507/*
51508** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
51509** bytes in this text up to but excluding the first character in
51510** a host parameter.  If the text contains no host parameters, return
51511** the total number of bytes in the text.
51512*/
51513static int findNextHostParameter(const char *zSql, int *pnToken){
51514  int tokenType;
51515  int nTotal = 0;
51516  int n;
51517
51518  *pnToken = 0;
51519  while( zSql[0] ){
51520    n = sqlite3GetToken((u8*)zSql, &tokenType);
51521    assert( n>0 && tokenType!=TK_ILLEGAL );
51522    if( tokenType==TK_VARIABLE ){
51523      *pnToken = n;
51524      break;
51525    }
51526    nTotal += n;
51527    zSql += n;
51528  }
51529  return nTotal;
51530}
51531
51532/*
51533** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
51534** holds a copy of zRawSql but with host parameters expanded to their
51535** current bindings.
51536**
51537** The calling function is responsible for making sure the memory returned
51538** is eventually freed.
51539**
51540** ALGORITHM:  Scan the input string looking for host parameters in any of
51541** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
51542** string literals, quoted identifier names, and comments.  For text forms,
51543** the host parameter index is found by scanning the perpared
51544** statement for the corresponding OP_Variable opcode.  Once the host
51545** parameter index is known, locate the value in p->aVar[].  Then render
51546** the value as a literal in place of the host parameter name.
51547*/
51548SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
51549  Vdbe *p,                 /* The prepared statement being evaluated */
51550  const char *zRawSql      /* Raw text of the SQL statement */
51551){
51552  sqlite3 *db;             /* The database connection */
51553  int idx = 0;             /* Index of a host parameter */
51554  int nextIndex = 1;       /* Index of next ? host parameter */
51555  int n;                   /* Length of a token prefix */
51556  int nToken;              /* Length of the parameter token */
51557  int i;                   /* Loop counter */
51558  Mem *pVar;               /* Value of a host parameter */
51559  StrAccum out;            /* Accumulate the output here */
51560  char zBase[100];         /* Initial working space */
51561
51562  db = p->db;
51563  sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
51564                      db->aLimit[SQLITE_LIMIT_LENGTH]);
51565  out.db = db;
51566  while( zRawSql[0] ){
51567    n = findNextHostParameter(zRawSql, &nToken);
51568    assert( n>0 );
51569    sqlite3StrAccumAppend(&out, zRawSql, n);
51570    zRawSql += n;
51571    assert( zRawSql[0] || nToken==0 );
51572    if( nToken==0 ) break;
51573    if( zRawSql[0]=='?' ){
51574      if( nToken>1 ){
51575        assert( sqlite3Isdigit(zRawSql[1]) );
51576        sqlite3GetInt32(&zRawSql[1], &idx);
51577      }else{
51578        idx = nextIndex;
51579      }
51580    }else{
51581      assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
51582      testcase( zRawSql[0]==':' );
51583      testcase( zRawSql[0]=='$' );
51584      testcase( zRawSql[0]=='@' );
51585      idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
51586      assert( idx>0 );
51587    }
51588    zRawSql += nToken;
51589    nextIndex = idx + 1;
51590    assert( idx>0 && idx<=p->nVar );
51591    pVar = &p->aVar[idx-1];
51592    if( pVar->flags & MEM_Null ){
51593      sqlite3StrAccumAppend(&out, "NULL", 4);
51594    }else if( pVar->flags & MEM_Int ){
51595      sqlite3XPrintf(&out, "%lld", pVar->u.i);
51596    }else if( pVar->flags & MEM_Real ){
51597      sqlite3XPrintf(&out, "%!.15g", pVar->r);
51598    }else if( pVar->flags & MEM_Str ){
51599#ifndef SQLITE_OMIT_UTF16
51600      u8 enc = ENC(db);
51601      if( enc!=SQLITE_UTF8 ){
51602        Mem utf8;
51603        memset(&utf8, 0, sizeof(utf8));
51604        utf8.db = db;
51605        sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
51606        sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
51607        sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
51608        sqlite3VdbeMemRelease(&utf8);
51609      }else
51610#endif
51611      {
51612        sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
51613      }
51614    }else if( pVar->flags & MEM_Zero ){
51615      sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
51616    }else{
51617      assert( pVar->flags & MEM_Blob );
51618      sqlite3StrAccumAppend(&out, "x'", 2);
51619      for(i=0; i<pVar->n; i++){
51620        sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
51621      }
51622      sqlite3StrAccumAppend(&out, "'", 1);
51623    }
51624  }
51625  return sqlite3StrAccumFinish(&out);
51626}
51627
51628#endif /* #ifndef SQLITE_OMIT_TRACE */
51629
51630/************** End of vdbetrace.c *******************************************/
51631/************** Begin file vdbe.c ********************************************/
51632/*
51633** 2001 September 15
51634**
51635** The author disclaims copyright to this source code.  In place of
51636** a legal notice, here is a blessing:
51637**
51638**    May you do good and not evil.
51639**    May you find forgiveness for yourself and forgive others.
51640**    May you share freely, never taking more than you give.
51641**
51642*************************************************************************
51643** The code in this file implements execution method of the
51644** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
51645** handles housekeeping details such as creating and deleting
51646** VDBE instances.  This file is solely interested in executing
51647** the VDBE program.
51648**
51649** In the external interface, an "sqlite3_stmt*" is an opaque pointer
51650** to a VDBE.
51651**
51652** The SQL parser generates a program which is then executed by
51653** the VDBE to do the work of the SQL statement.  VDBE programs are
51654** similar in form to assembly language.  The program consists of
51655** a linear sequence of operations.  Each operation has an opcode
51656** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
51657** is a null-terminated string.  Operand P5 is an unsigned character.
51658** Few opcodes use all 5 operands.
51659**
51660** Computation results are stored on a set of registers numbered beginning
51661** with 1 and going up to Vdbe.nMem.  Each register can store
51662** either an integer, a null-terminated string, a floating point
51663** number, or the SQL "NULL" value.  An implicit conversion from one
51664** type to the other occurs as necessary.
51665**
51666** Most of the code in this file is taken up by the sqlite3VdbeExec()
51667** function which does the work of interpreting a VDBE program.
51668** But other routines are also provided to help in building up
51669** a program instruction by instruction.
51670**
51671** Various scripts scan this source file in order to generate HTML
51672** documentation, headers files, or other derived files.  The formatting
51673** of the code in this file is, therefore, important.  See other comments
51674** in this file for details.  If in doubt, do not deviate from existing
51675** commenting and indentation practices when changing or adding code.
51676*/
51677
51678/*
51679** The following global variable is incremented every time a cursor
51680** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
51681** procedures use this information to make sure that indices are
51682** working correctly.  This variable has no function other than to
51683** help verify the correct operation of the library.
51684*/
51685#ifdef SQLITE_TEST
51686SQLITE_API int sqlite3_search_count = 0;
51687#endif
51688
51689/*
51690** When this global variable is positive, it gets decremented once before
51691** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
51692** field of the sqlite3 structure is set in order to simulate and interrupt.
51693**
51694** This facility is used for testing purposes only.  It does not function
51695** in an ordinary build.
51696*/
51697#ifdef SQLITE_TEST
51698SQLITE_API int sqlite3_interrupt_count = 0;
51699#endif
51700
51701/*
51702** The next global variable is incremented each type the OP_Sort opcode
51703** is executed.  The test procedures use this information to make sure that
51704** sorting is occurring or not occurring at appropriate times.   This variable
51705** has no function other than to help verify the correct operation of the
51706** library.
51707*/
51708#ifdef SQLITE_TEST
51709SQLITE_API int sqlite3_sort_count = 0;
51710#endif
51711
51712/*
51713** The next global variable records the size of the largest MEM_Blob
51714** or MEM_Str that has been used by a VDBE opcode.  The test procedures
51715** use this information to make sure that the zero-blob functionality
51716** is working correctly.   This variable has no function other than to
51717** help verify the correct operation of the library.
51718*/
51719#ifdef SQLITE_TEST
51720SQLITE_API int sqlite3_max_blobsize = 0;
51721static void updateMaxBlobsize(Mem *p){
51722  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
51723    sqlite3_max_blobsize = p->n;
51724  }
51725}
51726#endif
51727
51728/*
51729** The next global variable is incremented each type the OP_Found opcode
51730** is executed. This is used to test whether or not the foreign key
51731** operation implemented using OP_FkIsZero is working. This variable
51732** has no function other than to help verify the correct operation of the
51733** library.
51734*/
51735#ifdef SQLITE_TEST
51736SQLITE_API int sqlite3_found_count = 0;
51737#endif
51738
51739/*
51740** Test a register to see if it exceeds the current maximum blob size.
51741** If it does, record the new maximum blob size.
51742*/
51743#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
51744# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
51745#else
51746# define UPDATE_MAX_BLOBSIZE(P)
51747#endif
51748
51749/*
51750** Convert the given register into a string if it isn't one
51751** already. Return non-zero if a malloc() fails.
51752*/
51753#define Stringify(P, enc) \
51754   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
51755     { goto no_mem; }
51756
51757/*
51758** An ephemeral string value (signified by the MEM_Ephem flag) contains
51759** a pointer to a dynamically allocated string where some other entity
51760** is responsible for deallocating that string.  Because the register
51761** does not control the string, it might be deleted without the register
51762** knowing it.
51763**
51764** This routine converts an ephemeral string into a dynamically allocated
51765** string that the register itself controls.  In other words, it
51766** converts an MEM_Ephem string into an MEM_Dyn string.
51767*/
51768#define Deephemeralize(P) \
51769   if( ((P)->flags&MEM_Ephem)!=0 \
51770       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
51771
51772/*
51773** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
51774** P if required.
51775*/
51776#define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
51777
51778/*
51779** Argument pMem points at a register that will be passed to a
51780** user-defined function or returned to the user as the result of a query.
51781** This routine sets the pMem->type variable used by the sqlite3_value_*()
51782** routines.
51783*/
51784SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
51785  int flags = pMem->flags;
51786  if( flags & MEM_Null ){
51787    pMem->type = SQLITE_NULL;
51788  }
51789  else if( flags & MEM_Int ){
51790    pMem->type = SQLITE_INTEGER;
51791  }
51792  else if( flags & MEM_Real ){
51793    pMem->type = SQLITE_FLOAT;
51794  }
51795  else if( flags & MEM_Str ){
51796    pMem->type = SQLITE_TEXT;
51797  }else{
51798    pMem->type = SQLITE_BLOB;
51799  }
51800}
51801
51802/*
51803** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
51804** if we run out of memory.
51805*/
51806static VdbeCursor *allocateCursor(
51807  Vdbe *p,              /* The virtual machine */
51808  int iCur,             /* Index of the new VdbeCursor */
51809  int nField,           /* Number of fields in the table or index */
51810  int iDb,              /* When database the cursor belongs to, or -1 */
51811  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
51812){
51813  /* Find the memory cell that will be used to store the blob of memory
51814  ** required for this VdbeCursor structure. It is convenient to use a
51815  ** vdbe memory cell to manage the memory allocation required for a
51816  ** VdbeCursor structure for the following reasons:
51817  **
51818  **   * Sometimes cursor numbers are used for a couple of different
51819  **     purposes in a vdbe program. The different uses might require
51820  **     different sized allocations. Memory cells provide growable
51821  **     allocations.
51822  **
51823  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
51824  **     be freed lazily via the sqlite3_release_memory() API. This
51825  **     minimizes the number of malloc calls made by the system.
51826  **
51827  ** Memory cells for cursors are allocated at the top of the address
51828  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
51829  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
51830  */
51831  Mem *pMem = &p->aMem[p->nMem-iCur];
51832
51833  int nByte;
51834  VdbeCursor *pCx = 0;
51835  nByte =
51836      ROUND8(sizeof(VdbeCursor)) +
51837      (isBtreeCursor?sqlite3BtreeCursorSize():0) +
51838      2*nField*sizeof(u32);
51839
51840  assert( iCur<p->nCursor );
51841  if( p->apCsr[iCur] ){
51842    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
51843    p->apCsr[iCur] = 0;
51844  }
51845  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
51846    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
51847    memset(pCx, 0, sizeof(VdbeCursor));
51848    pCx->iDb = iDb;
51849    pCx->nField = nField;
51850    if( nField ){
51851      pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
51852    }
51853    if( isBtreeCursor ){
51854      pCx->pCursor = (BtCursor*)
51855          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
51856      sqlite3BtreeCursorZero(pCx->pCursor);
51857    }
51858  }
51859  return pCx;
51860}
51861
51862/*
51863** Try to convert a value into a numeric representation if we can
51864** do so without loss of information.  In other words, if the string
51865** looks like a number, convert it into a number.  If it does not
51866** look like a number, leave it alone.
51867*/
51868static void applyNumericAffinity(Mem *pRec){
51869  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
51870    int realnum;
51871    sqlite3VdbeMemNulTerminate(pRec);
51872    if( (pRec->flags&MEM_Str)
51873         && sqlite3IsNumber(pRec->z, &realnum, pRec->enc) ){
51874      i64 value;
51875      sqlite3VdbeChangeEncoding(pRec, SQLITE_UTF8);
51876      if( !realnum && sqlite3Atoi64(pRec->z, &value) ){
51877        pRec->u.i = value;
51878        MemSetTypeFlag(pRec, MEM_Int);
51879      }else{
51880        sqlite3VdbeMemRealify(pRec);
51881      }
51882    }
51883  }
51884}
51885
51886/*
51887** Processing is determine by the affinity parameter:
51888**
51889** SQLITE_AFF_INTEGER:
51890** SQLITE_AFF_REAL:
51891** SQLITE_AFF_NUMERIC:
51892**    Try to convert pRec to an integer representation or a
51893**    floating-point representation if an integer representation
51894**    is not possible.  Note that the integer representation is
51895**    always preferred, even if the affinity is REAL, because
51896**    an integer representation is more space efficient on disk.
51897**
51898** SQLITE_AFF_TEXT:
51899**    Convert pRec to a text representation.
51900**
51901** SQLITE_AFF_NONE:
51902**    No-op.  pRec is unchanged.
51903*/
51904static void applyAffinity(
51905  Mem *pRec,          /* The value to apply affinity to */
51906  char affinity,      /* The affinity to be applied */
51907  u8 enc              /* Use this text encoding */
51908){
51909  if( affinity==SQLITE_AFF_TEXT ){
51910    /* Only attempt the conversion to TEXT if there is an integer or real
51911    ** representation (blob and NULL do not get converted) but no string
51912    ** representation.
51913    */
51914    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
51915      sqlite3VdbeMemStringify(pRec, enc);
51916    }
51917    pRec->flags &= ~(MEM_Real|MEM_Int);
51918  }else if( affinity!=SQLITE_AFF_NONE ){
51919    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
51920             || affinity==SQLITE_AFF_NUMERIC );
51921    applyNumericAffinity(pRec);
51922    if( pRec->flags & MEM_Real ){
51923      sqlite3VdbeIntegerAffinity(pRec);
51924    }
51925  }
51926}
51927
51928/*
51929** Try to convert the type of a function argument or a result column
51930** into a numeric representation.  Use either INTEGER or REAL whichever
51931** is appropriate.  But only do the conversion if it is possible without
51932** loss of information and return the revised type of the argument.
51933**
51934** This is an EXPERIMENTAL api and is subject to change or removal.
51935*/
51936SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
51937  Mem *pMem = (Mem*)pVal;
51938  applyNumericAffinity(pMem);
51939  sqlite3VdbeMemStoreType(pMem);
51940  return pMem->type;
51941}
51942
51943/*
51944** Exported version of applyAffinity(). This one works on sqlite3_value*,
51945** not the internal Mem* type.
51946*/
51947SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
51948  sqlite3_value *pVal,
51949  u8 affinity,
51950  u8 enc
51951){
51952  applyAffinity((Mem *)pVal, affinity, enc);
51953}
51954
51955#ifdef SQLITE_DEBUG
51956/*
51957** Write a nice string representation of the contents of cell pMem
51958** into buffer zBuf, length nBuf.
51959*/
51960SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
51961  char *zCsr = zBuf;
51962  int f = pMem->flags;
51963
51964  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
51965
51966  if( f&MEM_Blob ){
51967    int i;
51968    char c;
51969    if( f & MEM_Dyn ){
51970      c = 'z';
51971      assert( (f & (MEM_Static|MEM_Ephem))==0 );
51972    }else if( f & MEM_Static ){
51973      c = 't';
51974      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
51975    }else if( f & MEM_Ephem ){
51976      c = 'e';
51977      assert( (f & (MEM_Static|MEM_Dyn))==0 );
51978    }else{
51979      c = 's';
51980    }
51981
51982    sqlite3_snprintf(100, zCsr, "%c", c);
51983    zCsr += sqlite3Strlen30(zCsr);
51984    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
51985    zCsr += sqlite3Strlen30(zCsr);
51986    for(i=0; i<16 && i<pMem->n; i++){
51987      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
51988      zCsr += sqlite3Strlen30(zCsr);
51989    }
51990    for(i=0; i<16 && i<pMem->n; i++){
51991      char z = pMem->z[i];
51992      if( z<32 || z>126 ) *zCsr++ = '.';
51993      else *zCsr++ = z;
51994    }
51995
51996    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
51997    zCsr += sqlite3Strlen30(zCsr);
51998    if( f & MEM_Zero ){
51999      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
52000      zCsr += sqlite3Strlen30(zCsr);
52001    }
52002    *zCsr = '\0';
52003  }else if( f & MEM_Str ){
52004    int j, k;
52005    zBuf[0] = ' ';
52006    if( f & MEM_Dyn ){
52007      zBuf[1] = 'z';
52008      assert( (f & (MEM_Static|MEM_Ephem))==0 );
52009    }else if( f & MEM_Static ){
52010      zBuf[1] = 't';
52011      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
52012    }else if( f & MEM_Ephem ){
52013      zBuf[1] = 'e';
52014      assert( (f & (MEM_Static|MEM_Dyn))==0 );
52015    }else{
52016      zBuf[1] = 's';
52017    }
52018    k = 2;
52019    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
52020    k += sqlite3Strlen30(&zBuf[k]);
52021    zBuf[k++] = '[';
52022    for(j=0; j<15 && j<pMem->n; j++){
52023      u8 c = pMem->z[j];
52024      if( c>=0x20 && c<0x7f ){
52025        zBuf[k++] = c;
52026      }else{
52027        zBuf[k++] = '.';
52028      }
52029    }
52030    zBuf[k++] = ']';
52031    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
52032    k += sqlite3Strlen30(&zBuf[k]);
52033    zBuf[k++] = 0;
52034  }
52035}
52036#endif
52037
52038#ifdef SQLITE_DEBUG
52039/*
52040** Print the value of a register for tracing purposes:
52041*/
52042static void memTracePrint(FILE *out, Mem *p){
52043  if( p->flags & MEM_Null ){
52044    fprintf(out, " NULL");
52045  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
52046    fprintf(out, " si:%lld", p->u.i);
52047  }else if( p->flags & MEM_Int ){
52048    fprintf(out, " i:%lld", p->u.i);
52049#ifndef SQLITE_OMIT_FLOATING_POINT
52050  }else if( p->flags & MEM_Real ){
52051    fprintf(out, " r:%g", p->r);
52052#endif
52053  }else if( p->flags & MEM_RowSet ){
52054    fprintf(out, " (rowset)");
52055  }else{
52056    char zBuf[200];
52057    sqlite3VdbeMemPrettyPrint(p, zBuf);
52058    fprintf(out, " ");
52059    fprintf(out, "%s", zBuf);
52060  }
52061}
52062static void registerTrace(FILE *out, int iReg, Mem *p){
52063  fprintf(out, "REG[%d] = ", iReg);
52064  memTracePrint(out, p);
52065  fprintf(out, "\n");
52066}
52067#endif
52068
52069#ifdef SQLITE_DEBUG
52070#  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
52071#else
52072#  define REGISTER_TRACE(R,M)
52073#endif
52074
52075
52076#ifdef VDBE_PROFILE
52077
52078/*
52079** hwtime.h contains inline assembler code for implementing
52080** high-performance timing routines.
52081*/
52082/************** Include hwtime.h in the middle of vdbe.c *********************/
52083/************** Begin file hwtime.h ******************************************/
52084/*
52085** 2008 May 27
52086**
52087** The author disclaims copyright to this source code.  In place of
52088** a legal notice, here is a blessing:
52089**
52090**    May you do good and not evil.
52091**    May you find forgiveness for yourself and forgive others.
52092**    May you share freely, never taking more than you give.
52093**
52094******************************************************************************
52095**
52096** This file contains inline asm code for retrieving "high-performance"
52097** counters for x86 class CPUs.
52098*/
52099#ifndef _HWTIME_H_
52100#define _HWTIME_H_
52101
52102/*
52103** The following routine only works on pentium-class (or newer) processors.
52104** It uses the RDTSC opcode to read the cycle count value out of the
52105** processor and returns that value.  This can be used for high-res
52106** profiling.
52107*/
52108#if (defined(__GNUC__) || defined(_MSC_VER)) && \
52109      (defined(i386) || defined(__i386__) || defined(_M_IX86))
52110
52111  #if defined(__GNUC__)
52112
52113  __inline__ sqlite_uint64 sqlite3Hwtime(void){
52114     unsigned int lo, hi;
52115     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
52116     return (sqlite_uint64)hi << 32 | lo;
52117  }
52118
52119  #elif defined(_MSC_VER)
52120
52121  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
52122     __asm {
52123        rdtsc
52124        ret       ; return value at EDX:EAX
52125     }
52126  }
52127
52128  #endif
52129
52130#elif (defined(__GNUC__) && defined(__x86_64__))
52131
52132  __inline__ sqlite_uint64 sqlite3Hwtime(void){
52133      unsigned long val;
52134      __asm__ __volatile__ ("rdtsc" : "=A" (val));
52135      return val;
52136  }
52137
52138#elif (defined(__GNUC__) && defined(__ppc__))
52139
52140  __inline__ sqlite_uint64 sqlite3Hwtime(void){
52141      unsigned long long retval;
52142      unsigned long junk;
52143      __asm__ __volatile__ ("\n\
52144          1:      mftbu   %1\n\
52145                  mftb    %L0\n\
52146                  mftbu   %0\n\
52147                  cmpw    %0,%1\n\
52148                  bne     1b"
52149                  : "=r" (retval), "=r" (junk));
52150      return retval;
52151  }
52152
52153#else
52154
52155  #error Need implementation of sqlite3Hwtime() for your platform.
52156
52157  /*
52158  ** To compile without implementing sqlite3Hwtime() for your platform,
52159  ** you can remove the above #error and use the following
52160  ** stub function.  You will lose timing support for many
52161  ** of the debugging and testing utilities, but it should at
52162  ** least compile and run.
52163  */
52164SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
52165
52166#endif
52167
52168#endif /* !defined(_HWTIME_H_) */
52169
52170/************** End of hwtime.h **********************************************/
52171/************** Continuing where we left off in vdbe.c ***********************/
52172
52173#endif
52174
52175/*
52176** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
52177** sqlite3_interrupt() routine has been called.  If it has been, then
52178** processing of the VDBE program is interrupted.
52179**
52180** This macro added to every instruction that does a jump in order to
52181** implement a loop.  This test used to be on every single instruction,
52182** but that meant we more testing that we needed.  By only testing the
52183** flag on jump instructions, we get a (small) speed improvement.
52184*/
52185#define CHECK_FOR_INTERRUPT \
52186   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
52187
52188#ifdef SQLITE_DEBUG
52189static int fileExists(sqlite3 *db, const char *zFile){
52190  int res = 0;
52191  int rc = SQLITE_OK;
52192#ifdef SQLITE_TEST
52193  /* If we are currently testing IO errors, then do not call OsAccess() to
52194  ** test for the presence of zFile. This is because any IO error that
52195  ** occurs here will not be reported, causing the test to fail.
52196  */
52197  extern int sqlite3_io_error_pending;
52198  if( sqlite3_io_error_pending<=0 )
52199#endif
52200    rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
52201  return (res && rc==SQLITE_OK);
52202}
52203#endif
52204
52205#ifndef NDEBUG
52206/*
52207** This function is only called from within an assert() expression. It
52208** checks that the sqlite3.nTransaction variable is correctly set to
52209** the number of non-transaction savepoints currently in the
52210** linked list starting at sqlite3.pSavepoint.
52211**
52212** Usage:
52213**
52214**     assert( checkSavepointCount(db) );
52215*/
52216static int checkSavepointCount(sqlite3 *db){
52217  int n = 0;
52218  Savepoint *p;
52219  for(p=db->pSavepoint; p; p=p->pNext) n++;
52220  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
52221  return 1;
52222}
52223#endif
52224
52225/*
52226** Execute as much of a VDBE program as we can then return.
52227**
52228** sqlite3VdbeMakeReady() must be called before this routine in order to
52229** close the program with a final OP_Halt and to set up the callbacks
52230** and the error message pointer.
52231**
52232** Whenever a row or result data is available, this routine will either
52233** invoke the result callback (if there is one) or return with
52234** SQLITE_ROW.
52235**
52236** If an attempt is made to open a locked database, then this routine
52237** will either invoke the busy callback (if there is one) or it will
52238** return SQLITE_BUSY.
52239**
52240** If an error occurs, an error message is written to memory obtained
52241** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
52242** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
52243**
52244** If the callback ever returns non-zero, then the program exits
52245** immediately.  There will be no error message but the p->rc field is
52246** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
52247**
52248** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
52249** routine to return SQLITE_ERROR.
52250**
52251** Other fatal errors return SQLITE_ERROR.
52252**
52253** After this routine has finished, sqlite3VdbeFinalize() should be
52254** used to clean up the mess that was left behind.
52255*/
52256SQLITE_PRIVATE int sqlite3VdbeExec(
52257  Vdbe *p                    /* The VDBE */
52258){
52259  int pc;                    /* The program counter */
52260  Op *aOp = p->aOp;          /* Copy of p->aOp */
52261  Op *pOp;                   /* Current operation */
52262  int rc = SQLITE_OK;        /* Value to return */
52263  sqlite3 *db = p->db;       /* The database */
52264  u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
52265  u8 encoding = ENC(db);     /* The database encoding */
52266#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52267  int checkProgress;         /* True if progress callbacks are enabled */
52268  int nProgressOps = 0;      /* Opcodes executed since progress callback. */
52269#endif
52270  Mem *aMem = p->aMem;       /* Copy of p->aMem */
52271  Mem *pIn1 = 0;             /* 1st input operand */
52272  Mem *pIn2 = 0;             /* 2nd input operand */
52273  Mem *pIn3 = 0;             /* 3rd input operand */
52274  Mem *pOut = 0;             /* Output operand */
52275  int iCompare = 0;          /* Result of last OP_Compare operation */
52276  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
52277#ifdef VDBE_PROFILE
52278  u64 start;                 /* CPU clock count at start of opcode */
52279  int origPc;                /* Program counter at start of opcode */
52280#endif
52281  /********************************************************************
52282  ** Automatically generated code
52283  **
52284  ** The following union is automatically generated by the
52285  ** vdbe-compress.tcl script.  The purpose of this union is to
52286  ** reduce the amount of stack space required by this function.
52287  ** See comments in the vdbe-compress.tcl script for details.
52288  */
52289  union vdbeExecUnion {
52290    struct OP_Yield_stack_vars {
52291      int pcDest;
52292    } aa;
52293    struct OP_Variable_stack_vars {
52294      int p1;          /* Variable to copy from */
52295      int p2;          /* Register to copy to */
52296      int n;           /* Number of values left to copy */
52297      Mem *pVar;       /* Value being transferred */
52298    } ab;
52299    struct OP_Move_stack_vars {
52300      char *zMalloc;   /* Holding variable for allocated memory */
52301      int n;           /* Number of registers left to copy */
52302      int p1;          /* Register to copy from */
52303      int p2;          /* Register to copy to */
52304    } ac;
52305    struct OP_ResultRow_stack_vars {
52306      Mem *pMem;
52307      int i;
52308    } ad;
52309    struct OP_Concat_stack_vars {
52310      i64 nByte;
52311    } ae;
52312    struct OP_Remainder_stack_vars {
52313      int flags;      /* Combined MEM_* flags from both inputs */
52314      i64 iA;         /* Integer value of left operand */
52315      i64 iB;         /* Integer value of right operand */
52316      double rA;      /* Real value of left operand */
52317      double rB;      /* Real value of right operand */
52318    } af;
52319    struct OP_Function_stack_vars {
52320      int i;
52321      Mem *pArg;
52322      sqlite3_context ctx;
52323      sqlite3_value **apVal;
52324      int n;
52325    } ag;
52326    struct OP_ShiftRight_stack_vars {
52327      i64 a;
52328      i64 b;
52329    } ah;
52330    struct OP_Ge_stack_vars {
52331      int res;            /* Result of the comparison of pIn1 against pIn3 */
52332      char affinity;      /* Affinity to use for comparison */
52333    } ai;
52334    struct OP_Compare_stack_vars {
52335      int n;
52336      int i;
52337      int p1;
52338      int p2;
52339      const KeyInfo *pKeyInfo;
52340      int idx;
52341      CollSeq *pColl;    /* Collating sequence to use on this term */
52342      int bRev;          /* True for DESCENDING sort order */
52343    } aj;
52344    struct OP_Or_stack_vars {
52345      int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
52346      int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
52347    } ak;
52348    struct OP_IfNot_stack_vars {
52349      int c;
52350    } al;
52351    struct OP_Column_stack_vars {
52352      u32 payloadSize;   /* Number of bytes in the record */
52353      i64 payloadSize64; /* Number of bytes in the record */
52354      int p1;            /* P1 value of the opcode */
52355      int p2;            /* column number to retrieve */
52356      VdbeCursor *pC;    /* The VDBE cursor */
52357      char *zRec;        /* Pointer to complete record-data */
52358      BtCursor *pCrsr;   /* The BTree cursor */
52359      u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
52360      u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
52361      int nField;        /* number of fields in the record */
52362      int len;           /* The length of the serialized data for the column */
52363      int i;             /* Loop counter */
52364      char *zData;       /* Part of the record being decoded */
52365      Mem *pDest;        /* Where to write the extracted value */
52366      Mem sMem;          /* For storing the record being decoded */
52367      u8 *zIdx;          /* Index into header */
52368      u8 *zEndHdr;       /* Pointer to first byte after the header */
52369      u32 offset;        /* Offset into the data */
52370      u64 offset64;      /* 64-bit offset.  64 bits needed to catch overflow */
52371      int szHdr;         /* Size of the header size field at start of record */
52372      int avail;         /* Number of bytes of available data */
52373      Mem *pReg;         /* PseudoTable input register */
52374    } am;
52375    struct OP_Affinity_stack_vars {
52376      const char *zAffinity;   /* The affinity to be applied */
52377      char cAff;               /* A single character of affinity */
52378    } an;
52379    struct OP_MakeRecord_stack_vars {
52380      u8 *zNewRecord;        /* A buffer to hold the data for the new record */
52381      Mem *pRec;             /* The new record */
52382      u64 nData;             /* Number of bytes of data space */
52383      int nHdr;              /* Number of bytes of header space */
52384      i64 nByte;             /* Data space required for this record */
52385      int nZero;             /* Number of zero bytes at the end of the record */
52386      int nVarint;           /* Number of bytes in a varint */
52387      u32 serial_type;       /* Type field */
52388      Mem *pData0;           /* First field to be combined into the record */
52389      Mem *pLast;            /* Last field of the record */
52390      int nField;            /* Number of fields in the record */
52391      char *zAffinity;       /* The affinity string for the record */
52392      int file_format;       /* File format to use for encoding */
52393      int i;                 /* Space used in zNewRecord[] */
52394      int len;               /* Length of a field */
52395    } ao;
52396    struct OP_Count_stack_vars {
52397      i64 nEntry;
52398      BtCursor *pCrsr;
52399    } ap;
52400    struct OP_Savepoint_stack_vars {
52401      int p1;                         /* Value of P1 operand */
52402      char *zName;                    /* Name of savepoint */
52403      int nName;
52404      Savepoint *pNew;
52405      Savepoint *pSavepoint;
52406      Savepoint *pTmp;
52407      int iSavepoint;
52408      int ii;
52409    } aq;
52410    struct OP_AutoCommit_stack_vars {
52411      int desiredAutoCommit;
52412      int iRollback;
52413      int turnOnAC;
52414    } ar;
52415    struct OP_Transaction_stack_vars {
52416      Btree *pBt;
52417    } as;
52418    struct OP_ReadCookie_stack_vars {
52419      int iMeta;
52420      int iDb;
52421      int iCookie;
52422    } at;
52423    struct OP_SetCookie_stack_vars {
52424      Db *pDb;
52425    } au;
52426    struct OP_VerifyCookie_stack_vars {
52427      int iMeta;
52428      Btree *pBt;
52429    } av;
52430    struct OP_OpenWrite_stack_vars {
52431      int nField;
52432      KeyInfo *pKeyInfo;
52433      int p2;
52434      int iDb;
52435      int wrFlag;
52436      Btree *pX;
52437      VdbeCursor *pCur;
52438      Db *pDb;
52439    } aw;
52440    struct OP_OpenEphemeral_stack_vars {
52441      VdbeCursor *pCx;
52442    } ax;
52443    struct OP_OpenPseudo_stack_vars {
52444      VdbeCursor *pCx;
52445    } ay;
52446    struct OP_SeekGt_stack_vars {
52447      int res;
52448      int oc;
52449      VdbeCursor *pC;
52450      UnpackedRecord r;
52451      int nField;
52452      i64 iKey;      /* The rowid we are to seek to */
52453    } az;
52454    struct OP_Seek_stack_vars {
52455      VdbeCursor *pC;
52456    } ba;
52457    struct OP_Found_stack_vars {
52458      int alreadyExists;
52459      VdbeCursor *pC;
52460      int res;
52461      UnpackedRecord *pIdxKey;
52462      UnpackedRecord r;
52463      char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
52464    } bb;
52465    struct OP_IsUnique_stack_vars {
52466      u16 ii;
52467      VdbeCursor *pCx;
52468      BtCursor *pCrsr;
52469      u16 nField;
52470      Mem *aMx;
52471      UnpackedRecord r;                  /* B-Tree index search key */
52472      i64 R;                             /* Rowid stored in register P3 */
52473    } bc;
52474    struct OP_NotExists_stack_vars {
52475      VdbeCursor *pC;
52476      BtCursor *pCrsr;
52477      int res;
52478      u64 iKey;
52479    } bd;
52480    struct OP_NewRowid_stack_vars {
52481      i64 v;                 /* The new rowid */
52482      VdbeCursor *pC;        /* Cursor of table to get the new rowid */
52483      int res;               /* Result of an sqlite3BtreeLast() */
52484      int cnt;               /* Counter to limit the number of searches */
52485      Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
52486      VdbeFrame *pFrame;     /* Root frame of VDBE */
52487    } be;
52488    struct OP_InsertInt_stack_vars {
52489      Mem *pData;       /* MEM cell holding data for the record to be inserted */
52490      Mem *pKey;        /* MEM cell holding key  for the record */
52491      i64 iKey;         /* The integer ROWID or key for the record to be inserted */
52492      VdbeCursor *pC;   /* Cursor to table into which insert is written */
52493      int nZero;        /* Number of zero-bytes to append */
52494      int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
52495      const char *zDb;  /* database name - used by the update hook */
52496      const char *zTbl; /* Table name - used by the opdate hook */
52497      int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
52498    } bf;
52499    struct OP_Delete_stack_vars {
52500      i64 iKey;
52501      VdbeCursor *pC;
52502    } bg;
52503    struct OP_RowData_stack_vars {
52504      VdbeCursor *pC;
52505      BtCursor *pCrsr;
52506      u32 n;
52507      i64 n64;
52508    } bh;
52509    struct OP_Rowid_stack_vars {
52510      VdbeCursor *pC;
52511      i64 v;
52512      sqlite3_vtab *pVtab;
52513      const sqlite3_module *pModule;
52514    } bi;
52515    struct OP_NullRow_stack_vars {
52516      VdbeCursor *pC;
52517    } bj;
52518    struct OP_Last_stack_vars {
52519      VdbeCursor *pC;
52520      BtCursor *pCrsr;
52521      int res;
52522    } bk;
52523    struct OP_Rewind_stack_vars {
52524      VdbeCursor *pC;
52525      BtCursor *pCrsr;
52526      int res;
52527    } bl;
52528    struct OP_Next_stack_vars {
52529      VdbeCursor *pC;
52530      BtCursor *pCrsr;
52531      int res;
52532    } bm;
52533    struct OP_IdxInsert_stack_vars {
52534      VdbeCursor *pC;
52535      BtCursor *pCrsr;
52536      int nKey;
52537      const char *zKey;
52538    } bn;
52539    struct OP_IdxDelete_stack_vars {
52540      VdbeCursor *pC;
52541      BtCursor *pCrsr;
52542      int res;
52543      UnpackedRecord r;
52544    } bo;
52545    struct OP_IdxRowid_stack_vars {
52546      BtCursor *pCrsr;
52547      VdbeCursor *pC;
52548      i64 rowid;
52549    } bp;
52550    struct OP_IdxGE_stack_vars {
52551      VdbeCursor *pC;
52552      int res;
52553      UnpackedRecord r;
52554    } bq;
52555    struct OP_Destroy_stack_vars {
52556      int iMoved;
52557      int iCnt;
52558      Vdbe *pVdbe;
52559      int iDb;
52560    } br;
52561    struct OP_Clear_stack_vars {
52562      int nChange;
52563    } bs;
52564    struct OP_CreateTable_stack_vars {
52565      int pgno;
52566      int flags;
52567      Db *pDb;
52568    } bt;
52569    struct OP_ParseSchema_stack_vars {
52570      int iDb;
52571      const char *zMaster;
52572      char *zSql;
52573      InitData initData;
52574    } bu;
52575    struct OP_IntegrityCk_stack_vars {
52576      int nRoot;      /* Number of tables to check.  (Number of root pages.) */
52577      int *aRoot;     /* Array of rootpage numbers for tables to be checked */
52578      int j;          /* Loop counter */
52579      int nErr;       /* Number of errors reported */
52580      char *z;        /* Text of the error report */
52581      Mem *pnErr;     /* Register keeping track of errors remaining */
52582    } bv;
52583    struct OP_RowSetRead_stack_vars {
52584      i64 val;
52585    } bw;
52586    struct OP_RowSetTest_stack_vars {
52587      int iSet;
52588      int exists;
52589    } bx;
52590    struct OP_Program_stack_vars {
52591      int nMem;               /* Number of memory registers for sub-program */
52592      int nByte;              /* Bytes of runtime space required for sub-program */
52593      Mem *pRt;               /* Register to allocate runtime space */
52594      Mem *pMem;              /* Used to iterate through memory cells */
52595      Mem *pEnd;              /* Last memory cell in new array */
52596      VdbeFrame *pFrame;      /* New vdbe frame to execute in */
52597      SubProgram *pProgram;   /* Sub-program to execute */
52598      void *t;                /* Token identifying trigger */
52599    } by;
52600    struct OP_Param_stack_vars {
52601      VdbeFrame *pFrame;
52602      Mem *pIn;
52603    } bz;
52604    struct OP_MemMax_stack_vars {
52605      Mem *pIn1;
52606      VdbeFrame *pFrame;
52607    } ca;
52608    struct OP_AggStep_stack_vars {
52609      int n;
52610      int i;
52611      Mem *pMem;
52612      Mem *pRec;
52613      sqlite3_context ctx;
52614      sqlite3_value **apVal;
52615    } cb;
52616    struct OP_AggFinal_stack_vars {
52617      Mem *pMem;
52618    } cc;
52619    struct OP_IncrVacuum_stack_vars {
52620      Btree *pBt;
52621    } cd;
52622    struct OP_VBegin_stack_vars {
52623      VTable *pVTab;
52624    } ce;
52625    struct OP_VOpen_stack_vars {
52626      VdbeCursor *pCur;
52627      sqlite3_vtab_cursor *pVtabCursor;
52628      sqlite3_vtab *pVtab;
52629      sqlite3_module *pModule;
52630    } cf;
52631    struct OP_VFilter_stack_vars {
52632      int nArg;
52633      int iQuery;
52634      const sqlite3_module *pModule;
52635      Mem *pQuery;
52636      Mem *pArgc;
52637      sqlite3_vtab_cursor *pVtabCursor;
52638      sqlite3_vtab *pVtab;
52639      VdbeCursor *pCur;
52640      int res;
52641      int i;
52642      Mem **apArg;
52643    } cg;
52644    struct OP_VColumn_stack_vars {
52645      sqlite3_vtab *pVtab;
52646      const sqlite3_module *pModule;
52647      Mem *pDest;
52648      sqlite3_context sContext;
52649    } ch;
52650    struct OP_VNext_stack_vars {
52651      sqlite3_vtab *pVtab;
52652      const sqlite3_module *pModule;
52653      int res;
52654      VdbeCursor *pCur;
52655    } ci;
52656    struct OP_VRename_stack_vars {
52657      sqlite3_vtab *pVtab;
52658      Mem *pName;
52659    } cj;
52660    struct OP_VUpdate_stack_vars {
52661      sqlite3_vtab *pVtab;
52662      sqlite3_module *pModule;
52663      int nArg;
52664      int i;
52665      sqlite_int64 rowid;
52666      Mem **apArg;
52667      Mem *pX;
52668    } ck;
52669    struct OP_Pagecount_stack_vars {
52670      int p1;
52671      int nPage;
52672      Pager *pPager;
52673    } cl;
52674    struct OP_Trace_stack_vars {
52675      char *zTrace;
52676    } cm;
52677  } u;
52678  /* End automatically generated code
52679  ********************************************************************/
52680
52681  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
52682  assert( db->magic==SQLITE_MAGIC_BUSY );
52683  sqlite3VdbeMutexArrayEnter(p);
52684  if( p->rc==SQLITE_NOMEM ){
52685    /* This happens if a malloc() inside a call to sqlite3_column_text() or
52686    ** sqlite3_column_text16() failed.  */
52687    goto no_mem;
52688  }
52689  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
52690  p->rc = SQLITE_OK;
52691  assert( p->explain==0 );
52692  p->pResultSet = 0;
52693  db->busyHandler.nBusy = 0;
52694  CHECK_FOR_INTERRUPT;
52695  sqlite3VdbeIOTraceSql(p);
52696#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52697  checkProgress = db->xProgress!=0;
52698#endif
52699#ifdef SQLITE_DEBUG
52700  sqlite3BeginBenignMalloc();
52701  if( p->pc==0
52702   && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
52703  ){
52704    int i;
52705    printf("VDBE Program Listing:\n");
52706    sqlite3VdbePrintSql(p);
52707    for(i=0; i<p->nOp; i++){
52708      sqlite3VdbePrintOp(stdout, i, &aOp[i]);
52709    }
52710  }
52711  if( fileExists(db, "vdbe_trace") ){
52712    p->trace = stdout;
52713  }
52714  sqlite3EndBenignMalloc();
52715#endif
52716  for(pc=p->pc; rc==SQLITE_OK; pc++){
52717    assert( pc>=0 && pc<p->nOp );
52718    if( db->mallocFailed ) goto no_mem;
52719#ifdef VDBE_PROFILE
52720    origPc = pc;
52721    start = sqlite3Hwtime();
52722#endif
52723    pOp = &aOp[pc];
52724
52725    /* Only allow tracing if SQLITE_DEBUG is defined.
52726    */
52727#ifdef SQLITE_DEBUG
52728    if( p->trace ){
52729      if( pc==0 ){
52730        printf("VDBE Execution Trace:\n");
52731        sqlite3VdbePrintSql(p);
52732      }
52733      sqlite3VdbePrintOp(p->trace, pc, pOp);
52734    }
52735    if( p->trace==0 && pc==0 ){
52736      sqlite3BeginBenignMalloc();
52737      if( fileExists(db, "vdbe_sqltrace") ){
52738        sqlite3VdbePrintSql(p);
52739      }
52740      sqlite3EndBenignMalloc();
52741    }
52742#endif
52743
52744
52745    /* Check to see if we need to simulate an interrupt.  This only happens
52746    ** if we have a special test build.
52747    */
52748#ifdef SQLITE_TEST
52749    if( sqlite3_interrupt_count>0 ){
52750      sqlite3_interrupt_count--;
52751      if( sqlite3_interrupt_count==0 ){
52752        sqlite3_interrupt(db);
52753      }
52754    }
52755#endif
52756
52757#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
52758    /* Call the progress callback if it is configured and the required number
52759    ** of VDBE ops have been executed (either since this invocation of
52760    ** sqlite3VdbeExec() or since last time the progress callback was called).
52761    ** If the progress callback returns non-zero, exit the virtual machine with
52762    ** a return code SQLITE_ABORT.
52763    */
52764    if( checkProgress ){
52765      if( db->nProgressOps==nProgressOps ){
52766        int prc;
52767        if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
52768        prc =db->xProgress(db->pProgressArg);
52769        if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
52770        if( prc!=0 ){
52771          rc = SQLITE_INTERRUPT;
52772          goto vdbe_error_halt;
52773        }
52774        nProgressOps = 0;
52775      }
52776      nProgressOps++;
52777    }
52778#endif
52779
52780    /* On any opcode with the "out2-prerelase" tag, free any
52781    ** external allocations out of mem[p2] and set mem[p2] to be
52782    ** an undefined integer.  Opcodes will either fill in the integer
52783    ** value or convert mem[p2] to a different type.
52784    */
52785    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
52786    if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
52787      assert( pOp->p2>0 );
52788      assert( pOp->p2<=p->nMem );
52789      pOut = &aMem[pOp->p2];
52790      sqlite3VdbeMemReleaseExternal(pOut);
52791      pOut->flags = MEM_Int;
52792    }
52793
52794    /* Sanity checking on other operands */
52795#ifdef SQLITE_DEBUG
52796    if( (pOp->opflags & OPFLG_IN1)!=0 ){
52797      assert( pOp->p1>0 );
52798      assert( pOp->p1<=p->nMem );
52799      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
52800    }
52801    if( (pOp->opflags & OPFLG_IN2)!=0 ){
52802      assert( pOp->p2>0 );
52803      assert( pOp->p2<=p->nMem );
52804      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
52805    }
52806    if( (pOp->opflags & OPFLG_IN3)!=0 ){
52807      assert( pOp->p3>0 );
52808      assert( pOp->p3<=p->nMem );
52809      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
52810    }
52811    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
52812      assert( pOp->p2>0 );
52813      assert( pOp->p2<=p->nMem );
52814    }
52815    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
52816      assert( pOp->p3>0 );
52817      assert( pOp->p3<=p->nMem );
52818    }
52819#endif
52820
52821    switch( pOp->opcode ){
52822
52823/*****************************************************************************
52824** What follows is a massive switch statement where each case implements a
52825** separate instruction in the virtual machine.  If we follow the usual
52826** indentation conventions, each case should be indented by 6 spaces.  But
52827** that is a lot of wasted space on the left margin.  So the code within
52828** the switch statement will break with convention and be flush-left. Another
52829** big comment (similar to this one) will mark the point in the code where
52830** we transition back to normal indentation.
52831**
52832** The formatting of each case is important.  The makefile for SQLite
52833** generates two C files "opcodes.h" and "opcodes.c" by scanning this
52834** file looking for lines that begin with "case OP_".  The opcodes.h files
52835** will be filled with #defines that give unique integer values to each
52836** opcode and the opcodes.c file is filled with an array of strings where
52837** each string is the symbolic name for the corresponding opcode.  If the
52838** case statement is followed by a comment of the form "/# same as ... #/"
52839** that comment is used to determine the particular value of the opcode.
52840**
52841** Other keywords in the comment that follows each case are used to
52842** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
52843** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
52844** the mkopcodeh.awk script for additional information.
52845**
52846** Documentation about VDBE opcodes is generated by scanning this file
52847** for lines of that contain "Opcode:".  That line and all subsequent
52848** comment lines are used in the generation of the opcode.html documentation
52849** file.
52850**
52851** SUMMARY:
52852**
52853**     Formatting is important to scripts that scan this file.
52854**     Do not deviate from the formatting style currently in use.
52855**
52856*****************************************************************************/
52857
52858/* Opcode:  Goto * P2 * * *
52859**
52860** An unconditional jump to address P2.
52861** The next instruction executed will be
52862** the one at index P2 from the beginning of
52863** the program.
52864*/
52865case OP_Goto: {             /* jump */
52866  CHECK_FOR_INTERRUPT;
52867  pc = pOp->p2 - 1;
52868  break;
52869}
52870
52871/* Opcode:  Gosub P1 P2 * * *
52872**
52873** Write the current address onto register P1
52874** and then jump to address P2.
52875*/
52876case OP_Gosub: {            /* jump, in1 */
52877  pIn1 = &aMem[pOp->p1];
52878  assert( (pIn1->flags & MEM_Dyn)==0 );
52879  pIn1->flags = MEM_Int;
52880  pIn1->u.i = pc;
52881  REGISTER_TRACE(pOp->p1, pIn1);
52882  pc = pOp->p2 - 1;
52883  break;
52884}
52885
52886/* Opcode:  Return P1 * * * *
52887**
52888** Jump to the next instruction after the address in register P1.
52889*/
52890case OP_Return: {           /* in1 */
52891  pIn1 = &aMem[pOp->p1];
52892  assert( pIn1->flags & MEM_Int );
52893  pc = (int)pIn1->u.i;
52894  break;
52895}
52896
52897/* Opcode:  Yield P1 * * * *
52898**
52899** Swap the program counter with the value in register P1.
52900*/
52901case OP_Yield: {            /* in1 */
52902#if 0  /* local variables moved into u.aa */
52903  int pcDest;
52904#endif /* local variables moved into u.aa */
52905  pIn1 = &aMem[pOp->p1];
52906  assert( (pIn1->flags & MEM_Dyn)==0 );
52907  pIn1->flags = MEM_Int;
52908  u.aa.pcDest = (int)pIn1->u.i;
52909  pIn1->u.i = pc;
52910  REGISTER_TRACE(pOp->p1, pIn1);
52911  pc = u.aa.pcDest;
52912  break;
52913}
52914
52915/* Opcode:  HaltIfNull  P1 P2 P3 P4 *
52916**
52917** Check the value in register P3.  If is is NULL then Halt using
52918** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
52919** value in register P3 is not NULL, then this routine is a no-op.
52920*/
52921case OP_HaltIfNull: {      /* in3 */
52922  pIn3 = &aMem[pOp->p3];
52923  if( (pIn3->flags & MEM_Null)==0 ) break;
52924  /* Fall through into OP_Halt */
52925}
52926
52927/* Opcode:  Halt P1 P2 * P4 *
52928**
52929** Exit immediately.  All open cursors, etc are closed
52930** automatically.
52931**
52932** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
52933** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
52934** For errors, it can be some other value.  If P1!=0 then P2 will determine
52935** whether or not to rollback the current transaction.  Do not rollback
52936** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
52937** then back out all changes that have occurred during this execution of the
52938** VDBE, but do not rollback the transaction.
52939**
52940** If P4 is not null then it is an error message string.
52941**
52942** There is an implied "Halt 0 0 0" instruction inserted at the very end of
52943** every program.  So a jump past the last instruction of the program
52944** is the same as executing Halt.
52945*/
52946case OP_Halt: {
52947  if( pOp->p1==SQLITE_OK && p->pFrame ){
52948    /* Halt the sub-program. Return control to the parent frame. */
52949    VdbeFrame *pFrame = p->pFrame;
52950    p->pFrame = pFrame->pParent;
52951    p->nFrame--;
52952    sqlite3VdbeSetChanges(db, p->nChange);
52953    pc = sqlite3VdbeFrameRestore(pFrame);
52954    if( pOp->p2==OE_Ignore ){
52955      /* Instruction pc is the OP_Program that invoked the sub-program
52956      ** currently being halted. If the p2 instruction of this OP_Halt
52957      ** instruction is set to OE_Ignore, then the sub-program is throwing
52958      ** an IGNORE exception. In this case jump to the address specified
52959      ** as the p2 of the calling OP_Program.  */
52960      pc = p->aOp[pc].p2-1;
52961    }
52962    aOp = p->aOp;
52963    aMem = p->aMem;
52964    break;
52965  }
52966
52967  p->rc = pOp->p1;
52968  p->errorAction = (u8)pOp->p2;
52969  p->pc = pc;
52970  if( pOp->p4.z ){
52971    sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
52972  }
52973  rc = sqlite3VdbeHalt(p);
52974  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
52975  if( rc==SQLITE_BUSY ){
52976    p->rc = rc = SQLITE_BUSY;
52977  }else{
52978    assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
52979    assert( rc==SQLITE_OK || db->nDeferredCons>0 );
52980    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
52981  }
52982  goto vdbe_return;
52983}
52984
52985/* Opcode: Integer P1 P2 * * *
52986**
52987** The 32-bit integer value P1 is written into register P2.
52988*/
52989case OP_Integer: {         /* out2-prerelease */
52990  pOut->u.i = pOp->p1;
52991  break;
52992}
52993
52994/* Opcode: Int64 * P2 * P4 *
52995**
52996** P4 is a pointer to a 64-bit integer value.
52997** Write that value into register P2.
52998*/
52999case OP_Int64: {           /* out2-prerelease */
53000  assert( pOp->p4.pI64!=0 );
53001  pOut->u.i = *pOp->p4.pI64;
53002  break;
53003}
53004
53005/* Opcode: Real * P2 * P4 *
53006**
53007** P4 is a pointer to a 64-bit floating point value.
53008** Write that value into register P2.
53009*/
53010case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
53011  pOut->flags = MEM_Real;
53012  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
53013  pOut->r = *pOp->p4.pReal;
53014  break;
53015}
53016
53017/* Opcode: String8 * P2 * P4 *
53018**
53019** P4 points to a nul terminated UTF-8 string. This opcode is transformed
53020** into an OP_String before it is executed for the first time.
53021*/
53022case OP_String8: {         /* same as TK_STRING, out2-prerelease */
53023  assert( pOp->p4.z!=0 );
53024  pOp->opcode = OP_String;
53025  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
53026
53027#ifndef SQLITE_OMIT_UTF16
53028  if( encoding!=SQLITE_UTF8 ){
53029    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
53030    if( rc==SQLITE_TOOBIG ) goto too_big;
53031    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
53032    assert( pOut->zMalloc==pOut->z );
53033    assert( pOut->flags & MEM_Dyn );
53034    pOut->zMalloc = 0;
53035    pOut->flags |= MEM_Static;
53036    pOut->flags &= ~MEM_Dyn;
53037    if( pOp->p4type==P4_DYNAMIC ){
53038      sqlite3DbFree(db, pOp->p4.z);
53039    }
53040    pOp->p4type = P4_DYNAMIC;
53041    pOp->p4.z = pOut->z;
53042    pOp->p1 = pOut->n;
53043  }
53044#endif
53045  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
53046    goto too_big;
53047  }
53048  /* Fall through to the next case, OP_String */
53049}
53050
53051/* Opcode: String P1 P2 * P4 *
53052**
53053** The string value P4 of length P1 (bytes) is stored in register P2.
53054*/
53055case OP_String: {          /* out2-prerelease */
53056  assert( pOp->p4.z!=0 );
53057  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
53058  pOut->z = pOp->p4.z;
53059  pOut->n = pOp->p1;
53060  pOut->enc = encoding;
53061  UPDATE_MAX_BLOBSIZE(pOut);
53062  break;
53063}
53064
53065/* Opcode: Null * P2 * * *
53066**
53067** Write a NULL into register P2.
53068*/
53069case OP_Null: {           /* out2-prerelease */
53070  pOut->flags = MEM_Null;
53071  break;
53072}
53073
53074
53075/* Opcode: Blob P1 P2 * P4
53076**
53077** P4 points to a blob of data P1 bytes long.  Store this
53078** blob in register P2. This instruction is not coded directly
53079** by the compiler. Instead, the compiler layer specifies
53080** an OP_HexBlob opcode, with the hex string representation of
53081** the blob as P4. This opcode is transformed to an OP_Blob
53082** the first time it is executed.
53083*/
53084case OP_Blob: {                /* out2-prerelease */
53085  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
53086  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
53087  pOut->enc = encoding;
53088  UPDATE_MAX_BLOBSIZE(pOut);
53089  break;
53090}
53091
53092/* Opcode: Variable P1 P2 P3 P4 *
53093**
53094** Transfer the values of bound parameters P1..P1+P3-1 into registers
53095** P2..P2+P3-1.
53096**
53097** If the parameter is named, then its name appears in P4 and P3==1.
53098** The P4 value is used by sqlite3_bind_parameter_name().
53099*/
53100case OP_Variable: {
53101#if 0  /* local variables moved into u.ab */
53102  int p1;          /* Variable to copy from */
53103  int p2;          /* Register to copy to */
53104  int n;           /* Number of values left to copy */
53105  Mem *pVar;       /* Value being transferred */
53106#endif /* local variables moved into u.ab */
53107
53108  u.ab.p1 = pOp->p1 - 1;
53109  u.ab.p2 = pOp->p2;
53110  u.ab.n = pOp->p3;
53111  assert( u.ab.p1>=0 && u.ab.p1+u.ab.n<=p->nVar );
53112  assert( u.ab.p2>=1 && u.ab.p2+u.ab.n-1<=p->nMem );
53113  assert( pOp->p4.z==0 || pOp->p3==1 || pOp->p3==0 );
53114
53115  while( u.ab.n-- > 0 ){
53116    u.ab.pVar = &p->aVar[u.ab.p1++];
53117    if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
53118      goto too_big;
53119    }
53120    pOut = &aMem[u.ab.p2++];
53121    sqlite3VdbeMemReleaseExternal(pOut);
53122    pOut->flags = MEM_Null;
53123    sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
53124    UPDATE_MAX_BLOBSIZE(pOut);
53125  }
53126  break;
53127}
53128
53129/* Opcode: Move P1 P2 P3 * *
53130**
53131** Move the values in register P1..P1+P3-1 over into
53132** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
53133** left holding a NULL.  It is an error for register ranges
53134** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
53135*/
53136case OP_Move: {
53137#if 0  /* local variables moved into u.ac */
53138  char *zMalloc;   /* Holding variable for allocated memory */
53139  int n;           /* Number of registers left to copy */
53140  int p1;          /* Register to copy from */
53141  int p2;          /* Register to copy to */
53142#endif /* local variables moved into u.ac */
53143
53144  u.ac.n = pOp->p3;
53145  u.ac.p1 = pOp->p1;
53146  u.ac.p2 = pOp->p2;
53147  assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
53148  assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
53149
53150  pIn1 = &aMem[u.ac.p1];
53151  pOut = &aMem[u.ac.p2];
53152  while( u.ac.n-- ){
53153    assert( pOut<=&aMem[p->nMem] );
53154    assert( pIn1<=&aMem[p->nMem] );
53155    u.ac.zMalloc = pOut->zMalloc;
53156    pOut->zMalloc = 0;
53157    sqlite3VdbeMemMove(pOut, pIn1);
53158    pIn1->zMalloc = u.ac.zMalloc;
53159    REGISTER_TRACE(u.ac.p2++, pOut);
53160    pIn1++;
53161    pOut++;
53162  }
53163  break;
53164}
53165
53166/* Opcode: Copy P1 P2 * * *
53167**
53168** Make a copy of register P1 into register P2.
53169**
53170** This instruction makes a deep copy of the value.  A duplicate
53171** is made of any string or blob constant.  See also OP_SCopy.
53172*/
53173case OP_Copy: {             /* in1, out2 */
53174  pIn1 = &aMem[pOp->p1];
53175  pOut = &aMem[pOp->p2];
53176  assert( pOut!=pIn1 );
53177  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
53178  Deephemeralize(pOut);
53179  REGISTER_TRACE(pOp->p2, pOut);
53180  break;
53181}
53182
53183/* Opcode: SCopy P1 P2 * * *
53184**
53185** Make a shallow copy of register P1 into register P2.
53186**
53187** This instruction makes a shallow copy of the value.  If the value
53188** is a string or blob, then the copy is only a pointer to the
53189** original and hence if the original changes so will the copy.
53190** Worse, if the original is deallocated, the copy becomes invalid.
53191** Thus the program must guarantee that the original will not change
53192** during the lifetime of the copy.  Use OP_Copy to make a complete
53193** copy.
53194*/
53195case OP_SCopy: {            /* in1, out2 */
53196  pIn1 = &aMem[pOp->p1];
53197  pOut = &aMem[pOp->p2];
53198  assert( pOut!=pIn1 );
53199  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
53200  REGISTER_TRACE(pOp->p2, pOut);
53201  break;
53202}
53203
53204/* Opcode: ResultRow P1 P2 * * *
53205**
53206** The registers P1 through P1+P2-1 contain a single row of
53207** results. This opcode causes the sqlite3_step() call to terminate
53208** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
53209** structure to provide access to the top P1 values as the result
53210** row.
53211*/
53212case OP_ResultRow: {
53213#if 0  /* local variables moved into u.ad */
53214  Mem *pMem;
53215  int i;
53216#endif /* local variables moved into u.ad */
53217  assert( p->nResColumn==pOp->p2 );
53218  assert( pOp->p1>0 );
53219  assert( pOp->p1+pOp->p2<=p->nMem+1 );
53220
53221  /* If this statement has violated immediate foreign key constraints, do
53222  ** not return the number of rows modified. And do not RELEASE the statement
53223  ** transaction. It needs to be rolled back.  */
53224  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
53225    assert( db->flags&SQLITE_CountRows );
53226    assert( p->usesStmtJournal );
53227    break;
53228  }
53229
53230  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
53231  ** DML statements invoke this opcode to return the number of rows
53232  ** modified to the user. This is the only way that a VM that
53233  ** opens a statement transaction may invoke this opcode.
53234  **
53235  ** In case this is such a statement, close any statement transaction
53236  ** opened by this VM before returning control to the user. This is to
53237  ** ensure that statement-transactions are always nested, not overlapping.
53238  ** If the open statement-transaction is not closed here, then the user
53239  ** may step another VM that opens its own statement transaction. This
53240  ** may lead to overlapping statement transactions.
53241  **
53242  ** The statement transaction is never a top-level transaction.  Hence
53243  ** the RELEASE call below can never fail.
53244  */
53245  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
53246  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
53247  if( NEVER(rc!=SQLITE_OK) ){
53248    break;
53249  }
53250
53251  /* Invalidate all ephemeral cursor row caches */
53252  p->cacheCtr = (p->cacheCtr + 2)|1;
53253
53254  /* Make sure the results of the current row are \000 terminated
53255  ** and have an assigned type.  The results are de-ephemeralized as
53256  ** as side effect.
53257  */
53258  u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
53259  for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
53260    sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
53261    sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
53262    REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
53263  }
53264  if( db->mallocFailed ) goto no_mem;
53265
53266  /* Return SQLITE_ROW
53267  */
53268  p->pc = pc + 1;
53269  rc = SQLITE_ROW;
53270  goto vdbe_return;
53271}
53272
53273/* Opcode: Concat P1 P2 P3 * *
53274**
53275** Add the text in register P1 onto the end of the text in
53276** register P2 and store the result in register P3.
53277** If either the P1 or P2 text are NULL then store NULL in P3.
53278**
53279**   P3 = P2 || P1
53280**
53281** It is illegal for P1 and P3 to be the same register. Sometimes,
53282** if P3 is the same register as P2, the implementation is able
53283** to avoid a memcpy().
53284*/
53285case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
53286#if 0  /* local variables moved into u.ae */
53287  i64 nByte;
53288#endif /* local variables moved into u.ae */
53289
53290  pIn1 = &aMem[pOp->p1];
53291  pIn2 = &aMem[pOp->p2];
53292  pOut = &aMem[pOp->p3];
53293  assert( pIn1!=pOut );
53294  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
53295    sqlite3VdbeMemSetNull(pOut);
53296    break;
53297  }
53298  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
53299  Stringify(pIn1, encoding);
53300  Stringify(pIn2, encoding);
53301  u.ae.nByte = pIn1->n + pIn2->n;
53302  if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
53303    goto too_big;
53304  }
53305  MemSetTypeFlag(pOut, MEM_Str);
53306  if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
53307    goto no_mem;
53308  }
53309  if( pOut!=pIn2 ){
53310    memcpy(pOut->z, pIn2->z, pIn2->n);
53311  }
53312  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
53313  pOut->z[u.ae.nByte] = 0;
53314  pOut->z[u.ae.nByte+1] = 0;
53315  pOut->flags |= MEM_Term;
53316  pOut->n = (int)u.ae.nByte;
53317  pOut->enc = encoding;
53318  UPDATE_MAX_BLOBSIZE(pOut);
53319  break;
53320}
53321
53322/* Opcode: Add P1 P2 P3 * *
53323**
53324** Add the value in register P1 to the value in register P2
53325** and store the result in register P3.
53326** If either input is NULL, the result is NULL.
53327*/
53328/* Opcode: Multiply P1 P2 P3 * *
53329**
53330**
53331** Multiply the value in register P1 by the value in register P2
53332** and store the result in register P3.
53333** If either input is NULL, the result is NULL.
53334*/
53335/* Opcode: Subtract P1 P2 P3 * *
53336**
53337** Subtract the value in register P1 from the value in register P2
53338** and store the result in register P3.
53339** If either input is NULL, the result is NULL.
53340*/
53341/* Opcode: Divide P1 P2 P3 * *
53342**
53343** Divide the value in register P1 by the value in register P2
53344** and store the result in register P3 (P3=P2/P1). If the value in
53345** register P1 is zero, then the result is NULL. If either input is
53346** NULL, the result is NULL.
53347*/
53348/* Opcode: Remainder P1 P2 P3 * *
53349**
53350** Compute the remainder after integer division of the value in
53351** register P1 by the value in register P2 and store the result in P3.
53352** If the value in register P2 is zero the result is NULL.
53353** If either operand is NULL, the result is NULL.
53354*/
53355case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
53356case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
53357case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
53358case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
53359case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
53360#if 0  /* local variables moved into u.af */
53361  int flags;      /* Combined MEM_* flags from both inputs */
53362  i64 iA;         /* Integer value of left operand */
53363  i64 iB;         /* Integer value of right operand */
53364  double rA;      /* Real value of left operand */
53365  double rB;      /* Real value of right operand */
53366#endif /* local variables moved into u.af */
53367
53368  pIn1 = &aMem[pOp->p1];
53369  applyNumericAffinity(pIn1);
53370  pIn2 = &aMem[pOp->p2];
53371  applyNumericAffinity(pIn2);
53372  pOut = &aMem[pOp->p3];
53373  u.af.flags = pIn1->flags | pIn2->flags;
53374  if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
53375  if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
53376    u.af.iA = pIn1->u.i;
53377    u.af.iB = pIn2->u.i;
53378    switch( pOp->opcode ){
53379      case OP_Add:         u.af.iB += u.af.iA;       break;
53380      case OP_Subtract:    u.af.iB -= u.af.iA;       break;
53381      case OP_Multiply:    u.af.iB *= u.af.iA;       break;
53382      case OP_Divide: {
53383        if( u.af.iA==0 ) goto arithmetic_result_is_null;
53384        /* Dividing the largest possible negative 64-bit integer (1<<63) by
53385        ** -1 returns an integer too large to store in a 64-bit data-type. On
53386        ** some architectures, the value overflows to (1<<63). On others,
53387        ** a SIGFPE is issued. The following statement normalizes this
53388        ** behavior so that all architectures behave as if integer
53389        ** overflow occurred.
53390        */
53391        if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
53392        u.af.iB /= u.af.iA;
53393        break;
53394      }
53395      default: {
53396        if( u.af.iA==0 ) goto arithmetic_result_is_null;
53397        if( u.af.iA==-1 ) u.af.iA = 1;
53398        u.af.iB %= u.af.iA;
53399        break;
53400      }
53401    }
53402    pOut->u.i = u.af.iB;
53403    MemSetTypeFlag(pOut, MEM_Int);
53404  }else{
53405    u.af.rA = sqlite3VdbeRealValue(pIn1);
53406    u.af.rB = sqlite3VdbeRealValue(pIn2);
53407    switch( pOp->opcode ){
53408      case OP_Add:         u.af.rB += u.af.rA;       break;
53409      case OP_Subtract:    u.af.rB -= u.af.rA;       break;
53410      case OP_Multiply:    u.af.rB *= u.af.rA;       break;
53411      case OP_Divide: {
53412        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
53413        if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
53414        u.af.rB /= u.af.rA;
53415        break;
53416      }
53417      default: {
53418        u.af.iA = (i64)u.af.rA;
53419        u.af.iB = (i64)u.af.rB;
53420        if( u.af.iA==0 ) goto arithmetic_result_is_null;
53421        if( u.af.iA==-1 ) u.af.iA = 1;
53422        u.af.rB = (double)(u.af.iB % u.af.iA);
53423        break;
53424      }
53425    }
53426    if( sqlite3IsNaN(u.af.rB) ){
53427      goto arithmetic_result_is_null;
53428    }
53429    pOut->r = u.af.rB;
53430    MemSetTypeFlag(pOut, MEM_Real);
53431    if( (u.af.flags & MEM_Real)==0 ){
53432      sqlite3VdbeIntegerAffinity(pOut);
53433    }
53434  }
53435  break;
53436
53437arithmetic_result_is_null:
53438  sqlite3VdbeMemSetNull(pOut);
53439  break;
53440}
53441
53442/* Opcode: CollSeq * * P4
53443**
53444** P4 is a pointer to a CollSeq struct. If the next call to a user function
53445** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
53446** be returned. This is used by the built-in min(), max() and nullif()
53447** functions.
53448**
53449** The interface used by the implementation of the aforementioned functions
53450** to retrieve the collation sequence set by this opcode is not available
53451** publicly, only to user functions defined in func.c.
53452*/
53453case OP_CollSeq: {
53454  assert( pOp->p4type==P4_COLLSEQ );
53455  break;
53456}
53457
53458/* Opcode: Function P1 P2 P3 P4 P5
53459**
53460** Invoke a user function (P4 is a pointer to a Function structure that
53461** defines the function) with P5 arguments taken from register P2 and
53462** successors.  The result of the function is stored in register P3.
53463** Register P3 must not be one of the function inputs.
53464**
53465** P1 is a 32-bit bitmask indicating whether or not each argument to the
53466** function was determined to be constant at compile time. If the first
53467** argument was constant then bit 0 of P1 is set. This is used to determine
53468** whether meta data associated with a user function argument using the
53469** sqlite3_set_auxdata() API may be safely retained until the next
53470** invocation of this opcode.
53471**
53472** See also: AggStep and AggFinal
53473*/
53474case OP_Function: {
53475#if 0  /* local variables moved into u.ag */
53476  int i;
53477  Mem *pArg;
53478  sqlite3_context ctx;
53479  sqlite3_value **apVal;
53480  int n;
53481#endif /* local variables moved into u.ag */
53482
53483  u.ag.n = pOp->p5;
53484  u.ag.apVal = p->apArg;
53485  assert( u.ag.apVal || u.ag.n==0 );
53486
53487  assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
53488  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
53489  u.ag.pArg = &aMem[pOp->p2];
53490  for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
53491    u.ag.apVal[u.ag.i] = u.ag.pArg;
53492    sqlite3VdbeMemStoreType(u.ag.pArg);
53493    REGISTER_TRACE(pOp->p2, u.ag.pArg);
53494  }
53495
53496  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
53497  if( pOp->p4type==P4_FUNCDEF ){
53498    u.ag.ctx.pFunc = pOp->p4.pFunc;
53499    u.ag.ctx.pVdbeFunc = 0;
53500  }else{
53501    u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
53502    u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
53503  }
53504
53505  assert( pOp->p3>0 && pOp->p3<=p->nMem );
53506  pOut = &aMem[pOp->p3];
53507  u.ag.ctx.s.flags = MEM_Null;
53508  u.ag.ctx.s.db = db;
53509  u.ag.ctx.s.xDel = 0;
53510  u.ag.ctx.s.zMalloc = 0;
53511
53512  /* The output cell may already have a buffer allocated. Move
53513  ** the pointer to u.ag.ctx.s so in case the user-function can use
53514  ** the already allocated buffer instead of allocating a new one.
53515  */
53516  sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
53517  MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
53518
53519  u.ag.ctx.isError = 0;
53520  if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
53521    assert( pOp>aOp );
53522    assert( pOp[-1].p4type==P4_COLLSEQ );
53523    assert( pOp[-1].opcode==OP_CollSeq );
53524    u.ag.ctx.pColl = pOp[-1].p4.pColl;
53525  }
53526  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
53527  (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal);
53528  if( sqlite3SafetyOn(db) ){
53529    sqlite3VdbeMemRelease(&u.ag.ctx.s);
53530    goto abort_due_to_misuse;
53531  }
53532  if( db->mallocFailed ){
53533    /* Even though a malloc() has failed, the implementation of the
53534    ** user function may have called an sqlite3_result_XXX() function
53535    ** to return a value. The following call releases any resources
53536    ** associated with such a value.
53537    **
53538    ** Note: Maybe MemRelease() should be called if sqlite3SafetyOn()
53539    ** fails also (the if(...) statement above). But if people are
53540    ** misusing sqlite, they have bigger problems than a leaked value.
53541    */
53542    sqlite3VdbeMemRelease(&u.ag.ctx.s);
53543    goto no_mem;
53544  }
53545
53546  /* If any auxiliary data functions have been called by this user function,
53547  ** immediately call the destructor for any non-static values.
53548  */
53549  if( u.ag.ctx.pVdbeFunc ){
53550    sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
53551    pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
53552    pOp->p4type = P4_VDBEFUNC;
53553  }
53554
53555  /* If the function returned an error, throw an exception */
53556  if( u.ag.ctx.isError ){
53557    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
53558    rc = u.ag.ctx.isError;
53559  }
53560
53561  /* Copy the result of the function into register P3 */
53562  sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
53563  sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
53564  if( sqlite3VdbeMemTooBig(pOut) ){
53565    goto too_big;
53566  }
53567  REGISTER_TRACE(pOp->p3, pOut);
53568  UPDATE_MAX_BLOBSIZE(pOut);
53569  break;
53570}
53571
53572/* Opcode: BitAnd P1 P2 P3 * *
53573**
53574** Take the bit-wise AND of the values in register P1 and P2 and
53575** store the result in register P3.
53576** If either input is NULL, the result is NULL.
53577*/
53578/* Opcode: BitOr P1 P2 P3 * *
53579**
53580** Take the bit-wise OR of the values in register P1 and P2 and
53581** store the result in register P3.
53582** If either input is NULL, the result is NULL.
53583*/
53584/* Opcode: ShiftLeft P1 P2 P3 * *
53585**
53586** Shift the integer value in register P2 to the left by the
53587** number of bits specified by the integer in regiser P1.
53588** Store the result in register P3.
53589** If either input is NULL, the result is NULL.
53590*/
53591/* Opcode: ShiftRight P1 P2 P3 * *
53592**
53593** Shift the integer value in register P2 to the right by the
53594** number of bits specified by the integer in register P1.
53595** Store the result in register P3.
53596** If either input is NULL, the result is NULL.
53597*/
53598case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
53599case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
53600case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
53601case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
53602#if 0  /* local variables moved into u.ah */
53603  i64 a;
53604  i64 b;
53605#endif /* local variables moved into u.ah */
53606
53607  pIn1 = &aMem[pOp->p1];
53608  pIn2 = &aMem[pOp->p2];
53609  pOut = &aMem[pOp->p3];
53610  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
53611    sqlite3VdbeMemSetNull(pOut);
53612    break;
53613  }
53614  u.ah.a = sqlite3VdbeIntValue(pIn2);
53615  u.ah.b = sqlite3VdbeIntValue(pIn1);
53616  switch( pOp->opcode ){
53617    case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
53618    case OP_BitOr:       u.ah.a |= u.ah.b;     break;
53619    case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
53620    default:  assert( pOp->opcode==OP_ShiftRight );
53621                         u.ah.a >>= u.ah.b;    break;
53622  }
53623  pOut->u.i = u.ah.a;
53624  MemSetTypeFlag(pOut, MEM_Int);
53625  break;
53626}
53627
53628/* Opcode: AddImm  P1 P2 * * *
53629**
53630** Add the constant P2 to the value in register P1.
53631** The result is always an integer.
53632**
53633** To force any register to be an integer, just add 0.
53634*/
53635case OP_AddImm: {            /* in1 */
53636  pIn1 = &aMem[pOp->p1];
53637  sqlite3VdbeMemIntegerify(pIn1);
53638  pIn1->u.i += pOp->p2;
53639  break;
53640}
53641
53642/* Opcode: MustBeInt P1 P2 * * *
53643**
53644** Force the value in register P1 to be an integer.  If the value
53645** in P1 is not an integer and cannot be converted into an integer
53646** without data loss, then jump immediately to P2, or if P2==0
53647** raise an SQLITE_MISMATCH exception.
53648*/
53649case OP_MustBeInt: {            /* jump, in1 */
53650  pIn1 = &aMem[pOp->p1];
53651  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
53652  if( (pIn1->flags & MEM_Int)==0 ){
53653    if( pOp->p2==0 ){
53654      rc = SQLITE_MISMATCH;
53655      goto abort_due_to_error;
53656    }else{
53657      pc = pOp->p2 - 1;
53658    }
53659  }else{
53660    MemSetTypeFlag(pIn1, MEM_Int);
53661  }
53662  break;
53663}
53664
53665/* Opcode: RealAffinity P1 * * * *
53666**
53667** If register P1 holds an integer convert it to a real value.
53668**
53669** This opcode is used when extracting information from a column that
53670** has REAL affinity.  Such column values may still be stored as
53671** integers, for space efficiency, but after extraction we want them
53672** to have only a real value.
53673*/
53674case OP_RealAffinity: {                  /* in1 */
53675  pIn1 = &aMem[pOp->p1];
53676  if( pIn1->flags & MEM_Int ){
53677    sqlite3VdbeMemRealify(pIn1);
53678  }
53679  break;
53680}
53681
53682#ifndef SQLITE_OMIT_CAST
53683/* Opcode: ToText P1 * * * *
53684**
53685** Force the value in register P1 to be text.
53686** If the value is numeric, convert it to a string using the
53687** equivalent of printf().  Blob values are unchanged and
53688** are afterwards simply interpreted as text.
53689**
53690** A NULL value is not changed by this routine.  It remains NULL.
53691*/
53692case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
53693  pIn1 = &aMem[pOp->p1];
53694  if( pIn1->flags & MEM_Null ) break;
53695  assert( MEM_Str==(MEM_Blob>>3) );
53696  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
53697  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
53698  rc = ExpandBlob(pIn1);
53699  assert( pIn1->flags & MEM_Str || db->mallocFailed );
53700  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
53701  UPDATE_MAX_BLOBSIZE(pIn1);
53702  break;
53703}
53704
53705/* Opcode: ToBlob P1 * * * *
53706**
53707** Force the value in register P1 to be a BLOB.
53708** If the value is numeric, convert it to a string first.
53709** Strings are simply reinterpreted as blobs with no change
53710** to the underlying data.
53711**
53712** A NULL value is not changed by this routine.  It remains NULL.
53713*/
53714case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
53715  pIn1 = &aMem[pOp->p1];
53716  if( pIn1->flags & MEM_Null ) break;
53717  if( (pIn1->flags & MEM_Blob)==0 ){
53718    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
53719    assert( pIn1->flags & MEM_Str || db->mallocFailed );
53720    MemSetTypeFlag(pIn1, MEM_Blob);
53721  }else{
53722    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
53723  }
53724  UPDATE_MAX_BLOBSIZE(pIn1);
53725  break;
53726}
53727
53728/* Opcode: ToNumeric P1 * * * *
53729**
53730** Force the value in register P1 to be numeric (either an
53731** integer or a floating-point number.)
53732** If the value is text or blob, try to convert it to an using the
53733** equivalent of atoi() or atof() and store 0 if no such conversion
53734** is possible.
53735**
53736** A NULL value is not changed by this routine.  It remains NULL.
53737*/
53738case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
53739  pIn1 = &aMem[pOp->p1];
53740  if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
53741    sqlite3VdbeMemNumerify(pIn1);
53742  }
53743  break;
53744}
53745#endif /* SQLITE_OMIT_CAST */
53746
53747/* Opcode: ToInt P1 * * * *
53748**
53749** Force the value in register P1 be an integer.  If
53750** The value is currently a real number, drop its fractional part.
53751** If the value is text or blob, try to convert it to an integer using the
53752** equivalent of atoi() and store 0 if no such conversion is possible.
53753**
53754** A NULL value is not changed by this routine.  It remains NULL.
53755*/
53756case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
53757  pIn1 = &aMem[pOp->p1];
53758  if( (pIn1->flags & MEM_Null)==0 ){
53759    sqlite3VdbeMemIntegerify(pIn1);
53760  }
53761  break;
53762}
53763
53764#ifndef SQLITE_OMIT_CAST
53765/* Opcode: ToReal P1 * * * *
53766**
53767** Force the value in register P1 to be a floating point number.
53768** If The value is currently an integer, convert it.
53769** If the value is text or blob, try to convert it to an integer using the
53770** equivalent of atoi() and store 0.0 if no such conversion is possible.
53771**
53772** A NULL value is not changed by this routine.  It remains NULL.
53773*/
53774case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
53775  pIn1 = &aMem[pOp->p1];
53776  if( (pIn1->flags & MEM_Null)==0 ){
53777    sqlite3VdbeMemRealify(pIn1);
53778  }
53779  break;
53780}
53781#endif /* SQLITE_OMIT_CAST */
53782
53783/* Opcode: Lt P1 P2 P3 P4 P5
53784**
53785** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
53786** jump to address P2.
53787**
53788** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
53789** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
53790** bit is clear then fall thru if either operand is NULL.
53791**
53792** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
53793** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
53794** to coerce both inputs according to this affinity before the
53795** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
53796** affinity is used. Note that the affinity conversions are stored
53797** back into the input registers P1 and P3.  So this opcode can cause
53798** persistent changes to registers P1 and P3.
53799**
53800** Once any conversions have taken place, and neither value is NULL,
53801** the values are compared. If both values are blobs then memcmp() is
53802** used to determine the results of the comparison.  If both values
53803** are text, then the appropriate collating function specified in
53804** P4 is  used to do the comparison.  If P4 is not specified then
53805** memcmp() is used to compare text string.  If both values are
53806** numeric, then a numeric comparison is used. If the two values
53807** are of different types, then numbers are considered less than
53808** strings and strings are considered less than blobs.
53809**
53810** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
53811** store a boolean result (either 0, or 1, or NULL) in register P2.
53812*/
53813/* Opcode: Ne P1 P2 P3 P4 P5
53814**
53815** This works just like the Lt opcode except that the jump is taken if
53816** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
53817** additional information.
53818**
53819** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
53820** true or false and is never NULL.  If both operands are NULL then the result
53821** of comparison is false.  If either operand is NULL then the result is true.
53822** If neither operand is NULL the the result is the same as it would be if
53823** the SQLITE_NULLEQ flag were omitted from P5.
53824*/
53825/* Opcode: Eq P1 P2 P3 P4 P5
53826**
53827** This works just like the Lt opcode except that the jump is taken if
53828** the operands in registers P1 and P3 are equal.
53829** See the Lt opcode for additional information.
53830**
53831** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
53832** true or false and is never NULL.  If both operands are NULL then the result
53833** of comparison is true.  If either operand is NULL then the result is false.
53834** If neither operand is NULL the the result is the same as it would be if
53835** the SQLITE_NULLEQ flag were omitted from P5.
53836*/
53837/* Opcode: Le P1 P2 P3 P4 P5
53838**
53839** This works just like the Lt opcode except that the jump is taken if
53840** the content of register P3 is less than or equal to the content of
53841** register P1.  See the Lt opcode for additional information.
53842*/
53843/* Opcode: Gt P1 P2 P3 P4 P5
53844**
53845** This works just like the Lt opcode except that the jump is taken if
53846** the content of register P3 is greater than the content of
53847** register P1.  See the Lt opcode for additional information.
53848*/
53849/* Opcode: Ge P1 P2 P3 P4 P5
53850**
53851** This works just like the Lt opcode except that the jump is taken if
53852** the content of register P3 is greater than or equal to the content of
53853** register P1.  See the Lt opcode for additional information.
53854*/
53855case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
53856case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
53857case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
53858case OP_Le:               /* same as TK_LE, jump, in1, in3 */
53859case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
53860case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
53861#if 0  /* local variables moved into u.ai */
53862  int res;            /* Result of the comparison of pIn1 against pIn3 */
53863  char affinity;      /* Affinity to use for comparison */
53864#endif /* local variables moved into u.ai */
53865
53866  pIn1 = &aMem[pOp->p1];
53867  pIn3 = &aMem[pOp->p3];
53868  if( (pIn1->flags | pIn3->flags)&MEM_Null ){
53869    /* One or both operands are NULL */
53870    if( pOp->p5 & SQLITE_NULLEQ ){
53871      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
53872      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
53873      ** or not both operands are null.
53874      */
53875      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
53876      u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
53877    }else{
53878      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
53879      ** then the result is always NULL.
53880      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
53881      */
53882      if( pOp->p5 & SQLITE_STOREP2 ){
53883        pOut = &aMem[pOp->p2];
53884        MemSetTypeFlag(pOut, MEM_Null);
53885        REGISTER_TRACE(pOp->p2, pOut);
53886      }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
53887        pc = pOp->p2-1;
53888      }
53889      break;
53890    }
53891  }else{
53892    /* Neither operand is NULL.  Do a comparison. */
53893    u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
53894    if( u.ai.affinity ){
53895      applyAffinity(pIn1, u.ai.affinity, encoding);
53896      applyAffinity(pIn3, u.ai.affinity, encoding);
53897      if( db->mallocFailed ) goto no_mem;
53898    }
53899
53900    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
53901    ExpandBlob(pIn1);
53902    ExpandBlob(pIn3);
53903    u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
53904  }
53905  switch( pOp->opcode ){
53906    case OP_Eq:    u.ai.res = u.ai.res==0;     break;
53907    case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
53908    case OP_Lt:    u.ai.res = u.ai.res<0;      break;
53909    case OP_Le:    u.ai.res = u.ai.res<=0;     break;
53910    case OP_Gt:    u.ai.res = u.ai.res>0;      break;
53911    default:       u.ai.res = u.ai.res>=0;     break;
53912  }
53913
53914  if( pOp->p5 & SQLITE_STOREP2 ){
53915    pOut = &aMem[pOp->p2];
53916    MemSetTypeFlag(pOut, MEM_Int);
53917    pOut->u.i = u.ai.res;
53918    REGISTER_TRACE(pOp->p2, pOut);
53919  }else if( u.ai.res ){
53920    pc = pOp->p2-1;
53921  }
53922  break;
53923}
53924
53925/* Opcode: Permutation * * * P4 *
53926**
53927** Set the permutation used by the OP_Compare operator to be the array
53928** of integers in P4.
53929**
53930** The permutation is only valid until the next OP_Permutation, OP_Compare,
53931** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
53932** immediately prior to the OP_Compare.
53933*/
53934case OP_Permutation: {
53935  assert( pOp->p4type==P4_INTARRAY );
53936  assert( pOp->p4.ai );
53937  aPermute = pOp->p4.ai;
53938  break;
53939}
53940
53941/* Opcode: Compare P1 P2 P3 P4 *
53942**
53943** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
53944** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
53945** the comparison for use by the next OP_Jump instruct.
53946**
53947** P4 is a KeyInfo structure that defines collating sequences and sort
53948** orders for the comparison.  The permutation applies to registers
53949** only.  The KeyInfo elements are used sequentially.
53950**
53951** The comparison is a sort comparison, so NULLs compare equal,
53952** NULLs are less than numbers, numbers are less than strings,
53953** and strings are less than blobs.
53954*/
53955case OP_Compare: {
53956#if 0  /* local variables moved into u.aj */
53957  int n;
53958  int i;
53959  int p1;
53960  int p2;
53961  const KeyInfo *pKeyInfo;
53962  int idx;
53963  CollSeq *pColl;    /* Collating sequence to use on this term */
53964  int bRev;          /* True for DESCENDING sort order */
53965#endif /* local variables moved into u.aj */
53966
53967  u.aj.n = pOp->p3;
53968  u.aj.pKeyInfo = pOp->p4.pKeyInfo;
53969  assert( u.aj.n>0 );
53970  assert( u.aj.pKeyInfo!=0 );
53971  u.aj.p1 = pOp->p1;
53972  u.aj.p2 = pOp->p2;
53973#if SQLITE_DEBUG
53974  if( aPermute ){
53975    int k, mx = 0;
53976    for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
53977    assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
53978    assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
53979  }else{
53980    assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
53981    assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
53982  }
53983#endif /* SQLITE_DEBUG */
53984  for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
53985    u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
53986    REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
53987    REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
53988    assert( u.aj.i<u.aj.pKeyInfo->nField );
53989    u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
53990    u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
53991    iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
53992    if( iCompare ){
53993      if( u.aj.bRev ) iCompare = -iCompare;
53994      break;
53995    }
53996  }
53997  aPermute = 0;
53998  break;
53999}
54000
54001/* Opcode: Jump P1 P2 P3 * *
54002**
54003** Jump to the instruction at address P1, P2, or P3 depending on whether
54004** in the most recent OP_Compare instruction the P1 vector was less than
54005** equal to, or greater than the P2 vector, respectively.
54006*/
54007case OP_Jump: {             /* jump */
54008  if( iCompare<0 ){
54009    pc = pOp->p1 - 1;
54010  }else if( iCompare==0 ){
54011    pc = pOp->p2 - 1;
54012  }else{
54013    pc = pOp->p3 - 1;
54014  }
54015  break;
54016}
54017
54018/* Opcode: And P1 P2 P3 * *
54019**
54020** Take the logical AND of the values in registers P1 and P2 and
54021** write the result into register P3.
54022**
54023** If either P1 or P2 is 0 (false) then the result is 0 even if
54024** the other input is NULL.  A NULL and true or two NULLs give
54025** a NULL output.
54026*/
54027/* Opcode: Or P1 P2 P3 * *
54028**
54029** Take the logical OR of the values in register P1 and P2 and
54030** store the answer in register P3.
54031**
54032** If either P1 or P2 is nonzero (true) then the result is 1 (true)
54033** even if the other input is NULL.  A NULL and false or two NULLs
54034** give a NULL output.
54035*/
54036case OP_And:              /* same as TK_AND, in1, in2, out3 */
54037case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
54038#if 0  /* local variables moved into u.ak */
54039  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
54040  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
54041#endif /* local variables moved into u.ak */
54042
54043  pIn1 = &aMem[pOp->p1];
54044  if( pIn1->flags & MEM_Null ){
54045    u.ak.v1 = 2;
54046  }else{
54047    u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
54048  }
54049  pIn2 = &aMem[pOp->p2];
54050  if( pIn2->flags & MEM_Null ){
54051    u.ak.v2 = 2;
54052  }else{
54053    u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
54054  }
54055  if( pOp->opcode==OP_And ){
54056    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
54057    u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
54058  }else{
54059    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
54060    u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
54061  }
54062  pOut = &aMem[pOp->p3];
54063  if( u.ak.v1==2 ){
54064    MemSetTypeFlag(pOut, MEM_Null);
54065  }else{
54066    pOut->u.i = u.ak.v1;
54067    MemSetTypeFlag(pOut, MEM_Int);
54068  }
54069  break;
54070}
54071
54072/* Opcode: Not P1 P2 * * *
54073**
54074** Interpret the value in register P1 as a boolean value.  Store the
54075** boolean complement in register P2.  If the value in register P1 is
54076** NULL, then a NULL is stored in P2.
54077*/
54078case OP_Not: {                /* same as TK_NOT, in1, out2 */
54079  pIn1 = &aMem[pOp->p1];
54080  pOut = &aMem[pOp->p2];
54081  if( pIn1->flags & MEM_Null ){
54082    sqlite3VdbeMemSetNull(pOut);
54083  }else{
54084    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
54085  }
54086  break;
54087}
54088
54089/* Opcode: BitNot P1 P2 * * *
54090**
54091** Interpret the content of register P1 as an integer.  Store the
54092** ones-complement of the P1 value into register P2.  If P1 holds
54093** a NULL then store a NULL in P2.
54094*/
54095case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
54096  pIn1 = &aMem[pOp->p1];
54097  pOut = &aMem[pOp->p2];
54098  if( pIn1->flags & MEM_Null ){
54099    sqlite3VdbeMemSetNull(pOut);
54100  }else{
54101    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
54102  }
54103  break;
54104}
54105
54106/* Opcode: If P1 P2 P3 * *
54107**
54108** Jump to P2 if the value in register P1 is true.  The value is
54109** is considered true if it is numeric and non-zero.  If the value
54110** in P1 is NULL then take the jump if P3 is true.
54111*/
54112/* Opcode: IfNot P1 P2 P3 * *
54113**
54114** Jump to P2 if the value in register P1 is False.  The value is
54115** is considered true if it has a numeric value of zero.  If the value
54116** in P1 is NULL then take the jump if P3 is true.
54117*/
54118case OP_If:                 /* jump, in1 */
54119case OP_IfNot: {            /* jump, in1 */
54120#if 0  /* local variables moved into u.al */
54121  int c;
54122#endif /* local variables moved into u.al */
54123  pIn1 = &aMem[pOp->p1];
54124  if( pIn1->flags & MEM_Null ){
54125    u.al.c = pOp->p3;
54126  }else{
54127#ifdef SQLITE_OMIT_FLOATING_POINT
54128    u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
54129#else
54130    u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
54131#endif
54132    if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
54133  }
54134  if( u.al.c ){
54135    pc = pOp->p2-1;
54136  }
54137  break;
54138}
54139
54140/* Opcode: IsNull P1 P2 * * *
54141**
54142** Jump to P2 if the value in register P1 is NULL.
54143*/
54144case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
54145  pIn1 = &aMem[pOp->p1];
54146  if( (pIn1->flags & MEM_Null)!=0 ){
54147    pc = pOp->p2 - 1;
54148  }
54149  break;
54150}
54151
54152/* Opcode: NotNull P1 P2 * * *
54153**
54154** Jump to P2 if the value in register P1 is not NULL.
54155*/
54156case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
54157  pIn1 = &aMem[pOp->p1];
54158  if( (pIn1->flags & MEM_Null)==0 ){
54159    pc = pOp->p2 - 1;
54160  }
54161  break;
54162}
54163
54164/* Opcode: Column P1 P2 P3 P4 P5
54165**
54166** Interpret the data that cursor P1 points to as a structure built using
54167** the MakeRecord instruction.  (See the MakeRecord opcode for additional
54168** information about the format of the data.)  Extract the P2-th column
54169** from this record.  If there are less that (P2+1)
54170** values in the record, extract a NULL.
54171**
54172** The value extracted is stored in register P3.
54173**
54174** If the column contains fewer than P2 fields, then extract a NULL.  Or,
54175** if the P4 argument is a P4_MEM use the value of the P4 argument as
54176** the result.
54177**
54178** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
54179** then the cache of the cursor is reset prior to extracting the column.
54180** The first OP_Column against a pseudo-table after the value of the content
54181** register has changed should have this bit set.
54182*/
54183case OP_Column: {
54184#if 0  /* local variables moved into u.am */
54185  u32 payloadSize;   /* Number of bytes in the record */
54186  i64 payloadSize64; /* Number of bytes in the record */
54187  int p1;            /* P1 value of the opcode */
54188  int p2;            /* column number to retrieve */
54189  VdbeCursor *pC;    /* The VDBE cursor */
54190  char *zRec;        /* Pointer to complete record-data */
54191  BtCursor *pCrsr;   /* The BTree cursor */
54192  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
54193  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
54194  int nField;        /* number of fields in the record */
54195  int len;           /* The length of the serialized data for the column */
54196  int i;             /* Loop counter */
54197  char *zData;       /* Part of the record being decoded */
54198  Mem *pDest;        /* Where to write the extracted value */
54199  Mem sMem;          /* For storing the record being decoded */
54200  u8 *zIdx;          /* Index into header */
54201  u8 *zEndHdr;       /* Pointer to first byte after the header */
54202  u32 offset;        /* Offset into the data */
54203  u64 offset64;      /* 64-bit offset.  64 bits needed to catch overflow */
54204  int szHdr;         /* Size of the header size field at start of record */
54205  int avail;         /* Number of bytes of available data */
54206  Mem *pReg;         /* PseudoTable input register */
54207#endif /* local variables moved into u.am */
54208
54209
54210  u.am.p1 = pOp->p1;
54211  u.am.p2 = pOp->p2;
54212  u.am.pC = 0;
54213  memset(&u.am.sMem, 0, sizeof(u.am.sMem));
54214  assert( u.am.p1<p->nCursor );
54215  assert( pOp->p3>0 && pOp->p3<=p->nMem );
54216  u.am.pDest = &aMem[pOp->p3];
54217  MemSetTypeFlag(u.am.pDest, MEM_Null);
54218  u.am.zRec = 0;
54219
54220  /* This block sets the variable u.am.payloadSize to be the total number of
54221  ** bytes in the record.
54222  **
54223  ** u.am.zRec is set to be the complete text of the record if it is available.
54224  ** The complete record text is always available for pseudo-tables
54225  ** If the record is stored in a cursor, the complete record text
54226  ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
54227  ** If the data is unavailable,  u.am.zRec is set to NULL.
54228  **
54229  ** We also compute the number of columns in the record.  For cursors,
54230  ** the number of columns is stored in the VdbeCursor.nField element.
54231  */
54232  u.am.pC = p->apCsr[u.am.p1];
54233  assert( u.am.pC!=0 );
54234#ifndef SQLITE_OMIT_VIRTUALTABLE
54235  assert( u.am.pC->pVtabCursor==0 );
54236#endif
54237  u.am.pCrsr = u.am.pC->pCursor;
54238  if( u.am.pCrsr!=0 ){
54239    /* The record is stored in a B-Tree */
54240    rc = sqlite3VdbeCursorMoveto(u.am.pC);
54241    if( rc ) goto abort_due_to_error;
54242    if( u.am.pC->nullRow ){
54243      u.am.payloadSize = 0;
54244    }else if( u.am.pC->cacheStatus==p->cacheCtr ){
54245      u.am.payloadSize = u.am.pC->payloadSize;
54246      u.am.zRec = (char*)u.am.pC->aRow;
54247    }else if( u.am.pC->isIndex ){
54248      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
54249      rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
54250      assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
54251      /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
54252      ** payload size, so it is impossible for u.am.payloadSize64 to be
54253      ** larger than 32 bits. */
54254      assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
54255      u.am.payloadSize = (u32)u.am.payloadSize64;
54256    }else{
54257      assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
54258      rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
54259      assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
54260    }
54261  }else if( u.am.pC->pseudoTableReg>0 ){
54262    u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
54263    assert( u.am.pReg->flags & MEM_Blob );
54264    u.am.payloadSize = u.am.pReg->n;
54265    u.am.zRec = u.am.pReg->z;
54266    u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
54267    assert( u.am.payloadSize==0 || u.am.zRec!=0 );
54268  }else{
54269    /* Consider the row to be NULL */
54270    u.am.payloadSize = 0;
54271  }
54272
54273  /* If u.am.payloadSize is 0, then just store a NULL */
54274  if( u.am.payloadSize==0 ){
54275    assert( u.am.pDest->flags&MEM_Null );
54276    goto op_column_out;
54277  }
54278  assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
54279  if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
54280    goto too_big;
54281  }
54282
54283  u.am.nField = u.am.pC->nField;
54284  assert( u.am.p2<u.am.nField );
54285
54286  /* Read and parse the table header.  Store the results of the parse
54287  ** into the record header cache fields of the cursor.
54288  */
54289  u.am.aType = u.am.pC->aType;
54290  if( u.am.pC->cacheStatus==p->cacheCtr ){
54291    u.am.aOffset = u.am.pC->aOffset;
54292  }else{
54293    assert(u.am.aType);
54294    u.am.avail = 0;
54295    u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
54296    u.am.pC->payloadSize = u.am.payloadSize;
54297    u.am.pC->cacheStatus = p->cacheCtr;
54298
54299    /* Figure out how many bytes are in the header */
54300    if( u.am.zRec ){
54301      u.am.zData = u.am.zRec;
54302    }else{
54303      if( u.am.pC->isIndex ){
54304        u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
54305      }else{
54306        u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
54307      }
54308      /* If KeyFetch()/DataFetch() managed to get the entire payload,
54309      ** save the payload in the u.am.pC->aRow cache.  That will save us from
54310      ** having to make additional calls to fetch the content portion of
54311      ** the record.
54312      */
54313      assert( u.am.avail>=0 );
54314      if( u.am.payloadSize <= (u32)u.am.avail ){
54315        u.am.zRec = u.am.zData;
54316        u.am.pC->aRow = (u8*)u.am.zData;
54317      }else{
54318        u.am.pC->aRow = 0;
54319      }
54320    }
54321    /* The following assert is true in all cases accept when
54322    ** the database file has been corrupted externally.
54323    **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
54324    u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
54325
54326    /* Make sure a corrupt database has not given us an oversize header.
54327    ** Do this now to avoid an oversize memory allocation.
54328    **
54329    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
54330    ** types use so much data space that there can only be 4096 and 32 of
54331    ** them, respectively.  So the maximum header length results from a
54332    ** 3-byte type for each of the maximum of 32768 columns plus three
54333    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
54334    */
54335    if( u.am.offset > 98307 ){
54336      rc = SQLITE_CORRUPT_BKPT;
54337      goto op_column_out;
54338    }
54339
54340    /* Compute in u.am.len the number of bytes of data we need to read in order
54341    ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
54342    ** u.am.nField might be significantly less than the true number of columns
54343    ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
54344    ** We want to minimize u.am.len in order to limit the size of the memory
54345    ** allocation, especially if a corrupt database file has caused u.am.offset
54346    ** to be oversized. Offset is limited to 98307 above.  But 98307 might
54347    ** still exceed Robson memory allocation limits on some configurations.
54348    ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
54349    ** will likely be much smaller since u.am.nField will likely be less than
54350    ** 20 or so.  This insures that Robson memory allocation limits are
54351    ** not exceeded even for corrupt database files.
54352    */
54353    u.am.len = u.am.nField*5 + 3;
54354    if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
54355
54356    /* The KeyFetch() or DataFetch() above are fast and will get the entire
54357    ** record header in most cases.  But they will fail to get the complete
54358    ** record header if the record header does not fit on a single page
54359    ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
54360    ** acquire the complete header text.
54361    */
54362    if( !u.am.zRec && u.am.avail<u.am.len ){
54363      u.am.sMem.flags = 0;
54364      u.am.sMem.db = 0;
54365      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
54366      if( rc!=SQLITE_OK ){
54367        goto op_column_out;
54368      }
54369      u.am.zData = u.am.sMem.z;
54370    }
54371    u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
54372    u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
54373
54374    /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
54375    ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
54376    ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
54377    ** of the record to the start of the data for the u.am.i-th column
54378    */
54379    u.am.offset64 = u.am.offset;
54380    for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
54381      if( u.am.zIdx<u.am.zEndHdr ){
54382        u.am.aOffset[u.am.i] = (u32)u.am.offset64;
54383        u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
54384        u.am.offset64 += sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
54385      }else{
54386        /* If u.am.i is less that u.am.nField, then there are less fields in this
54387        ** record than SetNumColumns indicated there are columns in the
54388        ** table. Set the u.am.offset for any extra columns not present in
54389        ** the record to 0. This tells code below to store a NULL
54390        ** instead of deserializing a value from the record.
54391        */
54392        u.am.aOffset[u.am.i] = 0;
54393      }
54394    }
54395    sqlite3VdbeMemRelease(&u.am.sMem);
54396    u.am.sMem.flags = MEM_Null;
54397
54398    /* If we have read more header data than was contained in the header,
54399    ** or if the end of the last field appears to be past the end of the
54400    ** record, or if the end of the last field appears to be before the end
54401    ** of the record (when all fields present), then we must be dealing
54402    ** with a corrupt database.
54403    */
54404    if( (u.am.zIdx > u.am.zEndHdr)|| (u.am.offset64 > u.am.payloadSize)
54405     || (u.am.zIdx==u.am.zEndHdr && u.am.offset64!=(u64)u.am.payloadSize) ){
54406      rc = SQLITE_CORRUPT_BKPT;
54407      goto op_column_out;
54408    }
54409  }
54410
54411  /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
54412  ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
54413  ** then there are not enough fields in the record to satisfy the
54414  ** request.  In this case, set the value NULL or to P4 if P4 is
54415  ** a pointer to a Mem object.
54416  */
54417  if( u.am.aOffset[u.am.p2] ){
54418    assert( rc==SQLITE_OK );
54419    if( u.am.zRec ){
54420      sqlite3VdbeMemReleaseExternal(u.am.pDest);
54421      sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
54422    }else{
54423      u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
54424      sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
54425      rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
54426      if( rc!=SQLITE_OK ){
54427        goto op_column_out;
54428      }
54429      u.am.zData = u.am.sMem.z;
54430      sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
54431    }
54432    u.am.pDest->enc = encoding;
54433  }else{
54434    if( pOp->p4type==P4_MEM ){
54435      sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
54436    }else{
54437      assert( u.am.pDest->flags&MEM_Null );
54438    }
54439  }
54440
54441  /* If we dynamically allocated space to hold the data (in the
54442  ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
54443  ** dynamically allocated space over to the u.am.pDest structure.
54444  ** This prevents a memory copy.
54445  */
54446  if( u.am.sMem.zMalloc ){
54447    assert( u.am.sMem.z==u.am.sMem.zMalloc );
54448    assert( !(u.am.pDest->flags & MEM_Dyn) );
54449    assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
54450    u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
54451    u.am.pDest->flags |= MEM_Term;
54452    u.am.pDest->z = u.am.sMem.z;
54453    u.am.pDest->zMalloc = u.am.sMem.zMalloc;
54454  }
54455
54456  rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
54457
54458op_column_out:
54459  UPDATE_MAX_BLOBSIZE(u.am.pDest);
54460  REGISTER_TRACE(pOp->p3, u.am.pDest);
54461  break;
54462}
54463
54464/* Opcode: Affinity P1 P2 * P4 *
54465**
54466** Apply affinities to a range of P2 registers starting with P1.
54467**
54468** P4 is a string that is P2 characters long. The nth character of the
54469** string indicates the column affinity that should be used for the nth
54470** memory cell in the range.
54471*/
54472case OP_Affinity: {
54473#if 0  /* local variables moved into u.an */
54474  const char *zAffinity;   /* The affinity to be applied */
54475  char cAff;               /* A single character of affinity */
54476#endif /* local variables moved into u.an */
54477
54478  u.an.zAffinity = pOp->p4.z;
54479  assert( u.an.zAffinity!=0 );
54480  assert( u.an.zAffinity[pOp->p2]==0 );
54481  pIn1 = &aMem[pOp->p1];
54482  while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
54483    assert( pIn1 <= &p->aMem[p->nMem] );
54484    ExpandBlob(pIn1);
54485    applyAffinity(pIn1, u.an.cAff, encoding);
54486    pIn1++;
54487  }
54488  break;
54489}
54490
54491/* Opcode: MakeRecord P1 P2 P3 P4 *
54492**
54493** Convert P2 registers beginning with P1 into a single entry
54494** suitable for use as a data record in a database table or as a key
54495** in an index.  The details of the format are irrelevant as long as
54496** the OP_Column opcode can decode the record later.
54497** Refer to source code comments for the details of the record
54498** format.
54499**
54500** P4 may be a string that is P2 characters long.  The nth character of the
54501** string indicates the column affinity that should be used for the nth
54502** field of the index key.
54503**
54504** The mapping from character to affinity is given by the SQLITE_AFF_
54505** macros defined in sqliteInt.h.
54506**
54507** If P4 is NULL then all index fields have the affinity NONE.
54508*/
54509case OP_MakeRecord: {
54510#if 0  /* local variables moved into u.ao */
54511  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
54512  Mem *pRec;             /* The new record */
54513  u64 nData;             /* Number of bytes of data space */
54514  int nHdr;              /* Number of bytes of header space */
54515  i64 nByte;             /* Data space required for this record */
54516  int nZero;             /* Number of zero bytes at the end of the record */
54517  int nVarint;           /* Number of bytes in a varint */
54518  u32 serial_type;       /* Type field */
54519  Mem *pData0;           /* First field to be combined into the record */
54520  Mem *pLast;            /* Last field of the record */
54521  int nField;            /* Number of fields in the record */
54522  char *zAffinity;       /* The affinity string for the record */
54523  int file_format;       /* File format to use for encoding */
54524  int i;                 /* Space used in zNewRecord[] */
54525  int len;               /* Length of a field */
54526#endif /* local variables moved into u.ao */
54527
54528  /* Assuming the record contains N fields, the record format looks
54529  ** like this:
54530  **
54531  ** ------------------------------------------------------------------------
54532  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
54533  ** ------------------------------------------------------------------------
54534  **
54535  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
54536  ** and so froth.
54537  **
54538  ** Each type field is a varint representing the serial type of the
54539  ** corresponding data element (see sqlite3VdbeSerialType()). The
54540  ** hdr-size field is also a varint which is the offset from the beginning
54541  ** of the record to data0.
54542  */
54543  u.ao.nData = 0;         /* Number of bytes of data space */
54544  u.ao.nHdr = 0;          /* Number of bytes of header space */
54545  u.ao.nByte = 0;         /* Data space required for this record */
54546  u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
54547  u.ao.nField = pOp->p1;
54548  u.ao.zAffinity = pOp->p4.z;
54549  assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
54550  u.ao.pData0 = &aMem[u.ao.nField];
54551  u.ao.nField = pOp->p2;
54552  u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
54553  u.ao.file_format = p->minWriteFileFormat;
54554
54555  /* Loop through the elements that will make up the record to figure
54556  ** out how much space is required for the new record.
54557  */
54558  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
54559    if( u.ao.zAffinity ){
54560      applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
54561    }
54562    if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
54563      sqlite3VdbeMemExpandBlob(u.ao.pRec);
54564    }
54565    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
54566    u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
54567    u.ao.nData += u.ao.len;
54568    u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
54569    if( u.ao.pRec->flags & MEM_Zero ){
54570      /* Only pure zero-filled BLOBs can be input to this Opcode.
54571      ** We do not allow blobs with a prefix and a zero-filled tail. */
54572      u.ao.nZero += u.ao.pRec->u.nZero;
54573    }else if( u.ao.len ){
54574      u.ao.nZero = 0;
54575    }
54576  }
54577
54578  /* Add the initial header varint and total the size */
54579  u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
54580  if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
54581    u.ao.nHdr++;
54582  }
54583  u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
54584  if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
54585    goto too_big;
54586  }
54587
54588  /* Make sure the output register has a buffer large enough to store
54589  ** the new record. The output register (pOp->p3) is not allowed to
54590  ** be one of the input registers (because the following call to
54591  ** sqlite3VdbeMemGrow() could clobber the value before it is used).
54592  */
54593  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
54594  pOut = &aMem[pOp->p3];
54595  if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
54596    goto no_mem;
54597  }
54598  u.ao.zNewRecord = (u8 *)pOut->z;
54599
54600  /* Write the record */
54601  u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
54602  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
54603    u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
54604    u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
54605  }
54606  for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
54607    u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
54608  }
54609  assert( u.ao.i==u.ao.nByte );
54610
54611  assert( pOp->p3>0 && pOp->p3<=p->nMem );
54612  pOut->n = (int)u.ao.nByte;
54613  pOut->flags = MEM_Blob | MEM_Dyn;
54614  pOut->xDel = 0;
54615  if( u.ao.nZero ){
54616    pOut->u.nZero = u.ao.nZero;
54617    pOut->flags |= MEM_Zero;
54618  }
54619  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
54620  REGISTER_TRACE(pOp->p3, pOut);
54621  UPDATE_MAX_BLOBSIZE(pOut);
54622  break;
54623}
54624
54625/* Opcode: Count P1 P2 * * *
54626**
54627** Store the number of entries (an integer value) in the table or index
54628** opened by cursor P1 in register P2
54629*/
54630#ifndef SQLITE_OMIT_BTREECOUNT
54631case OP_Count: {         /* out2-prerelease */
54632#if 0  /* local variables moved into u.ap */
54633  i64 nEntry;
54634  BtCursor *pCrsr;
54635#endif /* local variables moved into u.ap */
54636
54637  u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
54638  if( u.ap.pCrsr ){
54639    rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
54640  }else{
54641    u.ap.nEntry = 0;
54642  }
54643  pOut->u.i = u.ap.nEntry;
54644  break;
54645}
54646#endif
54647
54648/* Opcode: Savepoint P1 * * P4 *
54649**
54650** Open, release or rollback the savepoint named by parameter P4, depending
54651** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
54652** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
54653*/
54654case OP_Savepoint: {
54655#if 0  /* local variables moved into u.aq */
54656  int p1;                         /* Value of P1 operand */
54657  char *zName;                    /* Name of savepoint */
54658  int nName;
54659  Savepoint *pNew;
54660  Savepoint *pSavepoint;
54661  Savepoint *pTmp;
54662  int iSavepoint;
54663  int ii;
54664#endif /* local variables moved into u.aq */
54665
54666  u.aq.p1 = pOp->p1;
54667  u.aq.zName = pOp->p4.z;
54668
54669  /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
54670  ** transaction, then there cannot be any savepoints.
54671  */
54672  assert( db->pSavepoint==0 || db->autoCommit==0 );
54673  assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
54674  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
54675  assert( checkSavepointCount(db) );
54676
54677  if( u.aq.p1==SAVEPOINT_BEGIN ){
54678    if( db->writeVdbeCnt>0 ){
54679      /* A new savepoint cannot be created if there are active write
54680      ** statements (i.e. open read/write incremental blob handles).
54681      */
54682      sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
54683        "SQL statements in progress");
54684      rc = SQLITE_BUSY;
54685    }else{
54686      u.aq.nName = sqlite3Strlen30(u.aq.zName);
54687
54688      /* Create a new savepoint structure. */
54689      u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
54690      if( u.aq.pNew ){
54691        u.aq.pNew->zName = (char *)&u.aq.pNew[1];
54692        memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
54693
54694        /* If there is no open transaction, then mark this as a special
54695        ** "transaction savepoint". */
54696        if( db->autoCommit ){
54697          db->autoCommit = 0;
54698          db->isTransactionSavepoint = 1;
54699        }else{
54700          db->nSavepoint++;
54701        }
54702
54703        /* Link the new savepoint into the database handle's list. */
54704        u.aq.pNew->pNext = db->pSavepoint;
54705        db->pSavepoint = u.aq.pNew;
54706        u.aq.pNew->nDeferredCons = db->nDeferredCons;
54707      }
54708    }
54709  }else{
54710    u.aq.iSavepoint = 0;
54711
54712    /* Find the named savepoint. If there is no such savepoint, then an
54713    ** an error is returned to the user.  */
54714    for(
54715      u.aq.pSavepoint = db->pSavepoint;
54716      u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
54717      u.aq.pSavepoint = u.aq.pSavepoint->pNext
54718    ){
54719      u.aq.iSavepoint++;
54720    }
54721    if( !u.aq.pSavepoint ){
54722      sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
54723      rc = SQLITE_ERROR;
54724    }else if(
54725        db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
54726    ){
54727      /* It is not possible to release (commit) a savepoint if there are
54728      ** active write statements. It is not possible to rollback a savepoint
54729      ** if there are any active statements at all.
54730      */
54731      sqlite3SetString(&p->zErrMsg, db,
54732        "cannot %s savepoint - SQL statements in progress",
54733        (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
54734      );
54735      rc = SQLITE_BUSY;
54736    }else{
54737
54738      /* Determine whether or not this is a transaction savepoint. If so,
54739      ** and this is a RELEASE command, then the current transaction
54740      ** is committed.
54741      */
54742      int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
54743      if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
54744        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
54745          goto vdbe_return;
54746        }
54747        db->autoCommit = 1;
54748        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
54749          p->pc = pc;
54750          db->autoCommit = 0;
54751          p->rc = rc = SQLITE_BUSY;
54752          goto vdbe_return;
54753        }
54754        db->isTransactionSavepoint = 0;
54755        rc = p->rc;
54756      }else{
54757        u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
54758        for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
54759          rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
54760          if( rc!=SQLITE_OK ){
54761            goto abort_due_to_error;
54762          }
54763        }
54764        if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
54765          sqlite3ExpirePreparedStatements(db);
54766          sqlite3ResetInternalSchema(db, 0);
54767        }
54768      }
54769
54770      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
54771      ** savepoints nested inside of the savepoint being operated on. */
54772      while( db->pSavepoint!=u.aq.pSavepoint ){
54773        u.aq.pTmp = db->pSavepoint;
54774        db->pSavepoint = u.aq.pTmp->pNext;
54775        sqlite3DbFree(db, u.aq.pTmp);
54776        db->nSavepoint--;
54777      }
54778
54779      /* If it is a RELEASE, then destroy the savepoint being operated on
54780      ** too. If it is a ROLLBACK TO, then set the number of deferred
54781      ** constraint violations present in the database to the value stored
54782      ** when the savepoint was created.  */
54783      if( u.aq.p1==SAVEPOINT_RELEASE ){
54784        assert( u.aq.pSavepoint==db->pSavepoint );
54785        db->pSavepoint = u.aq.pSavepoint->pNext;
54786        sqlite3DbFree(db, u.aq.pSavepoint);
54787        if( !isTransaction ){
54788          db->nSavepoint--;
54789        }
54790      }else{
54791        db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
54792      }
54793    }
54794  }
54795
54796  break;
54797}
54798
54799/* Opcode: AutoCommit P1 P2 * * *
54800**
54801** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
54802** back any currently active btree transactions. If there are any active
54803** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
54804** there are active writing VMs or active VMs that use shared cache.
54805**
54806** This instruction causes the VM to halt.
54807*/
54808case OP_AutoCommit: {
54809#if 0  /* local variables moved into u.ar */
54810  int desiredAutoCommit;
54811  int iRollback;
54812  int turnOnAC;
54813#endif /* local variables moved into u.ar */
54814
54815  u.ar.desiredAutoCommit = pOp->p1;
54816  u.ar.iRollback = pOp->p2;
54817  u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
54818  assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
54819  assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
54820  assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
54821
54822  if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
54823    /* If this instruction implements a ROLLBACK and other VMs are
54824    ** still running, and a transaction is active, return an error indicating
54825    ** that the other VMs must complete first.
54826    */
54827    sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
54828        "SQL statements in progress");
54829    rc = SQLITE_BUSY;
54830  }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
54831    /* If this instruction implements a COMMIT and other VMs are writing
54832    ** return an error indicating that the other VMs must complete first.
54833    */
54834    sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
54835        "SQL statements in progress");
54836    rc = SQLITE_BUSY;
54837  }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
54838    if( u.ar.iRollback ){
54839      assert( u.ar.desiredAutoCommit==1 );
54840      sqlite3RollbackAll(db);
54841      db->autoCommit = 1;
54842    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
54843      goto vdbe_return;
54844    }else{
54845      db->autoCommit = (u8)u.ar.desiredAutoCommit;
54846      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
54847        p->pc = pc;
54848        db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
54849        p->rc = rc = SQLITE_BUSY;
54850        goto vdbe_return;
54851      }
54852    }
54853    assert( db->nStatement==0 );
54854    sqlite3CloseSavepoints(db);
54855    if( p->rc==SQLITE_OK ){
54856      rc = SQLITE_DONE;
54857    }else{
54858      rc = SQLITE_ERROR;
54859    }
54860    goto vdbe_return;
54861  }else{
54862    sqlite3SetString(&p->zErrMsg, db,
54863        (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
54864        (u.ar.iRollback)?"cannot rollback - no transaction is active":
54865                   "cannot commit - no transaction is active"));
54866
54867    rc = SQLITE_ERROR;
54868  }
54869  break;
54870}
54871
54872/* Opcode: Transaction P1 P2 * * *
54873**
54874** Begin a transaction.  The transaction ends when a Commit or Rollback
54875** opcode is encountered.  Depending on the ON CONFLICT setting, the
54876** transaction might also be rolled back if an error is encountered.
54877**
54878** P1 is the index of the database file on which the transaction is
54879** started.  Index 0 is the main database file and index 1 is the
54880** file used for temporary tables.  Indices of 2 or more are used for
54881** attached databases.
54882**
54883** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
54884** obtained on the database file when a write-transaction is started.  No
54885** other process can start another write transaction while this transaction is
54886** underway.  Starting a write transaction also creates a rollback journal. A
54887** write transaction must be started before any changes can be made to the
54888** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
54889** on the file.
54890**
54891** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
54892** true (this flag is set if the Vdbe may modify more than one row and may
54893** throw an ABORT exception), a statement transaction may also be opened.
54894** More specifically, a statement transaction is opened iff the database
54895** connection is currently not in autocommit mode, or if there are other
54896** active statements. A statement transaction allows the affects of this
54897** VDBE to be rolled back after an error without having to roll back the
54898** entire transaction. If no error is encountered, the statement transaction
54899** will automatically commit when the VDBE halts.
54900**
54901** If P2 is zero, then a read-lock is obtained on the database file.
54902*/
54903case OP_Transaction: {
54904#if 0  /* local variables moved into u.as */
54905  Btree *pBt;
54906#endif /* local variables moved into u.as */
54907
54908  assert( pOp->p1>=0 && pOp->p1<db->nDb );
54909  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
54910  u.as.pBt = db->aDb[pOp->p1].pBt;
54911
54912  if( u.as.pBt ){
54913    rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
54914    if( rc==SQLITE_BUSY ){
54915      p->pc = pc;
54916      p->rc = rc = SQLITE_BUSY;
54917      goto vdbe_return;
54918    }
54919    if( rc!=SQLITE_OK ){
54920      goto abort_due_to_error;
54921    }
54922
54923    if( pOp->p2 && p->usesStmtJournal
54924     && (db->autoCommit==0 || db->activeVdbeCnt>1)
54925    ){
54926      assert( sqlite3BtreeIsInTrans(u.as.pBt) );
54927      if( p->iStatement==0 ){
54928        assert( db->nStatement>=0 && db->nSavepoint>=0 );
54929        db->nStatement++;
54930        p->iStatement = db->nSavepoint + db->nStatement;
54931      }
54932      rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
54933
54934      /* Store the current value of the database handles deferred constraint
54935      ** counter. If the statement transaction needs to be rolled back,
54936      ** the value of this counter needs to be restored too.  */
54937      p->nStmtDefCons = db->nDeferredCons;
54938    }
54939  }
54940  break;
54941}
54942
54943/* Opcode: ReadCookie P1 P2 P3 * *
54944**
54945** Read cookie number P3 from database P1 and write it into register P2.
54946** P3==1 is the schema version.  P3==2 is the database format.
54947** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
54948** the main database file and P1==1 is the database file used to store
54949** temporary tables.
54950**
54951** There must be a read-lock on the database (either a transaction
54952** must be started or there must be an open cursor) before
54953** executing this instruction.
54954*/
54955case OP_ReadCookie: {               /* out2-prerelease */
54956#if 0  /* local variables moved into u.at */
54957  int iMeta;
54958  int iDb;
54959  int iCookie;
54960#endif /* local variables moved into u.at */
54961
54962  u.at.iDb = pOp->p1;
54963  u.at.iCookie = pOp->p3;
54964  assert( pOp->p3<SQLITE_N_BTREE_META );
54965  assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
54966  assert( db->aDb[u.at.iDb].pBt!=0 );
54967  assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
54968
54969  sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
54970  pOut->u.i = u.at.iMeta;
54971  break;
54972}
54973
54974/* Opcode: SetCookie P1 P2 P3 * *
54975**
54976** Write the content of register P3 (interpreted as an integer)
54977** into cookie number P2 of database P1.  P2==1 is the schema version.
54978** P2==2 is the database format. P2==3 is the recommended pager cache
54979** size, and so forth.  P1==0 is the main database file and P1==1 is the
54980** database file used to store temporary tables.
54981**
54982** A transaction must be started before executing this opcode.
54983*/
54984case OP_SetCookie: {       /* in3 */
54985#if 0  /* local variables moved into u.au */
54986  Db *pDb;
54987#endif /* local variables moved into u.au */
54988  assert( pOp->p2<SQLITE_N_BTREE_META );
54989  assert( pOp->p1>=0 && pOp->p1<db->nDb );
54990  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
54991  u.au.pDb = &db->aDb[pOp->p1];
54992  assert( u.au.pDb->pBt!=0 );
54993  pIn3 = &aMem[pOp->p3];
54994  sqlite3VdbeMemIntegerify(pIn3);
54995  /* See note about index shifting on OP_ReadCookie */
54996  rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
54997  if( pOp->p2==BTREE_SCHEMA_VERSION ){
54998    /* When the schema cookie changes, record the new cookie internally */
54999    u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
55000    db->flags |= SQLITE_InternChanges;
55001  }else if( pOp->p2==BTREE_FILE_FORMAT ){
55002    /* Record changes in the file format */
55003    u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
55004  }
55005  if( pOp->p1==1 ){
55006    /* Invalidate all prepared statements whenever the TEMP database
55007    ** schema is changed.  Ticket #1644 */
55008    sqlite3ExpirePreparedStatements(db);
55009    p->expired = 0;
55010  }
55011  break;
55012}
55013
55014/* Opcode: VerifyCookie P1 P2 *
55015**
55016** Check the value of global database parameter number 0 (the
55017** schema version) and make sure it is equal to P2.
55018** P1 is the database number which is 0 for the main database file
55019** and 1 for the file holding temporary tables and some higher number
55020** for auxiliary databases.
55021**
55022** The cookie changes its value whenever the database schema changes.
55023** This operation is used to detect when that the cookie has changed
55024** and that the current process needs to reread the schema.
55025**
55026** Either a transaction needs to have been started or an OP_Open needs
55027** to be executed (to establish a read lock) before this opcode is
55028** invoked.
55029*/
55030case OP_VerifyCookie: {
55031#if 0  /* local variables moved into u.av */
55032  int iMeta;
55033  Btree *pBt;
55034#endif /* local variables moved into u.av */
55035  assert( pOp->p1>=0 && pOp->p1<db->nDb );
55036  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
55037  u.av.pBt = db->aDb[pOp->p1].pBt;
55038  if( u.av.pBt ){
55039    sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
55040  }else{
55041    u.av.iMeta = 0;
55042  }
55043  if( u.av.iMeta!=pOp->p2 ){
55044    sqlite3DbFree(db, p->zErrMsg);
55045    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
55046    /* If the schema-cookie from the database file matches the cookie
55047    ** stored with the in-memory representation of the schema, do
55048    ** not reload the schema from the database file.
55049    **
55050    ** If virtual-tables are in use, this is not just an optimization.
55051    ** Often, v-tables store their data in other SQLite tables, which
55052    ** are queried from within xNext() and other v-table methods using
55053    ** prepared queries. If such a query is out-of-date, we do not want to
55054    ** discard the database schema, as the user code implementing the
55055    ** v-table would have to be ready for the sqlite3_vtab structure itself
55056    ** to be invalidated whenever sqlite3_step() is called from within
55057    ** a v-table method.
55058    */
55059    if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
55060      sqlite3ResetInternalSchema(db, pOp->p1);
55061    }
55062
55063    sqlite3ExpirePreparedStatements(db);
55064    rc = SQLITE_SCHEMA;
55065  }
55066  break;
55067}
55068
55069/* Opcode: OpenRead P1 P2 P3 P4 P5
55070**
55071** Open a read-only cursor for the database table whose root page is
55072** P2 in a database file.  The database file is determined by P3.
55073** P3==0 means the main database, P3==1 means the database used for
55074** temporary tables, and P3>1 means used the corresponding attached
55075** database.  Give the new cursor an identifier of P1.  The P1
55076** values need not be contiguous but all P1 values should be small integers.
55077** It is an error for P1 to be negative.
55078**
55079** If P5!=0 then use the content of register P2 as the root page, not
55080** the value of P2 itself.
55081**
55082** There will be a read lock on the database whenever there is an
55083** open cursor.  If the database was unlocked prior to this instruction
55084** then a read lock is acquired as part of this instruction.  A read
55085** lock allows other processes to read the database but prohibits
55086** any other process from modifying the database.  The read lock is
55087** released when all cursors are closed.  If this instruction attempts
55088** to get a read lock but fails, the script terminates with an
55089** SQLITE_BUSY error code.
55090**
55091** The P4 value may be either an integer (P4_INT32) or a pointer to
55092** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
55093** structure, then said structure defines the content and collating
55094** sequence of the index being opened. Otherwise, if P4 is an integer
55095** value, it is set to the number of columns in the table.
55096**
55097** See also OpenWrite.
55098*/
55099/* Opcode: OpenWrite P1 P2 P3 P4 P5
55100**
55101** Open a read/write cursor named P1 on the table or index whose root
55102** page is P2.  Or if P5!=0 use the content of register P2 to find the
55103** root page.
55104**
55105** The P4 value may be either an integer (P4_INT32) or a pointer to
55106** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
55107** structure, then said structure defines the content and collating
55108** sequence of the index being opened. Otherwise, if P4 is an integer
55109** value, it is set to the number of columns in the table, or to the
55110** largest index of any column of the table that is actually used.
55111**
55112** This instruction works just like OpenRead except that it opens the cursor
55113** in read/write mode.  For a given table, there can be one or more read-only
55114** cursors or a single read/write cursor but not both.
55115**
55116** See also OpenRead.
55117*/
55118case OP_OpenRead:
55119case OP_OpenWrite: {
55120#if 0  /* local variables moved into u.aw */
55121  int nField;
55122  KeyInfo *pKeyInfo;
55123  int p2;
55124  int iDb;
55125  int wrFlag;
55126  Btree *pX;
55127  VdbeCursor *pCur;
55128  Db *pDb;
55129#endif /* local variables moved into u.aw */
55130
55131  if( p->expired ){
55132    rc = SQLITE_ABORT;
55133    break;
55134  }
55135
55136  u.aw.nField = 0;
55137  u.aw.pKeyInfo = 0;
55138  u.aw.p2 = pOp->p2;
55139  u.aw.iDb = pOp->p3;
55140  assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
55141  assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
55142  u.aw.pDb = &db->aDb[u.aw.iDb];
55143  u.aw.pX = u.aw.pDb->pBt;
55144  assert( u.aw.pX!=0 );
55145  if( pOp->opcode==OP_OpenWrite ){
55146    u.aw.wrFlag = 1;
55147    if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
55148      p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
55149    }
55150  }else{
55151    u.aw.wrFlag = 0;
55152  }
55153  if( pOp->p5 ){
55154    assert( u.aw.p2>0 );
55155    assert( u.aw.p2<=p->nMem );
55156    pIn2 = &aMem[u.aw.p2];
55157    sqlite3VdbeMemIntegerify(pIn2);
55158    u.aw.p2 = (int)pIn2->u.i;
55159    /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
55160    ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
55161    ** If there were a failure, the prepared statement would have halted
55162    ** before reaching this instruction. */
55163    if( NEVER(u.aw.p2<2) ) {
55164      rc = SQLITE_CORRUPT_BKPT;
55165      goto abort_due_to_error;
55166    }
55167  }
55168  if( pOp->p4type==P4_KEYINFO ){
55169    u.aw.pKeyInfo = pOp->p4.pKeyInfo;
55170    u.aw.pKeyInfo->enc = ENC(p->db);
55171    u.aw.nField = u.aw.pKeyInfo->nField+1;
55172  }else if( pOp->p4type==P4_INT32 ){
55173    u.aw.nField = pOp->p4.i;
55174  }
55175  assert( pOp->p1>=0 );
55176  u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
55177  if( u.aw.pCur==0 ) goto no_mem;
55178  u.aw.pCur->nullRow = 1;
55179  rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
55180  u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
55181
55182  /* Since it performs no memory allocation or IO, the only values that
55183  ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
55184  ** SQLITE_EMPTY is only returned when attempting to open the table
55185  ** rooted at page 1 of a zero-byte database.  */
55186  assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
55187  if( rc==SQLITE_EMPTY ){
55188    u.aw.pCur->pCursor = 0;
55189    rc = SQLITE_OK;
55190  }
55191
55192  /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
55193  ** SQLite used to check if the root-page flags were sane at this point
55194  ** and report database corruption if they were not, but this check has
55195  ** since moved into the btree layer.  */
55196  u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
55197  u.aw.pCur->isIndex = !u.aw.pCur->isTable;
55198  break;
55199}
55200
55201/* Opcode: OpenEphemeral P1 P2 * P4 *
55202**
55203** Open a new cursor P1 to a transient table.
55204** The cursor is always opened read/write even if
55205** the main database is read-only.  The transient or virtual
55206** table is deleted automatically when the cursor is closed.
55207**
55208** P2 is the number of columns in the virtual table.
55209** The cursor points to a BTree table if P4==0 and to a BTree index
55210** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
55211** that defines the format of keys in the index.
55212**
55213** This opcode was once called OpenTemp.  But that created
55214** confusion because the term "temp table", might refer either
55215** to a TEMP table at the SQL level, or to a table opened by
55216** this opcode.  Then this opcode was call OpenVirtual.  But
55217** that created confusion with the whole virtual-table idea.
55218*/
55219case OP_OpenEphemeral: {
55220#if 0  /* local variables moved into u.ax */
55221  VdbeCursor *pCx;
55222#endif /* local variables moved into u.ax */
55223  static const int openFlags =
55224      SQLITE_OPEN_READWRITE |
55225      SQLITE_OPEN_CREATE |
55226      SQLITE_OPEN_EXCLUSIVE |
55227      SQLITE_OPEN_DELETEONCLOSE |
55228      SQLITE_OPEN_TRANSIENT_DB;
55229
55230  assert( pOp->p1>=0 );
55231  u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
55232  if( u.ax.pCx==0 ) goto no_mem;
55233  u.ax.pCx->nullRow = 1;
55234  rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
55235                           &u.ax.pCx->pBt);
55236  if( rc==SQLITE_OK ){
55237    rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
55238  }
55239  if( rc==SQLITE_OK ){
55240    /* If a transient index is required, create it by calling
55241    ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
55242    ** opening it. If a transient table is required, just use the
55243    ** automatically created table with root-page 1 (an INTKEY table).
55244    */
55245    if( pOp->p4.pKeyInfo ){
55246      int pgno;
55247      assert( pOp->p4type==P4_KEYINFO );
55248      rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_ZERODATA);
55249      if( rc==SQLITE_OK ){
55250        assert( pgno==MASTER_ROOT+1 );
55251        rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
55252                                (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
55253        u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
55254        u.ax.pCx->pKeyInfo->enc = ENC(p->db);
55255      }
55256      u.ax.pCx->isTable = 0;
55257    }else{
55258      rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
55259      u.ax.pCx->isTable = 1;
55260    }
55261  }
55262  u.ax.pCx->isIndex = !u.ax.pCx->isTable;
55263  break;
55264}
55265
55266/* Opcode: OpenPseudo P1 P2 P3 * *
55267**
55268** Open a new cursor that points to a fake table that contains a single
55269** row of data.  The content of that one row in the content of memory
55270** register P2.  In other words, cursor P1 becomes an alias for the
55271** MEM_Blob content contained in register P2.
55272**
55273** A pseudo-table created by this opcode is used to hold the a single
55274** row output from the sorter so that the row can be decomposed into
55275** individual columns using the OP_Column opcode.  The OP_Column opcode
55276** is the only cursor opcode that works with a pseudo-table.
55277**
55278** P3 is the number of fields in the records that will be stored by
55279** the pseudo-table.
55280*/
55281case OP_OpenPseudo: {
55282#if 0  /* local variables moved into u.ay */
55283  VdbeCursor *pCx;
55284#endif /* local variables moved into u.ay */
55285
55286  assert( pOp->p1>=0 );
55287  u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
55288  if( u.ay.pCx==0 ) goto no_mem;
55289  u.ay.pCx->nullRow = 1;
55290  u.ay.pCx->pseudoTableReg = pOp->p2;
55291  u.ay.pCx->isTable = 1;
55292  u.ay.pCx->isIndex = 0;
55293  break;
55294}
55295
55296/* Opcode: Close P1 * * * *
55297**
55298** Close a cursor previously opened as P1.  If P1 is not
55299** currently open, this instruction is a no-op.
55300*/
55301case OP_Close: {
55302  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55303  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
55304  p->apCsr[pOp->p1] = 0;
55305  break;
55306}
55307
55308/* Opcode: SeekGe P1 P2 P3 P4 *
55309**
55310** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55311** use the value in register P3 as the key.  If cursor P1 refers
55312** to an SQL index, then P3 is the first in an array of P4 registers
55313** that are used as an unpacked index key.
55314**
55315** Reposition cursor P1 so that  it points to the smallest entry that
55316** is greater than or equal to the key value. If there are no records
55317** greater than or equal to the key and P2 is not zero, then jump to P2.
55318**
55319** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
55320*/
55321/* Opcode: SeekGt P1 P2 P3 P4 *
55322**
55323** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55324** use the value in register P3 as a key. If cursor P1 refers
55325** to an SQL index, then P3 is the first in an array of P4 registers
55326** that are used as an unpacked index key.
55327**
55328** Reposition cursor P1 so that  it points to the smallest entry that
55329** is greater than the key value. If there are no records greater than
55330** the key and P2 is not zero, then jump to P2.
55331**
55332** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
55333*/
55334/* Opcode: SeekLt P1 P2 P3 P4 *
55335**
55336** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55337** use the value in register P3 as a key. If cursor P1 refers
55338** to an SQL index, then P3 is the first in an array of P4 registers
55339** that are used as an unpacked index key.
55340**
55341** Reposition cursor P1 so that  it points to the largest entry that
55342** is less than the key value. If there are no records less than
55343** the key and P2 is not zero, then jump to P2.
55344**
55345** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
55346*/
55347/* Opcode: SeekLe P1 P2 P3 P4 *
55348**
55349** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
55350** use the value in register P3 as a key. If cursor P1 refers
55351** to an SQL index, then P3 is the first in an array of P4 registers
55352** that are used as an unpacked index key.
55353**
55354** Reposition cursor P1 so that it points to the largest entry that
55355** is less than or equal to the key value. If there are no records
55356** less than or equal to the key and P2 is not zero, then jump to P2.
55357**
55358** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
55359*/
55360case OP_SeekLt:         /* jump, in3 */
55361case OP_SeekLe:         /* jump, in3 */
55362case OP_SeekGe:         /* jump, in3 */
55363case OP_SeekGt: {       /* jump, in3 */
55364#if 0  /* local variables moved into u.az */
55365  int res;
55366  int oc;
55367  VdbeCursor *pC;
55368  UnpackedRecord r;
55369  int nField;
55370  i64 iKey;      /* The rowid we are to seek to */
55371#endif /* local variables moved into u.az */
55372
55373  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55374  assert( pOp->p2!=0 );
55375  u.az.pC = p->apCsr[pOp->p1];
55376  assert( u.az.pC!=0 );
55377  assert( u.az.pC->pseudoTableReg==0 );
55378  assert( OP_SeekLe == OP_SeekLt+1 );
55379  assert( OP_SeekGe == OP_SeekLt+2 );
55380  assert( OP_SeekGt == OP_SeekLt+3 );
55381  if( u.az.pC->pCursor!=0 ){
55382    u.az.oc = pOp->opcode;
55383    u.az.pC->nullRow = 0;
55384    if( u.az.pC->isTable ){
55385      /* The input value in P3 might be of any type: integer, real, string,
55386      ** blob, or NULL.  But it needs to be an integer before we can do
55387      ** the seek, so covert it. */
55388      pIn3 = &aMem[pOp->p3];
55389      applyNumericAffinity(pIn3);
55390      u.az.iKey = sqlite3VdbeIntValue(pIn3);
55391      u.az.pC->rowidIsValid = 0;
55392
55393      /* If the P3 value could not be converted into an integer without
55394      ** loss of information, then special processing is required... */
55395      if( (pIn3->flags & MEM_Int)==0 ){
55396        if( (pIn3->flags & MEM_Real)==0 ){
55397          /* If the P3 value cannot be converted into any kind of a number,
55398          ** then the seek is not possible, so jump to P2 */
55399          pc = pOp->p2 - 1;
55400          break;
55401        }
55402        /* If we reach this point, then the P3 value must be a floating
55403        ** point number. */
55404        assert( (pIn3->flags & MEM_Real)!=0 );
55405
55406        if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
55407          /* The P3 value is too large in magnitude to be expressed as an
55408          ** integer. */
55409          u.az.res = 1;
55410          if( pIn3->r<0 ){
55411            if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
55412              rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
55413              if( rc!=SQLITE_OK ) goto abort_due_to_error;
55414            }
55415          }else{
55416            if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
55417              rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
55418              if( rc!=SQLITE_OK ) goto abort_due_to_error;
55419            }
55420          }
55421          if( u.az.res ){
55422            pc = pOp->p2 - 1;
55423          }
55424          break;
55425        }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
55426          /* Use the ceiling() function to convert real->int */
55427          if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
55428        }else{
55429          /* Use the floor() function to convert real->int */
55430          assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
55431          if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
55432        }
55433      }
55434      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
55435      if( rc!=SQLITE_OK ){
55436        goto abort_due_to_error;
55437      }
55438      if( u.az.res==0 ){
55439        u.az.pC->rowidIsValid = 1;
55440        u.az.pC->lastRowid = u.az.iKey;
55441      }
55442    }else{
55443      u.az.nField = pOp->p4.i;
55444      assert( pOp->p4type==P4_INT32 );
55445      assert( u.az.nField>0 );
55446      u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
55447      u.az.r.nField = (u16)u.az.nField;
55448
55449      /* The next line of code computes as follows, only faster:
55450      **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
55451      **     u.az.r.flags = UNPACKED_INCRKEY;
55452      **   }else{
55453      **     u.az.r.flags = 0;
55454      **   }
55455      */
55456      u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
55457      assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
55458      assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
55459      assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
55460      assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
55461
55462      u.az.r.aMem = &aMem[pOp->p3];
55463      ExpandBlob(u.az.r.aMem);
55464      rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
55465      if( rc!=SQLITE_OK ){
55466        goto abort_due_to_error;
55467      }
55468      u.az.pC->rowidIsValid = 0;
55469    }
55470    u.az.pC->deferredMoveto = 0;
55471    u.az.pC->cacheStatus = CACHE_STALE;
55472#ifdef SQLITE_TEST
55473    sqlite3_search_count++;
55474#endif
55475    if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
55476      if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
55477        rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
55478        if( rc!=SQLITE_OK ) goto abort_due_to_error;
55479        u.az.pC->rowidIsValid = 0;
55480      }else{
55481        u.az.res = 0;
55482      }
55483    }else{
55484      assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
55485      if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
55486        rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
55487        if( rc!=SQLITE_OK ) goto abort_due_to_error;
55488        u.az.pC->rowidIsValid = 0;
55489      }else{
55490        /* u.az.res might be negative because the table is empty.  Check to
55491        ** see if this is the case.
55492        */
55493        u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
55494      }
55495    }
55496    assert( pOp->p2>0 );
55497    if( u.az.res ){
55498      pc = pOp->p2 - 1;
55499    }
55500  }else{
55501    /* This happens when attempting to open the sqlite3_master table
55502    ** for read access returns SQLITE_EMPTY. In this case always
55503    ** take the jump (since there are no records in the table).
55504    */
55505    pc = pOp->p2 - 1;
55506  }
55507  break;
55508}
55509
55510/* Opcode: Seek P1 P2 * * *
55511**
55512** P1 is an open table cursor and P2 is a rowid integer.  Arrange
55513** for P1 to move so that it points to the rowid given by P2.
55514**
55515** This is actually a deferred seek.  Nothing actually happens until
55516** the cursor is used to read a record.  That way, if no reads
55517** occur, no unnecessary I/O happens.
55518*/
55519case OP_Seek: {    /* in2 */
55520#if 0  /* local variables moved into u.ba */
55521  VdbeCursor *pC;
55522#endif /* local variables moved into u.ba */
55523
55524  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55525  u.ba.pC = p->apCsr[pOp->p1];
55526  assert( u.ba.pC!=0 );
55527  if( ALWAYS(u.ba.pC->pCursor!=0) ){
55528    assert( u.ba.pC->isTable );
55529    u.ba.pC->nullRow = 0;
55530    pIn2 = &aMem[pOp->p2];
55531    u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
55532    u.ba.pC->rowidIsValid = 0;
55533    u.ba.pC->deferredMoveto = 1;
55534  }
55535  break;
55536}
55537
55538
55539/* Opcode: Found P1 P2 P3 P4 *
55540**
55541** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
55542** P4>0 then register P3 is the first of P4 registers that form an unpacked
55543** record.
55544**
55545** Cursor P1 is on an index btree.  If the record identified by P3 and P4
55546** is a prefix of any entry in P1 then a jump is made to P2 and
55547** P1 is left pointing at the matching entry.
55548*/
55549/* Opcode: NotFound P1 P2 P3 P4 *
55550**
55551** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
55552** P4>0 then register P3 is the first of P4 registers that form an unpacked
55553** record.
55554**
55555** Cursor P1 is on an index btree.  If the record identified by P3 and P4
55556** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
55557** does contain an entry whose prefix matches the P3/P4 record then control
55558** falls through to the next instruction and P1 is left pointing at the
55559** matching entry.
55560**
55561** See also: Found, NotExists, IsUnique
55562*/
55563case OP_NotFound:       /* jump, in3 */
55564case OP_Found: {        /* jump, in3 */
55565#if 0  /* local variables moved into u.bb */
55566  int alreadyExists;
55567  VdbeCursor *pC;
55568  int res;
55569  UnpackedRecord *pIdxKey;
55570  UnpackedRecord r;
55571  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
55572#endif /* local variables moved into u.bb */
55573
55574#ifdef SQLITE_TEST
55575  sqlite3_found_count++;
55576#endif
55577
55578  u.bb.alreadyExists = 0;
55579  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55580  assert( pOp->p4type==P4_INT32 );
55581  u.bb.pC = p->apCsr[pOp->p1];
55582  assert( u.bb.pC!=0 );
55583  pIn3 = &aMem[pOp->p3];
55584  if( ALWAYS(u.bb.pC->pCursor!=0) ){
55585
55586    assert( u.bb.pC->isTable==0 );
55587    if( pOp->p4.i>0 ){
55588      u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
55589      u.bb.r.nField = (u16)pOp->p4.i;
55590      u.bb.r.aMem = pIn3;
55591      u.bb.r.flags = UNPACKED_PREFIX_MATCH;
55592      u.bb.pIdxKey = &u.bb.r;
55593    }else{
55594      assert( pIn3->flags & MEM_Blob );
55595      ExpandBlob(pIn3);
55596      u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
55597                                        u.bb.aTempRec, sizeof(u.bb.aTempRec));
55598      if( u.bb.pIdxKey==0 ){
55599        goto no_mem;
55600      }
55601      u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
55602    }
55603    rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
55604    if( pOp->p4.i==0 ){
55605      sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
55606    }
55607    if( rc!=SQLITE_OK ){
55608      break;
55609    }
55610    u.bb.alreadyExists = (u.bb.res==0);
55611    u.bb.pC->deferredMoveto = 0;
55612    u.bb.pC->cacheStatus = CACHE_STALE;
55613  }
55614  if( pOp->opcode==OP_Found ){
55615    if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
55616  }else{
55617    if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
55618  }
55619  break;
55620}
55621
55622/* Opcode: IsUnique P1 P2 P3 P4 *
55623**
55624** Cursor P1 is open on an index b-tree - that is to say, a btree which
55625** no data and where the key are records generated by OP_MakeRecord with
55626** the list field being the integer ROWID of the entry that the index
55627** entry refers to.
55628**
55629** The P3 register contains an integer record number. Call this record
55630** number R. Register P4 is the first in a set of N contiguous registers
55631** that make up an unpacked index key that can be used with cursor P1.
55632** The value of N can be inferred from the cursor. N includes the rowid
55633** value appended to the end of the index record. This rowid value may
55634** or may not be the same as R.
55635**
55636** If any of the N registers beginning with register P4 contains a NULL
55637** value, jump immediately to P2.
55638**
55639** Otherwise, this instruction checks if cursor P1 contains an entry
55640** where the first (N-1) fields match but the rowid value at the end
55641** of the index entry is not R. If there is no such entry, control jumps
55642** to instruction P2. Otherwise, the rowid of the conflicting index
55643** entry is copied to register P3 and control falls through to the next
55644** instruction.
55645**
55646** See also: NotFound, NotExists, Found
55647*/
55648case OP_IsUnique: {        /* jump, in3 */
55649#if 0  /* local variables moved into u.bc */
55650  u16 ii;
55651  VdbeCursor *pCx;
55652  BtCursor *pCrsr;
55653  u16 nField;
55654  Mem *aMx;
55655  UnpackedRecord r;                  /* B-Tree index search key */
55656  i64 R;                             /* Rowid stored in register P3 */
55657#endif /* local variables moved into u.bc */
55658
55659  pIn3 = &aMem[pOp->p3];
55660  u.bc.aMx = &aMem[pOp->p4.i];
55661  /* Assert that the values of parameters P1 and P4 are in range. */
55662  assert( pOp->p4type==P4_INT32 );
55663  assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
55664  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55665
55666  /* Find the index cursor. */
55667  u.bc.pCx = p->apCsr[pOp->p1];
55668  assert( u.bc.pCx->deferredMoveto==0 );
55669  u.bc.pCx->seekResult = 0;
55670  u.bc.pCx->cacheStatus = CACHE_STALE;
55671  u.bc.pCrsr = u.bc.pCx->pCursor;
55672
55673  /* If any of the values are NULL, take the jump. */
55674  u.bc.nField = u.bc.pCx->pKeyInfo->nField;
55675  for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
55676    if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
55677      pc = pOp->p2 - 1;
55678      u.bc.pCrsr = 0;
55679      break;
55680    }
55681  }
55682  assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
55683
55684  if( u.bc.pCrsr!=0 ){
55685    /* Populate the index search key. */
55686    u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
55687    u.bc.r.nField = u.bc.nField + 1;
55688    u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
55689    u.bc.r.aMem = u.bc.aMx;
55690
55691    /* Extract the value of u.bc.R from register P3. */
55692    sqlite3VdbeMemIntegerify(pIn3);
55693    u.bc.R = pIn3->u.i;
55694
55695    /* Search the B-Tree index. If no conflicting record is found, jump
55696    ** to P2. Otherwise, copy the rowid of the conflicting record to
55697    ** register P3 and fall through to the next instruction.  */
55698    rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
55699    if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
55700      pc = pOp->p2 - 1;
55701    }else{
55702      pIn3->u.i = u.bc.r.rowid;
55703    }
55704  }
55705  break;
55706}
55707
55708/* Opcode: NotExists P1 P2 P3 * *
55709**
55710** Use the content of register P3 as a integer key.  If a record
55711** with that key does not exist in table of P1, then jump to P2.
55712** If the record does exist, then fall thru.  The cursor is left
55713** pointing to the record if it exists.
55714**
55715** The difference between this operation and NotFound is that this
55716** operation assumes the key is an integer and that P1 is a table whereas
55717** NotFound assumes key is a blob constructed from MakeRecord and
55718** P1 is an index.
55719**
55720** See also: Found, NotFound, IsUnique
55721*/
55722case OP_NotExists: {        /* jump, in3 */
55723#if 0  /* local variables moved into u.bd */
55724  VdbeCursor *pC;
55725  BtCursor *pCrsr;
55726  int res;
55727  u64 iKey;
55728#endif /* local variables moved into u.bd */
55729
55730  pIn3 = &aMem[pOp->p3];
55731  assert( pIn3->flags & MEM_Int );
55732  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55733  u.bd.pC = p->apCsr[pOp->p1];
55734  assert( u.bd.pC!=0 );
55735  assert( u.bd.pC->isTable );
55736  assert( u.bd.pC->pseudoTableReg==0 );
55737  u.bd.pCrsr = u.bd.pC->pCursor;
55738  if( u.bd.pCrsr!=0 ){
55739    u.bd.res = 0;
55740    u.bd.iKey = pIn3->u.i;
55741    rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
55742    u.bd.pC->lastRowid = pIn3->u.i;
55743    u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
55744    u.bd.pC->nullRow = 0;
55745    u.bd.pC->cacheStatus = CACHE_STALE;
55746    u.bd.pC->deferredMoveto = 0;
55747    if( u.bd.res!=0 ){
55748      pc = pOp->p2 - 1;
55749      assert( u.bd.pC->rowidIsValid==0 );
55750    }
55751    u.bd.pC->seekResult = u.bd.res;
55752  }else{
55753    /* This happens when an attempt to open a read cursor on the
55754    ** sqlite_master table returns SQLITE_EMPTY.
55755    */
55756    pc = pOp->p2 - 1;
55757    assert( u.bd.pC->rowidIsValid==0 );
55758    u.bd.pC->seekResult = 0;
55759  }
55760  break;
55761}
55762
55763/* Opcode: Sequence P1 P2 * * *
55764**
55765** Find the next available sequence number for cursor P1.
55766** Write the sequence number into register P2.
55767** The sequence number on the cursor is incremented after this
55768** instruction.
55769*/
55770case OP_Sequence: {           /* out2-prerelease */
55771  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55772  assert( p->apCsr[pOp->p1]!=0 );
55773  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
55774  break;
55775}
55776
55777
55778/* Opcode: NewRowid P1 P2 P3 * *
55779**
55780** Get a new integer record number (a.k.a "rowid") used as the key to a table.
55781** The record number is not previously used as a key in the database
55782** table that cursor P1 points to.  The new record number is written
55783** written to register P2.
55784**
55785** If P3>0 then P3 is a register in the root frame of this VDBE that holds
55786** the largest previously generated record number. No new record numbers are
55787** allowed to be less than this value. When this value reaches its maximum,
55788** a SQLITE_FULL error is generated. The P3 register is updated with the '
55789** generated record number. This P3 mechanism is used to help implement the
55790** AUTOINCREMENT feature.
55791*/
55792case OP_NewRowid: {           /* out2-prerelease */
55793#if 0  /* local variables moved into u.be */
55794  i64 v;                 /* The new rowid */
55795  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
55796  int res;               /* Result of an sqlite3BtreeLast() */
55797  int cnt;               /* Counter to limit the number of searches */
55798  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
55799  VdbeFrame *pFrame;     /* Root frame of VDBE */
55800#endif /* local variables moved into u.be */
55801
55802  u.be.v = 0;
55803  u.be.res = 0;
55804  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55805  u.be.pC = p->apCsr[pOp->p1];
55806  assert( u.be.pC!=0 );
55807  if( NEVER(u.be.pC->pCursor==0) ){
55808    /* The zero initialization above is all that is needed */
55809  }else{
55810    /* The next rowid or record number (different terms for the same
55811    ** thing) is obtained in a two-step algorithm.
55812    **
55813    ** First we attempt to find the largest existing rowid and add one
55814    ** to that.  But if the largest existing rowid is already the maximum
55815    ** positive integer, we have to fall through to the second
55816    ** probabilistic algorithm
55817    **
55818    ** The second algorithm is to select a rowid at random and see if
55819    ** it already exists in the table.  If it does not exist, we have
55820    ** succeeded.  If the random rowid does exist, we select a new one
55821    ** and try again, up to 100 times.
55822    */
55823    assert( u.be.pC->isTable );
55824    u.be.cnt = 0;
55825
55826#ifdef SQLITE_32BIT_ROWID
55827#   define MAX_ROWID 0x7fffffff
55828#else
55829    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
55830    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
55831    ** to provide the constant while making all compilers happy.
55832    */
55833#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
55834#endif
55835
55836    if( !u.be.pC->useRandomRowid ){
55837      u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
55838      if( u.be.v==0 ){
55839        rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
55840        if( rc!=SQLITE_OK ){
55841          goto abort_due_to_error;
55842        }
55843        if( u.be.res ){
55844          u.be.v = 1;   /* IMP: R-61914-48074 */
55845        }else{
55846          assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
55847          rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
55848          assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
55849          if( u.be.v==MAX_ROWID ){
55850            u.be.pC->useRandomRowid = 1;
55851          }else{
55852            u.be.v++;   /* IMP: R-29538-34987 */
55853          }
55854        }
55855      }
55856
55857#ifndef SQLITE_OMIT_AUTOINCREMENT
55858      if( pOp->p3 ){
55859        /* Assert that P3 is a valid memory cell. */
55860        assert( pOp->p3>0 );
55861        if( p->pFrame ){
55862          for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
55863          /* Assert that P3 is a valid memory cell. */
55864          assert( pOp->p3<=u.be.pFrame->nMem );
55865          u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
55866        }else{
55867          /* Assert that P3 is a valid memory cell. */
55868          assert( pOp->p3<=p->nMem );
55869          u.be.pMem = &aMem[pOp->p3];
55870        }
55871
55872        REGISTER_TRACE(pOp->p3, u.be.pMem);
55873        sqlite3VdbeMemIntegerify(u.be.pMem);
55874        assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
55875        if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
55876          rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
55877          goto abort_due_to_error;
55878        }
55879        if( u.be.v<u.be.pMem->u.i+1 ){
55880          u.be.v = u.be.pMem->u.i + 1;
55881        }
55882        u.be.pMem->u.i = u.be.v;
55883      }
55884#endif
55885
55886      sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
55887    }
55888    if( u.be.pC->useRandomRowid ){
55889      /* IMPLEMENTATION-OF: R-48598-02938 If the largest ROWID is equal to the
55890      ** largest possible integer (9223372036854775807) then the database
55891      ** engine starts picking candidate ROWIDs at random until it finds one
55892      ** that is not previously used.
55893      */
55894      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
55895                             ** an AUTOINCREMENT table. */
55896      u.be.v = db->lastRowid;
55897      u.be.cnt = 0;
55898      do{
55899        if( u.be.cnt==0 && (u.be.v&0xffffff)==u.be.v ){
55900          u.be.v++;
55901        }else{
55902          sqlite3_randomness(sizeof(u.be.v), &u.be.v);
55903          if( u.be.cnt<5 ) u.be.v &= 0xffffff;
55904        }
55905        rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v, 0, &u.be.res);
55906        u.be.cnt++;
55907      }while( u.be.cnt<100 && rc==SQLITE_OK && u.be.res==0 );
55908      if( rc==SQLITE_OK && u.be.res==0 ){
55909        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
55910        goto abort_due_to_error;
55911      }
55912    }
55913    u.be.pC->rowidIsValid = 0;
55914    u.be.pC->deferredMoveto = 0;
55915    u.be.pC->cacheStatus = CACHE_STALE;
55916  }
55917  pOut->u.i = u.be.v;
55918  break;
55919}
55920
55921/* Opcode: Insert P1 P2 P3 P4 P5
55922**
55923** Write an entry into the table of cursor P1.  A new entry is
55924** created if it doesn't already exist or the data for an existing
55925** entry is overwritten.  The data is the value MEM_Blob stored in register
55926** number P2. The key is stored in register P3. The key must
55927** be a MEM_Int.
55928**
55929** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
55930** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
55931** then rowid is stored for subsequent return by the
55932** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
55933**
55934** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
55935** the last seek operation (OP_NotExists) was a success, then this
55936** operation will not attempt to find the appropriate row before doing
55937** the insert but will instead overwrite the row that the cursor is
55938** currently pointing to.  Presumably, the prior OP_NotExists opcode
55939** has already positioned the cursor correctly.  This is an optimization
55940** that boosts performance by avoiding redundant seeks.
55941**
55942** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
55943** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
55944** is part of an INSERT operation.  The difference is only important to
55945** the update hook.
55946**
55947** Parameter P4 may point to a string containing the table-name, or
55948** may be NULL. If it is not NULL, then the update-hook
55949** (sqlite3.xUpdateCallback) is invoked following a successful insert.
55950**
55951** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
55952** allocated, then ownership of P2 is transferred to the pseudo-cursor
55953** and register P2 becomes ephemeral.  If the cursor is changed, the
55954** value of register P2 will then change.  Make sure this does not
55955** cause any problems.)
55956**
55957** This instruction only works on tables.  The equivalent instruction
55958** for indices is OP_IdxInsert.
55959*/
55960/* Opcode: InsertInt P1 P2 P3 P4 P5
55961**
55962** This works exactly like OP_Insert except that the key is the
55963** integer value P3, not the value of the integer stored in register P3.
55964*/
55965case OP_Insert:
55966case OP_InsertInt: {
55967#if 0  /* local variables moved into u.bf */
55968  Mem *pData;       /* MEM cell holding data for the record to be inserted */
55969  Mem *pKey;        /* MEM cell holding key  for the record */
55970  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
55971  VdbeCursor *pC;   /* Cursor to table into which insert is written */
55972  int nZero;        /* Number of zero-bytes to append */
55973  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
55974  const char *zDb;  /* database name - used by the update hook */
55975  const char *zTbl; /* Table name - used by the opdate hook */
55976  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
55977#endif /* local variables moved into u.bf */
55978
55979  u.bf.pData = &aMem[pOp->p2];
55980  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
55981  u.bf.pC = p->apCsr[pOp->p1];
55982  assert( u.bf.pC!=0 );
55983  assert( u.bf.pC->pCursor!=0 );
55984  assert( u.bf.pC->pseudoTableReg==0 );
55985  assert( u.bf.pC->isTable );
55986  REGISTER_TRACE(pOp->p2, u.bf.pData);
55987
55988  if( pOp->opcode==OP_Insert ){
55989    u.bf.pKey = &aMem[pOp->p3];
55990    assert( u.bf.pKey->flags & MEM_Int );
55991    REGISTER_TRACE(pOp->p3, u.bf.pKey);
55992    u.bf.iKey = u.bf.pKey->u.i;
55993  }else{
55994    assert( pOp->opcode==OP_InsertInt );
55995    u.bf.iKey = pOp->p3;
55996  }
55997
55998  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
55999  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
56000  if( u.bf.pData->flags & MEM_Null ){
56001    u.bf.pData->z = 0;
56002    u.bf.pData->n = 0;
56003  }else{
56004    assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
56005  }
56006  u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
56007  if( u.bf.pData->flags & MEM_Zero ){
56008    u.bf.nZero = u.bf.pData->u.nZero;
56009  }else{
56010    u.bf.nZero = 0;
56011  }
56012  sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
56013  rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
56014                          u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
56015                          pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
56016  );
56017  u.bf.pC->rowidIsValid = 0;
56018  u.bf.pC->deferredMoveto = 0;
56019  u.bf.pC->cacheStatus = CACHE_STALE;
56020
56021  /* Invoke the update-hook if required. */
56022  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
56023    u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
56024    u.bf.zTbl = pOp->p4.z;
56025    u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
56026    assert( u.bf.pC->isTable );
56027    db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
56028    assert( u.bf.pC->iDb>=0 );
56029  }
56030  break;
56031}
56032
56033/* Opcode: Delete P1 P2 * P4 *
56034**
56035** Delete the record at which the P1 cursor is currently pointing.
56036**
56037** The cursor will be left pointing at either the next or the previous
56038** record in the table. If it is left pointing at the next record, then
56039** the next Next instruction will be a no-op.  Hence it is OK to delete
56040** a record from within an Next loop.
56041**
56042** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
56043** incremented (otherwise not).
56044**
56045** P1 must not be pseudo-table.  It has to be a real table with
56046** multiple rows.
56047**
56048** If P4 is not NULL, then it is the name of the table that P1 is
56049** pointing to.  The update hook will be invoked, if it exists.
56050** If P4 is not NULL then the P1 cursor must have been positioned
56051** using OP_NotFound prior to invoking this opcode.
56052*/
56053case OP_Delete: {
56054#if 0  /* local variables moved into u.bg */
56055  i64 iKey;
56056  VdbeCursor *pC;
56057#endif /* local variables moved into u.bg */
56058
56059  u.bg.iKey = 0;
56060  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56061  u.bg.pC = p->apCsr[pOp->p1];
56062  assert( u.bg.pC!=0 );
56063  assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
56064
56065  /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
56066  ** row being deleted.
56067  */
56068  if( db->xUpdateCallback && pOp->p4.z ){
56069    assert( u.bg.pC->isTable );
56070    assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
56071    u.bg.iKey = u.bg.pC->lastRowid;
56072  }
56073
56074  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
56075  ** OP_Column on the same table without any intervening operations that
56076  ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
56077  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
56078  ** below is always a no-op and cannot fail.  We will run it anyhow, though,
56079  ** to guard against future changes to the code generator.
56080  **/
56081  assert( u.bg.pC->deferredMoveto==0 );
56082  rc = sqlite3VdbeCursorMoveto(u.bg.pC);
56083  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
56084
56085  sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
56086  rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
56087  u.bg.pC->cacheStatus = CACHE_STALE;
56088
56089  /* Invoke the update-hook if required. */
56090  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
56091    const char *zDb = db->aDb[u.bg.pC->iDb].zName;
56092    const char *zTbl = pOp->p4.z;
56093    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
56094    assert( u.bg.pC->iDb>=0 );
56095  }
56096  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
56097  break;
56098}
56099/* Opcode: ResetCount * * * * *
56100**
56101** The value of the change counter is copied to the database handle
56102** change counter (returned by subsequent calls to sqlite3_changes()).
56103** Then the VMs internal change counter resets to 0.
56104** This is used by trigger programs.
56105*/
56106case OP_ResetCount: {
56107  sqlite3VdbeSetChanges(db, p->nChange);
56108  p->nChange = 0;
56109  break;
56110}
56111
56112/* Opcode: RowData P1 P2 * * *
56113**
56114** Write into register P2 the complete row data for cursor P1.
56115** There is no interpretation of the data.
56116** It is just copied onto the P2 register exactly as
56117** it is found in the database file.
56118**
56119** If the P1 cursor must be pointing to a valid row (not a NULL row)
56120** of a real table, not a pseudo-table.
56121*/
56122/* Opcode: RowKey P1 P2 * * *
56123**
56124** Write into register P2 the complete row key for cursor P1.
56125** There is no interpretation of the data.
56126** The key is copied onto the P3 register exactly as
56127** it is found in the database file.
56128**
56129** If the P1 cursor must be pointing to a valid row (not a NULL row)
56130** of a real table, not a pseudo-table.
56131*/
56132case OP_RowKey:
56133case OP_RowData: {
56134#if 0  /* local variables moved into u.bh */
56135  VdbeCursor *pC;
56136  BtCursor *pCrsr;
56137  u32 n;
56138  i64 n64;
56139#endif /* local variables moved into u.bh */
56140
56141  pOut = &aMem[pOp->p2];
56142
56143  /* Note that RowKey and RowData are really exactly the same instruction */
56144  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56145  u.bh.pC = p->apCsr[pOp->p1];
56146  assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
56147  assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
56148  assert( u.bh.pC!=0 );
56149  assert( u.bh.pC->nullRow==0 );
56150  assert( u.bh.pC->pseudoTableReg==0 );
56151  assert( u.bh.pC->pCursor!=0 );
56152  u.bh.pCrsr = u.bh.pC->pCursor;
56153  assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
56154
56155  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
56156  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
56157  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
56158  ** a no-op and can never fail.  But we leave it in place as a safety.
56159  */
56160  assert( u.bh.pC->deferredMoveto==0 );
56161  rc = sqlite3VdbeCursorMoveto(u.bh.pC);
56162  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
56163
56164  if( u.bh.pC->isIndex ){
56165    assert( !u.bh.pC->isTable );
56166    rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
56167    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
56168    if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
56169      goto too_big;
56170    }
56171    u.bh.n = (u32)u.bh.n64;
56172  }else{
56173    rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
56174    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
56175    if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
56176      goto too_big;
56177    }
56178  }
56179  if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
56180    goto no_mem;
56181  }
56182  pOut->n = u.bh.n;
56183  MemSetTypeFlag(pOut, MEM_Blob);
56184  if( u.bh.pC->isIndex ){
56185    rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
56186  }else{
56187    rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
56188  }
56189  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
56190  UPDATE_MAX_BLOBSIZE(pOut);
56191  break;
56192}
56193
56194/* Opcode: Rowid P1 P2 * * *
56195**
56196** Store in register P2 an integer which is the key of the table entry that
56197** P1 is currently point to.
56198**
56199** P1 can be either an ordinary table or a virtual table.  There used to
56200** be a separate OP_VRowid opcode for use with virtual tables, but this
56201** one opcode now works for both table types.
56202*/
56203case OP_Rowid: {                 /* out2-prerelease */
56204#if 0  /* local variables moved into u.bi */
56205  VdbeCursor *pC;
56206  i64 v;
56207  sqlite3_vtab *pVtab;
56208  const sqlite3_module *pModule;
56209#endif /* local variables moved into u.bi */
56210
56211  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56212  u.bi.pC = p->apCsr[pOp->p1];
56213  assert( u.bi.pC!=0 );
56214  assert( u.bi.pC->pseudoTableReg==0 );
56215  if( u.bi.pC->nullRow ){
56216    pOut->flags = MEM_Null;
56217    break;
56218  }else if( u.bi.pC->deferredMoveto ){
56219    u.bi.v = u.bi.pC->movetoTarget;
56220#ifndef SQLITE_OMIT_VIRTUALTABLE
56221  }else if( u.bi.pC->pVtabCursor ){
56222    u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
56223    u.bi.pModule = u.bi.pVtab->pModule;
56224    assert( u.bi.pModule->xRowid );
56225    if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
56226    rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
56227    sqlite3DbFree(db, p->zErrMsg);
56228    p->zErrMsg = u.bi.pVtab->zErrMsg;
56229    u.bi.pVtab->zErrMsg = 0;
56230    if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
56231#endif /* SQLITE_OMIT_VIRTUALTABLE */
56232  }else{
56233    assert( u.bi.pC->pCursor!=0 );
56234    rc = sqlite3VdbeCursorMoveto(u.bi.pC);
56235    if( rc ) goto abort_due_to_error;
56236    if( u.bi.pC->rowidIsValid ){
56237      u.bi.v = u.bi.pC->lastRowid;
56238    }else{
56239      rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
56240      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
56241    }
56242  }
56243  pOut->u.i = u.bi.v;
56244  break;
56245}
56246
56247/* Opcode: NullRow P1 * * * *
56248**
56249** Move the cursor P1 to a null row.  Any OP_Column operations
56250** that occur while the cursor is on the null row will always
56251** write a NULL.
56252*/
56253case OP_NullRow: {
56254#if 0  /* local variables moved into u.bj */
56255  VdbeCursor *pC;
56256#endif /* local variables moved into u.bj */
56257
56258  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56259  u.bj.pC = p->apCsr[pOp->p1];
56260  assert( u.bj.pC!=0 );
56261  u.bj.pC->nullRow = 1;
56262  u.bj.pC->rowidIsValid = 0;
56263  if( u.bj.pC->pCursor ){
56264    sqlite3BtreeClearCursor(u.bj.pC->pCursor);
56265  }
56266  break;
56267}
56268
56269/* Opcode: Last P1 P2 * * *
56270**
56271** The next use of the Rowid or Column or Next instruction for P1
56272** will refer to the last entry in the database table or index.
56273** If the table or index is empty and P2>0, then jump immediately to P2.
56274** If P2 is 0 or if the table or index is not empty, fall through
56275** to the following instruction.
56276*/
56277case OP_Last: {        /* jump */
56278#if 0  /* local variables moved into u.bk */
56279  VdbeCursor *pC;
56280  BtCursor *pCrsr;
56281  int res;
56282#endif /* local variables moved into u.bk */
56283
56284  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56285  u.bk.pC = p->apCsr[pOp->p1];
56286  assert( u.bk.pC!=0 );
56287  u.bk.pCrsr = u.bk.pC->pCursor;
56288  if( u.bk.pCrsr==0 ){
56289    u.bk.res = 1;
56290  }else{
56291    rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
56292  }
56293  u.bk.pC->nullRow = (u8)u.bk.res;
56294  u.bk.pC->deferredMoveto = 0;
56295  u.bk.pC->rowidIsValid = 0;
56296  u.bk.pC->cacheStatus = CACHE_STALE;
56297  if( pOp->p2>0 && u.bk.res ){
56298    pc = pOp->p2 - 1;
56299  }
56300  break;
56301}
56302
56303
56304/* Opcode: Sort P1 P2 * * *
56305**
56306** This opcode does exactly the same thing as OP_Rewind except that
56307** it increments an undocumented global variable used for testing.
56308**
56309** Sorting is accomplished by writing records into a sorting index,
56310** then rewinding that index and playing it back from beginning to
56311** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
56312** rewinding so that the global variable will be incremented and
56313** regression tests can determine whether or not the optimizer is
56314** correctly optimizing out sorts.
56315*/
56316case OP_Sort: {        /* jump */
56317#ifdef SQLITE_TEST
56318  sqlite3_sort_count++;
56319  sqlite3_search_count--;
56320#endif
56321  p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
56322  /* Fall through into OP_Rewind */
56323}
56324/* Opcode: Rewind P1 P2 * * *
56325**
56326** The next use of the Rowid or Column or Next instruction for P1
56327** will refer to the first entry in the database table or index.
56328** If the table or index is empty and P2>0, then jump immediately to P2.
56329** If P2 is 0 or if the table or index is not empty, fall through
56330** to the following instruction.
56331*/
56332case OP_Rewind: {        /* jump */
56333#if 0  /* local variables moved into u.bl */
56334  VdbeCursor *pC;
56335  BtCursor *pCrsr;
56336  int res;
56337#endif /* local variables moved into u.bl */
56338
56339  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56340  u.bl.pC = p->apCsr[pOp->p1];
56341  assert( u.bl.pC!=0 );
56342  if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
56343    rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
56344    u.bl.pC->atFirst = u.bl.res==0 ?1:0;
56345    u.bl.pC->deferredMoveto = 0;
56346    u.bl.pC->cacheStatus = CACHE_STALE;
56347    u.bl.pC->rowidIsValid = 0;
56348  }else{
56349    u.bl.res = 1;
56350  }
56351  u.bl.pC->nullRow = (u8)u.bl.res;
56352  assert( pOp->p2>0 && pOp->p2<p->nOp );
56353  if( u.bl.res ){
56354    pc = pOp->p2 - 1;
56355  }
56356  break;
56357}
56358
56359/* Opcode: Next P1 P2 * * *
56360**
56361** Advance cursor P1 so that it points to the next key/data pair in its
56362** table or index.  If there are no more key/value pairs then fall through
56363** to the following instruction.  But if the cursor advance was successful,
56364** jump immediately to P2.
56365**
56366** The P1 cursor must be for a real table, not a pseudo-table.
56367**
56368** See also: Prev
56369*/
56370/* Opcode: Prev P1 P2 * * *
56371**
56372** Back up cursor P1 so that it points to the previous key/data pair in its
56373** table or index.  If there is no previous key/value pairs then fall through
56374** to the following instruction.  But if the cursor backup was successful,
56375** jump immediately to P2.
56376**
56377** The P1 cursor must be for a real table, not a pseudo-table.
56378*/
56379case OP_Prev:          /* jump */
56380case OP_Next: {        /* jump */
56381#if 0  /* local variables moved into u.bm */
56382  VdbeCursor *pC;
56383  BtCursor *pCrsr;
56384  int res;
56385#endif /* local variables moved into u.bm */
56386
56387  CHECK_FOR_INTERRUPT;
56388  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56389  u.bm.pC = p->apCsr[pOp->p1];
56390  if( u.bm.pC==0 ){
56391    break;  /* See ticket #2273 */
56392  }
56393  u.bm.pCrsr = u.bm.pC->pCursor;
56394  if( u.bm.pCrsr==0 ){
56395    u.bm.pC->nullRow = 1;
56396    break;
56397  }
56398  u.bm.res = 1;
56399  assert( u.bm.pC->deferredMoveto==0 );
56400  rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
56401                              sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
56402  u.bm.pC->nullRow = (u8)u.bm.res;
56403  u.bm.pC->cacheStatus = CACHE_STALE;
56404  if( u.bm.res==0 ){
56405    pc = pOp->p2 - 1;
56406    if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
56407#ifdef SQLITE_TEST
56408    sqlite3_search_count++;
56409#endif
56410  }
56411  u.bm.pC->rowidIsValid = 0;
56412  break;
56413}
56414
56415/* Opcode: IdxInsert P1 P2 P3 * P5
56416**
56417** Register P2 holds a SQL index key made using the
56418** MakeRecord instructions.  This opcode writes that key
56419** into the index P1.  Data for the entry is nil.
56420**
56421** P3 is a flag that provides a hint to the b-tree layer that this
56422** insert is likely to be an append.
56423**
56424** This instruction only works for indices.  The equivalent instruction
56425** for tables is OP_Insert.
56426*/
56427case OP_IdxInsert: {        /* in2 */
56428#if 0  /* local variables moved into u.bn */
56429  VdbeCursor *pC;
56430  BtCursor *pCrsr;
56431  int nKey;
56432  const char *zKey;
56433#endif /* local variables moved into u.bn */
56434
56435  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56436  u.bn.pC = p->apCsr[pOp->p1];
56437  assert( u.bn.pC!=0 );
56438  pIn2 = &aMem[pOp->p2];
56439  assert( pIn2->flags & MEM_Blob );
56440  u.bn.pCrsr = u.bn.pC->pCursor;
56441  if( ALWAYS(u.bn.pCrsr!=0) ){
56442    assert( u.bn.pC->isTable==0 );
56443    rc = ExpandBlob(pIn2);
56444    if( rc==SQLITE_OK ){
56445      u.bn.nKey = pIn2->n;
56446      u.bn.zKey = pIn2->z;
56447      rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
56448          ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
56449      );
56450      assert( u.bn.pC->deferredMoveto==0 );
56451      u.bn.pC->cacheStatus = CACHE_STALE;
56452    }
56453  }
56454  break;
56455}
56456
56457/* Opcode: IdxDelete P1 P2 P3 * *
56458**
56459** The content of P3 registers starting at register P2 form
56460** an unpacked index key. This opcode removes that entry from the
56461** index opened by cursor P1.
56462*/
56463case OP_IdxDelete: {
56464#if 0  /* local variables moved into u.bo */
56465  VdbeCursor *pC;
56466  BtCursor *pCrsr;
56467  int res;
56468  UnpackedRecord r;
56469#endif /* local variables moved into u.bo */
56470
56471  assert( pOp->p3>0 );
56472  assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
56473  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56474  u.bo.pC = p->apCsr[pOp->p1];
56475  assert( u.bo.pC!=0 );
56476  u.bo.pCrsr = u.bo.pC->pCursor;
56477  if( ALWAYS(u.bo.pCrsr!=0) ){
56478    u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
56479    u.bo.r.nField = (u16)pOp->p3;
56480    u.bo.r.flags = 0;
56481    u.bo.r.aMem = &aMem[pOp->p2];
56482    rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
56483    if( rc==SQLITE_OK && u.bo.res==0 ){
56484      rc = sqlite3BtreeDelete(u.bo.pCrsr);
56485    }
56486    assert( u.bo.pC->deferredMoveto==0 );
56487    u.bo.pC->cacheStatus = CACHE_STALE;
56488  }
56489  break;
56490}
56491
56492/* Opcode: IdxRowid P1 P2 * * *
56493**
56494** Write into register P2 an integer which is the last entry in the record at
56495** the end of the index key pointed to by cursor P1.  This integer should be
56496** the rowid of the table entry to which this index entry points.
56497**
56498** See also: Rowid, MakeRecord.
56499*/
56500case OP_IdxRowid: {              /* out2-prerelease */
56501#if 0  /* local variables moved into u.bp */
56502  BtCursor *pCrsr;
56503  VdbeCursor *pC;
56504  i64 rowid;
56505#endif /* local variables moved into u.bp */
56506
56507  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56508  u.bp.pC = p->apCsr[pOp->p1];
56509  assert( u.bp.pC!=0 );
56510  u.bp.pCrsr = u.bp.pC->pCursor;
56511  pOut->flags = MEM_Null;
56512  if( ALWAYS(u.bp.pCrsr!=0) ){
56513    rc = sqlite3VdbeCursorMoveto(u.bp.pC);
56514    if( NEVER(rc) ) goto abort_due_to_error;
56515    assert( u.bp.pC->deferredMoveto==0 );
56516    assert( u.bp.pC->isTable==0 );
56517    if( !u.bp.pC->nullRow ){
56518      rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
56519      if( rc!=SQLITE_OK ){
56520        goto abort_due_to_error;
56521      }
56522      pOut->u.i = u.bp.rowid;
56523      pOut->flags = MEM_Int;
56524    }
56525  }
56526  break;
56527}
56528
56529/* Opcode: IdxGE P1 P2 P3 P4 P5
56530**
56531** The P4 register values beginning with P3 form an unpacked index
56532** key that omits the ROWID.  Compare this key value against the index
56533** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
56534**
56535** If the P1 index entry is greater than or equal to the key value
56536** then jump to P2.  Otherwise fall through to the next instruction.
56537**
56538** If P5 is non-zero then the key value is increased by an epsilon
56539** prior to the comparison.  This make the opcode work like IdxGT except
56540** that if the key from register P3 is a prefix of the key in the cursor,
56541** the result is false whereas it would be true with IdxGT.
56542*/
56543/* Opcode: IdxLT P1 P2 P3 * P5
56544**
56545** The P4 register values beginning with P3 form an unpacked index
56546** key that omits the ROWID.  Compare this key value against the index
56547** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
56548**
56549** If the P1 index entry is less than the key value then jump to P2.
56550** Otherwise fall through to the next instruction.
56551**
56552** If P5 is non-zero then the key value is increased by an epsilon prior
56553** to the comparison.  This makes the opcode work like IdxLE.
56554*/
56555case OP_IdxLT:          /* jump */
56556case OP_IdxGE: {        /* jump */
56557#if 0  /* local variables moved into u.bq */
56558  VdbeCursor *pC;
56559  int res;
56560  UnpackedRecord r;
56561#endif /* local variables moved into u.bq */
56562
56563  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56564  u.bq.pC = p->apCsr[pOp->p1];
56565  assert( u.bq.pC!=0 );
56566  if( ALWAYS(u.bq.pC->pCursor!=0) ){
56567    assert( u.bq.pC->deferredMoveto==0 );
56568    assert( pOp->p5==0 || pOp->p5==1 );
56569    assert( pOp->p4type==P4_INT32 );
56570    u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
56571    u.bq.r.nField = (u16)pOp->p4.i;
56572    if( pOp->p5 ){
56573      u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
56574    }else{
56575      u.bq.r.flags = UNPACKED_IGNORE_ROWID;
56576    }
56577    u.bq.r.aMem = &aMem[pOp->p3];
56578    rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
56579    if( pOp->opcode==OP_IdxLT ){
56580      u.bq.res = -u.bq.res;
56581    }else{
56582      assert( pOp->opcode==OP_IdxGE );
56583      u.bq.res++;
56584    }
56585    if( u.bq.res>0 ){
56586      pc = pOp->p2 - 1 ;
56587    }
56588  }
56589  break;
56590}
56591
56592/* Opcode: Destroy P1 P2 P3 * *
56593**
56594** Delete an entire database table or index whose root page in the database
56595** file is given by P1.
56596**
56597** The table being destroyed is in the main database file if P3==0.  If
56598** P3==1 then the table to be clear is in the auxiliary database file
56599** that is used to store tables create using CREATE TEMPORARY TABLE.
56600**
56601** If AUTOVACUUM is enabled then it is possible that another root page
56602** might be moved into the newly deleted root page in order to keep all
56603** root pages contiguous at the beginning of the database.  The former
56604** value of the root page that moved - its value before the move occurred -
56605** is stored in register P2.  If no page
56606** movement was required (because the table being dropped was already
56607** the last one in the database) then a zero is stored in register P2.
56608** If AUTOVACUUM is disabled then a zero is stored in register P2.
56609**
56610** See also: Clear
56611*/
56612case OP_Destroy: {     /* out2-prerelease */
56613#if 0  /* local variables moved into u.br */
56614  int iMoved;
56615  int iCnt;
56616  Vdbe *pVdbe;
56617  int iDb;
56618#endif /* local variables moved into u.br */
56619#ifndef SQLITE_OMIT_VIRTUALTABLE
56620  u.br.iCnt = 0;
56621  for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
56622    if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
56623      u.br.iCnt++;
56624    }
56625  }
56626#else
56627  u.br.iCnt = db->activeVdbeCnt;
56628#endif
56629  pOut->flags = MEM_Null;
56630  if( u.br.iCnt>1 ){
56631    rc = SQLITE_LOCKED;
56632    p->errorAction = OE_Abort;
56633  }else{
56634    u.br.iDb = pOp->p3;
56635    assert( u.br.iCnt==1 );
56636    assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
56637    rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
56638    pOut->flags = MEM_Int;
56639    pOut->u.i = u.br.iMoved;
56640#ifndef SQLITE_OMIT_AUTOVACUUM
56641    if( rc==SQLITE_OK && u.br.iMoved!=0 ){
56642      sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
56643      resetSchemaOnFault = 1;
56644    }
56645#endif
56646  }
56647  break;
56648}
56649
56650/* Opcode: Clear P1 P2 P3
56651**
56652** Delete all contents of the database table or index whose root page
56653** in the database file is given by P1.  But, unlike Destroy, do not
56654** remove the table or index from the database file.
56655**
56656** The table being clear is in the main database file if P2==0.  If
56657** P2==1 then the table to be clear is in the auxiliary database file
56658** that is used to store tables create using CREATE TEMPORARY TABLE.
56659**
56660** If the P3 value is non-zero, then the table referred to must be an
56661** intkey table (an SQL table, not an index). In this case the row change
56662** count is incremented by the number of rows in the table being cleared.
56663** If P3 is greater than zero, then the value stored in register P3 is
56664** also incremented by the number of rows in the table being cleared.
56665**
56666** See also: Destroy
56667*/
56668case OP_Clear: {
56669#if 0  /* local variables moved into u.bs */
56670  int nChange;
56671#endif /* local variables moved into u.bs */
56672
56673  u.bs.nChange = 0;
56674  assert( (p->btreeMask & (1<<pOp->p2))!=0 );
56675  rc = sqlite3BtreeClearTable(
56676      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
56677  );
56678  if( pOp->p3 ){
56679    p->nChange += u.bs.nChange;
56680    if( pOp->p3>0 ){
56681      aMem[pOp->p3].u.i += u.bs.nChange;
56682    }
56683  }
56684  break;
56685}
56686
56687/* Opcode: CreateTable P1 P2 * * *
56688**
56689** Allocate a new table in the main database file if P1==0 or in the
56690** auxiliary database file if P1==1 or in an attached database if
56691** P1>1.  Write the root page number of the new table into
56692** register P2
56693**
56694** The difference between a table and an index is this:  A table must
56695** have a 4-byte integer key and can have arbitrary data.  An index
56696** has an arbitrary key but no data.
56697**
56698** See also: CreateIndex
56699*/
56700/* Opcode: CreateIndex P1 P2 * * *
56701**
56702** Allocate a new index in the main database file if P1==0 or in the
56703** auxiliary database file if P1==1 or in an attached database if
56704** P1>1.  Write the root page number of the new table into
56705** register P2.
56706**
56707** See documentation on OP_CreateTable for additional information.
56708*/
56709case OP_CreateIndex:            /* out2-prerelease */
56710case OP_CreateTable: {          /* out2-prerelease */
56711#if 0  /* local variables moved into u.bt */
56712  int pgno;
56713  int flags;
56714  Db *pDb;
56715#endif /* local variables moved into u.bt */
56716
56717  u.bt.pgno = 0;
56718  assert( pOp->p1>=0 && pOp->p1<db->nDb );
56719  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
56720  u.bt.pDb = &db->aDb[pOp->p1];
56721  assert( u.bt.pDb->pBt!=0 );
56722  if( pOp->opcode==OP_CreateTable ){
56723    /* u.bt.flags = BTREE_INTKEY; */
56724    u.bt.flags = BTREE_LEAFDATA|BTREE_INTKEY;
56725  }else{
56726    u.bt.flags = BTREE_ZERODATA;
56727  }
56728  rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
56729  pOut->u.i = u.bt.pgno;
56730  break;
56731}
56732
56733/* Opcode: ParseSchema P1 P2 * P4 *
56734**
56735** Read and parse all entries from the SQLITE_MASTER table of database P1
56736** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
56737** the parsing if P2 is true.  If P2 is false, then this routine is a
56738** no-op if the schema is not currently loaded.  In other words, if P2
56739** is false, the SQLITE_MASTER table is only parsed if the rest of the
56740** schema is already loaded into the symbol table.
56741**
56742** This opcode invokes the parser to create a new virtual machine,
56743** then runs the new virtual machine.  It is thus a re-entrant opcode.
56744*/
56745case OP_ParseSchema: {
56746#if 0  /* local variables moved into u.bu */
56747  int iDb;
56748  const char *zMaster;
56749  char *zSql;
56750  InitData initData;
56751#endif /* local variables moved into u.bu */
56752
56753  u.bu.iDb = pOp->p1;
56754  assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
56755
56756  /* If pOp->p2 is 0, then this opcode is being executed to read a
56757  ** single row, for example the row corresponding to a new index
56758  ** created by this VDBE, from the sqlite_master table. It only
56759  ** does this if the corresponding in-memory schema is currently
56760  ** loaded. Otherwise, the new index definition can be loaded along
56761  ** with the rest of the schema when it is required.
56762  **
56763  ** Although the mutex on the BtShared object that corresponds to
56764  ** database u.bu.iDb (the database containing the sqlite_master table
56765  ** read by this instruction) is currently held, it is necessary to
56766  ** obtain the mutexes on all attached databases before checking if
56767  ** the schema of u.bu.iDb is loaded. This is because, at the start of
56768  ** the sqlite3_exec() call below, SQLite will invoke
56769  ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
56770  ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
56771  ** this happens, then some other thread may delete the in-memory
56772  ** schema of database u.bu.iDb before the SQL statement runs. The schema
56773  ** will not be reloaded becuase the db->init.busy flag is set. This
56774  ** can result in a "no such table: sqlite_master" or "malformed
56775  ** database schema" error being returned to the user.
56776  */
56777  assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
56778  sqlite3BtreeEnterAll(db);
56779  if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
56780    u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
56781    u.bu.initData.db = db;
56782    u.bu.initData.iDb = pOp->p1;
56783    u.bu.initData.pzErrMsg = &p->zErrMsg;
56784    u.bu.zSql = sqlite3MPrintf(db,
56785       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s",
56786       db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
56787    if( u.bu.zSql==0 ){
56788      rc = SQLITE_NOMEM;
56789    }else{
56790      (void)sqlite3SafetyOff(db);
56791      assert( db->init.busy==0 );
56792      db->init.busy = 1;
56793      u.bu.initData.rc = SQLITE_OK;
56794      assert( !db->mallocFailed );
56795      rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
56796      if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
56797      sqlite3DbFree(db, u.bu.zSql);
56798      db->init.busy = 0;
56799      (void)sqlite3SafetyOn(db);
56800    }
56801  }
56802  sqlite3BtreeLeaveAll(db);
56803  if( rc==SQLITE_NOMEM ){
56804    goto no_mem;
56805  }
56806  break;
56807}
56808
56809#if !defined(SQLITE_OMIT_ANALYZE)
56810/* Opcode: LoadAnalysis P1 * * * *
56811**
56812** Read the sqlite_stat1 table for database P1 and load the content
56813** of that table into the internal index hash table.  This will cause
56814** the analysis to be used when preparing all subsequent queries.
56815*/
56816case OP_LoadAnalysis: {
56817  assert( pOp->p1>=0 && pOp->p1<db->nDb );
56818  rc = sqlite3AnalysisLoad(db, pOp->p1);
56819  break;
56820}
56821#endif /* !defined(SQLITE_OMIT_ANALYZE) */
56822
56823/* Opcode: DropTable P1 * * P4 *
56824**
56825** Remove the internal (in-memory) data structures that describe
56826** the table named P4 in database P1.  This is called after a table
56827** is dropped in order to keep the internal representation of the
56828** schema consistent with what is on disk.
56829*/
56830case OP_DropTable: {
56831  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
56832  break;
56833}
56834
56835/* Opcode: DropIndex P1 * * P4 *
56836**
56837** Remove the internal (in-memory) data structures that describe
56838** the index named P4 in database P1.  This is called after an index
56839** is dropped in order to keep the internal representation of the
56840** schema consistent with what is on disk.
56841*/
56842case OP_DropIndex: {
56843  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
56844  break;
56845}
56846
56847/* Opcode: DropTrigger P1 * * P4 *
56848**
56849** Remove the internal (in-memory) data structures that describe
56850** the trigger named P4 in database P1.  This is called after a trigger
56851** is dropped in order to keep the internal representation of the
56852** schema consistent with what is on disk.
56853*/
56854case OP_DropTrigger: {
56855  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
56856  break;
56857}
56858
56859
56860#ifndef SQLITE_OMIT_INTEGRITY_CHECK
56861/* Opcode: IntegrityCk P1 P2 P3 * P5
56862**
56863** Do an analysis of the currently open database.  Store in
56864** register P1 the text of an error message describing any problems.
56865** If no problems are found, store a NULL in register P1.
56866**
56867** The register P3 contains the maximum number of allowed errors.
56868** At most reg(P3) errors will be reported.
56869** In other words, the analysis stops as soon as reg(P1) errors are
56870** seen.  Reg(P1) is updated with the number of errors remaining.
56871**
56872** The root page numbers of all tables in the database are integer
56873** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
56874** total.
56875**
56876** If P5 is not zero, the check is done on the auxiliary database
56877** file, not the main database file.
56878**
56879** This opcode is used to implement the integrity_check pragma.
56880*/
56881case OP_IntegrityCk: {
56882#if 0  /* local variables moved into u.bv */
56883  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
56884  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
56885  int j;          /* Loop counter */
56886  int nErr;       /* Number of errors reported */
56887  char *z;        /* Text of the error report */
56888  Mem *pnErr;     /* Register keeping track of errors remaining */
56889#endif /* local variables moved into u.bv */
56890
56891  u.bv.nRoot = pOp->p2;
56892  assert( u.bv.nRoot>0 );
56893  u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
56894  if( u.bv.aRoot==0 ) goto no_mem;
56895  assert( pOp->p3>0 && pOp->p3<=p->nMem );
56896  u.bv.pnErr = &aMem[pOp->p3];
56897  assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
56898  assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
56899  pIn1 = &aMem[pOp->p1];
56900  for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
56901    u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
56902  }
56903  u.bv.aRoot[u.bv.j] = 0;
56904  assert( pOp->p5<db->nDb );
56905  assert( (p->btreeMask & (1<<pOp->p5))!=0 );
56906  u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
56907                                 (int)u.bv.pnErr->u.i, &u.bv.nErr);
56908  sqlite3DbFree(db, u.bv.aRoot);
56909  u.bv.pnErr->u.i -= u.bv.nErr;
56910  sqlite3VdbeMemSetNull(pIn1);
56911  if( u.bv.nErr==0 ){
56912    assert( u.bv.z==0 );
56913  }else if( u.bv.z==0 ){
56914    goto no_mem;
56915  }else{
56916    sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
56917  }
56918  UPDATE_MAX_BLOBSIZE(pIn1);
56919  sqlite3VdbeChangeEncoding(pIn1, encoding);
56920  break;
56921}
56922#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56923
56924/* Opcode: RowSetAdd P1 P2 * * *
56925**
56926** Insert the integer value held by register P2 into a boolean index
56927** held in register P1.
56928**
56929** An assertion fails if P2 is not an integer.
56930*/
56931case OP_RowSetAdd: {       /* in1, in2 */
56932  pIn1 = &aMem[pOp->p1];
56933  pIn2 = &aMem[pOp->p2];
56934  assert( (pIn2->flags & MEM_Int)!=0 );
56935  if( (pIn1->flags & MEM_RowSet)==0 ){
56936    sqlite3VdbeMemSetRowSet(pIn1);
56937    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
56938  }
56939  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
56940  break;
56941}
56942
56943/* Opcode: RowSetRead P1 P2 P3 * *
56944**
56945** Extract the smallest value from boolean index P1 and put that value into
56946** register P3.  Or, if boolean index P1 is initially empty, leave P3
56947** unchanged and jump to instruction P2.
56948*/
56949case OP_RowSetRead: {       /* jump, in1, out3 */
56950#if 0  /* local variables moved into u.bw */
56951  i64 val;
56952#endif /* local variables moved into u.bw */
56953  CHECK_FOR_INTERRUPT;
56954  pIn1 = &aMem[pOp->p1];
56955  if( (pIn1->flags & MEM_RowSet)==0
56956   || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
56957  ){
56958    /* The boolean index is empty */
56959    sqlite3VdbeMemSetNull(pIn1);
56960    pc = pOp->p2 - 1;
56961  }else{
56962    /* A value was pulled from the index */
56963    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
56964  }
56965  break;
56966}
56967
56968/* Opcode: RowSetTest P1 P2 P3 P4
56969**
56970** Register P3 is assumed to hold a 64-bit integer value. If register P1
56971** contains a RowSet object and that RowSet object contains
56972** the value held in P3, jump to register P2. Otherwise, insert the
56973** integer in P3 into the RowSet and continue on to the
56974** next opcode.
56975**
56976** The RowSet object is optimized for the case where successive sets
56977** of integers, where each set contains no duplicates. Each set
56978** of values is identified by a unique P4 value. The first set
56979** must have P4==0, the final set P4=-1.  P4 must be either -1 or
56980** non-negative.  For non-negative values of P4 only the lower 4
56981** bits are significant.
56982**
56983** This allows optimizations: (a) when P4==0 there is no need to test
56984** the rowset object for P3, as it is guaranteed not to contain it,
56985** (b) when P4==-1 there is no need to insert the value, as it will
56986** never be tested for, and (c) when a value that is part of set X is
56987** inserted, there is no need to search to see if the same value was
56988** previously inserted as part of set X (only if it was previously
56989** inserted as part of some other set).
56990*/
56991case OP_RowSetTest: {                     /* jump, in1, in3 */
56992#if 0  /* local variables moved into u.bx */
56993  int iSet;
56994  int exists;
56995#endif /* local variables moved into u.bx */
56996
56997  pIn1 = &aMem[pOp->p1];
56998  pIn3 = &aMem[pOp->p3];
56999  u.bx.iSet = pOp->p4.i;
57000  assert( pIn3->flags&MEM_Int );
57001
57002  /* If there is anything other than a rowset object in memory cell P1,
57003  ** delete it now and initialize P1 with an empty rowset
57004  */
57005  if( (pIn1->flags & MEM_RowSet)==0 ){
57006    sqlite3VdbeMemSetRowSet(pIn1);
57007    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
57008  }
57009
57010  assert( pOp->p4type==P4_INT32 );
57011  assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
57012  if( u.bx.iSet ){
57013    u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
57014                               (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
57015                               pIn3->u.i);
57016    if( u.bx.exists ){
57017      pc = pOp->p2 - 1;
57018      break;
57019    }
57020  }
57021  if( u.bx.iSet>=0 ){
57022    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
57023  }
57024  break;
57025}
57026
57027
57028#ifndef SQLITE_OMIT_TRIGGER
57029
57030/* Opcode: Program P1 P2 P3 P4 *
57031**
57032** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
57033**
57034** P1 contains the address of the memory cell that contains the first memory
57035** cell in an array of values used as arguments to the sub-program. P2
57036** contains the address to jump to if the sub-program throws an IGNORE
57037** exception using the RAISE() function. Register P3 contains the address
57038** of a memory cell in this (the parent) VM that is used to allocate the
57039** memory required by the sub-vdbe at runtime.
57040**
57041** P4 is a pointer to the VM containing the trigger program.
57042*/
57043case OP_Program: {        /* jump */
57044#if 0  /* local variables moved into u.by */
57045  int nMem;               /* Number of memory registers for sub-program */
57046  int nByte;              /* Bytes of runtime space required for sub-program */
57047  Mem *pRt;               /* Register to allocate runtime space */
57048  Mem *pMem;              /* Used to iterate through memory cells */
57049  Mem *pEnd;              /* Last memory cell in new array */
57050  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
57051  SubProgram *pProgram;   /* Sub-program to execute */
57052  void *t;                /* Token identifying trigger */
57053#endif /* local variables moved into u.by */
57054
57055  u.by.pProgram = pOp->p4.pProgram;
57056  u.by.pRt = &aMem[pOp->p3];
57057  assert( u.by.pProgram->nOp>0 );
57058
57059  /* If the p5 flag is clear, then recursive invocation of triggers is
57060  ** disabled for backwards compatibility (p5 is set if this sub-program
57061  ** is really a trigger, not a foreign key action, and the flag set
57062  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
57063  **
57064  ** It is recursive invocation of triggers, at the SQL level, that is
57065  ** disabled. In some cases a single trigger may generate more than one
57066  ** SubProgram (if the trigger may be executed with more than one different
57067  ** ON CONFLICT algorithm). SubProgram structures associated with a
57068  ** single trigger all have the same value for the SubProgram.token
57069  ** variable.  */
57070  if( pOp->p5 ){
57071    u.by.t = u.by.pProgram->token;
57072    for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
57073    if( u.by.pFrame ) break;
57074  }
57075
57076  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
57077    rc = SQLITE_ERROR;
57078    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
57079    break;
57080  }
57081
57082  /* Register u.by.pRt is used to store the memory required to save the state
57083  ** of the current program, and the memory required at runtime to execute
57084  ** the trigger program. If this trigger has been fired before, then u.by.pRt
57085  ** is already allocated. Otherwise, it must be initialized.  */
57086  if( (u.by.pRt->flags&MEM_Frame)==0 ){
57087    /* SubProgram.nMem is set to the number of memory cells used by the
57088    ** program stored in SubProgram.aOp. As well as these, one memory
57089    ** cell is required for each cursor used by the program. Set local
57090    ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
57091    */
57092    u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
57093    u.by.nByte = ROUND8(sizeof(VdbeFrame))
57094              + u.by.nMem * sizeof(Mem)
57095              + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
57096    u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
57097    if( !u.by.pFrame ){
57098      goto no_mem;
57099    }
57100    sqlite3VdbeMemRelease(u.by.pRt);
57101    u.by.pRt->flags = MEM_Frame;
57102    u.by.pRt->u.pFrame = u.by.pFrame;
57103
57104    u.by.pFrame->v = p;
57105    u.by.pFrame->nChildMem = u.by.nMem;
57106    u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
57107    u.by.pFrame->pc = pc;
57108    u.by.pFrame->aMem = p->aMem;
57109    u.by.pFrame->nMem = p->nMem;
57110    u.by.pFrame->apCsr = p->apCsr;
57111    u.by.pFrame->nCursor = p->nCursor;
57112    u.by.pFrame->aOp = p->aOp;
57113    u.by.pFrame->nOp = p->nOp;
57114    u.by.pFrame->token = u.by.pProgram->token;
57115
57116    u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
57117    for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
57118      u.by.pMem->flags = MEM_Null;
57119      u.by.pMem->db = db;
57120    }
57121  }else{
57122    u.by.pFrame = u.by.pRt->u.pFrame;
57123    assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
57124    assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
57125    assert( pc==u.by.pFrame->pc );
57126  }
57127
57128  p->nFrame++;
57129  u.by.pFrame->pParent = p->pFrame;
57130  u.by.pFrame->lastRowid = db->lastRowid;
57131  u.by.pFrame->nChange = p->nChange;
57132  p->nChange = 0;
57133  p->pFrame = u.by.pFrame;
57134  p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
57135  p->nMem = u.by.pFrame->nChildMem;
57136  p->nCursor = (u16)u.by.pFrame->nChildCsr;
57137  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
57138  p->aOp = aOp = u.by.pProgram->aOp;
57139  p->nOp = u.by.pProgram->nOp;
57140  pc = -1;
57141
57142  break;
57143}
57144
57145/* Opcode: Param P1 P2 * * *
57146**
57147** This opcode is only ever present in sub-programs called via the
57148** OP_Program instruction. Copy a value currently stored in a memory
57149** cell of the calling (parent) frame to cell P2 in the current frames
57150** address space. This is used by trigger programs to access the new.*
57151** and old.* values.
57152**
57153** The address of the cell in the parent frame is determined by adding
57154** the value of the P1 argument to the value of the P1 argument to the
57155** calling OP_Program instruction.
57156*/
57157case OP_Param: {           /* out2-prerelease */
57158#if 0  /* local variables moved into u.bz */
57159  VdbeFrame *pFrame;
57160  Mem *pIn;
57161#endif /* local variables moved into u.bz */
57162  u.bz.pFrame = p->pFrame;
57163  u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
57164  sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
57165  break;
57166}
57167
57168#endif /* #ifndef SQLITE_OMIT_TRIGGER */
57169
57170#ifndef SQLITE_OMIT_FOREIGN_KEY
57171/* Opcode: FkCounter P1 P2 * * *
57172**
57173** Increment a "constraint counter" by P2 (P2 may be negative or positive).
57174** If P1 is non-zero, the database constraint counter is incremented
57175** (deferred foreign key constraints). Otherwise, if P1 is zero, the
57176** statement counter is incremented (immediate foreign key constraints).
57177*/
57178case OP_FkCounter: {
57179  if( pOp->p1 ){
57180    db->nDeferredCons += pOp->p2;
57181  }else{
57182    p->nFkConstraint += pOp->p2;
57183  }
57184  break;
57185}
57186
57187/* Opcode: FkIfZero P1 P2 * * *
57188**
57189** This opcode tests if a foreign key constraint-counter is currently zero.
57190** If so, jump to instruction P2. Otherwise, fall through to the next
57191** instruction.
57192**
57193** If P1 is non-zero, then the jump is taken if the database constraint-counter
57194** is zero (the one that counts deferred constraint violations). If P1 is
57195** zero, the jump is taken if the statement constraint-counter is zero
57196** (immediate foreign key constraint violations).
57197*/
57198case OP_FkIfZero: {         /* jump */
57199  if( pOp->p1 ){
57200    if( db->nDeferredCons==0 ) pc = pOp->p2-1;
57201  }else{
57202    if( p->nFkConstraint==0 ) pc = pOp->p2-1;
57203  }
57204  break;
57205}
57206#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
57207
57208#ifndef SQLITE_OMIT_AUTOINCREMENT
57209/* Opcode: MemMax P1 P2 * * *
57210**
57211** P1 is a register in the root frame of this VM (the root frame is
57212** different from the current frame if this instruction is being executed
57213** within a sub-program). Set the value of register P1 to the maximum of
57214** its current value and the value in register P2.
57215**
57216** This instruction throws an error if the memory cell is not initially
57217** an integer.
57218*/
57219case OP_MemMax: {        /* in2 */
57220#if 0  /* local variables moved into u.ca */
57221  Mem *pIn1;
57222  VdbeFrame *pFrame;
57223#endif /* local variables moved into u.ca */
57224  if( p->pFrame ){
57225    for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
57226    u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
57227  }else{
57228    u.ca.pIn1 = &aMem[pOp->p1];
57229  }
57230  sqlite3VdbeMemIntegerify(u.ca.pIn1);
57231  pIn2 = &aMem[pOp->p2];
57232  sqlite3VdbeMemIntegerify(pIn2);
57233  if( u.ca.pIn1->u.i<pIn2->u.i){
57234    u.ca.pIn1->u.i = pIn2->u.i;
57235  }
57236  break;
57237}
57238#endif /* SQLITE_OMIT_AUTOINCREMENT */
57239
57240/* Opcode: IfPos P1 P2 * * *
57241**
57242** If the value of register P1 is 1 or greater, jump to P2.
57243**
57244** It is illegal to use this instruction on a register that does
57245** not contain an integer.  An assertion fault will result if you try.
57246*/
57247case OP_IfPos: {        /* jump, in1 */
57248  pIn1 = &aMem[pOp->p1];
57249  assert( pIn1->flags&MEM_Int );
57250  if( pIn1->u.i>0 ){
57251     pc = pOp->p2 - 1;
57252  }
57253  break;
57254}
57255
57256/* Opcode: IfNeg P1 P2 * * *
57257**
57258** If the value of register P1 is less than zero, jump to P2.
57259**
57260** It is illegal to use this instruction on a register that does
57261** not contain an integer.  An assertion fault will result if you try.
57262*/
57263case OP_IfNeg: {        /* jump, in1 */
57264  pIn1 = &aMem[pOp->p1];
57265  assert( pIn1->flags&MEM_Int );
57266  if( pIn1->u.i<0 ){
57267     pc = pOp->p2 - 1;
57268  }
57269  break;
57270}
57271
57272/* Opcode: IfZero P1 P2 P3 * *
57273**
57274** The register P1 must contain an integer.  Add literal P3 to the
57275** value in register P1.  If the result is exactly 0, jump to P2.
57276**
57277** It is illegal to use this instruction on a register that does
57278** not contain an integer.  An assertion fault will result if you try.
57279*/
57280case OP_IfZero: {        /* jump, in1 */
57281  pIn1 = &aMem[pOp->p1];
57282  assert( pIn1->flags&MEM_Int );
57283  pIn1->u.i += pOp->p3;
57284  if( pIn1->u.i==0 ){
57285     pc = pOp->p2 - 1;
57286  }
57287  break;
57288}
57289
57290/* Opcode: AggStep * P2 P3 P4 P5
57291**
57292** Execute the step function for an aggregate.  The
57293** function has P5 arguments.   P4 is a pointer to the FuncDef
57294** structure that specifies the function.  Use register
57295** P3 as the accumulator.
57296**
57297** The P5 arguments are taken from register P2 and its
57298** successors.
57299*/
57300case OP_AggStep: {
57301#if 0  /* local variables moved into u.cb */
57302  int n;
57303  int i;
57304  Mem *pMem;
57305  Mem *pRec;
57306  sqlite3_context ctx;
57307  sqlite3_value **apVal;
57308#endif /* local variables moved into u.cb */
57309
57310  u.cb.n = pOp->p5;
57311  assert( u.cb.n>=0 );
57312  u.cb.pRec = &aMem[pOp->p2];
57313  u.cb.apVal = p->apArg;
57314  assert( u.cb.apVal || u.cb.n==0 );
57315  for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
57316    u.cb.apVal[u.cb.i] = u.cb.pRec;
57317    sqlite3VdbeMemStoreType(u.cb.pRec);
57318  }
57319  u.cb.ctx.pFunc = pOp->p4.pFunc;
57320  assert( pOp->p3>0 && pOp->p3<=p->nMem );
57321  u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
57322  u.cb.pMem->n++;
57323  u.cb.ctx.s.flags = MEM_Null;
57324  u.cb.ctx.s.z = 0;
57325  u.cb.ctx.s.zMalloc = 0;
57326  u.cb.ctx.s.xDel = 0;
57327  u.cb.ctx.s.db = db;
57328  u.cb.ctx.isError = 0;
57329  u.cb.ctx.pColl = 0;
57330  if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
57331    assert( pOp>p->aOp );
57332    assert( pOp[-1].p4type==P4_COLLSEQ );
57333    assert( pOp[-1].opcode==OP_CollSeq );
57334    u.cb.ctx.pColl = pOp[-1].p4.pColl;
57335  }
57336  (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal);
57337  if( u.cb.ctx.isError ){
57338    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
57339    rc = u.cb.ctx.isError;
57340  }
57341  sqlite3VdbeMemRelease(&u.cb.ctx.s);
57342  break;
57343}
57344
57345/* Opcode: AggFinal P1 P2 * P4 *
57346**
57347** Execute the finalizer function for an aggregate.  P1 is
57348** the memory location that is the accumulator for the aggregate.
57349**
57350** P2 is the number of arguments that the step function takes and
57351** P4 is a pointer to the FuncDef for this function.  The P2
57352** argument is not used by this opcode.  It is only there to disambiguate
57353** functions that can take varying numbers of arguments.  The
57354** P4 argument is only needed for the degenerate case where
57355** the step function was not previously called.
57356*/
57357case OP_AggFinal: {
57358#if 0  /* local variables moved into u.cc */
57359  Mem *pMem;
57360#endif /* local variables moved into u.cc */
57361  assert( pOp->p1>0 && pOp->p1<=p->nMem );
57362  u.cc.pMem = &aMem[pOp->p1];
57363  assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
57364  rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
57365  if( rc ){
57366    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
57367  }
57368  sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
57369  UPDATE_MAX_BLOBSIZE(u.cc.pMem);
57370  if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
57371    goto too_big;
57372  }
57373  break;
57374}
57375
57376
57377#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
57378/* Opcode: Vacuum * * * * *
57379**
57380** Vacuum the entire database.  This opcode will cause other virtual
57381** machines to be created and run.  It may not be called from within
57382** a transaction.
57383*/
57384case OP_Vacuum: {
57385  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57386  rc = sqlite3RunVacuum(&p->zErrMsg, db);
57387  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57388  break;
57389}
57390#endif
57391
57392#if !defined(SQLITE_OMIT_AUTOVACUUM)
57393/* Opcode: IncrVacuum P1 P2 * * *
57394**
57395** Perform a single step of the incremental vacuum procedure on
57396** the P1 database. If the vacuum has finished, jump to instruction
57397** P2. Otherwise, fall through to the next instruction.
57398*/
57399case OP_IncrVacuum: {        /* jump */
57400#if 0  /* local variables moved into u.cd */
57401  Btree *pBt;
57402#endif /* local variables moved into u.cd */
57403
57404  assert( pOp->p1>=0 && pOp->p1<db->nDb );
57405  assert( (p->btreeMask & (1<<pOp->p1))!=0 );
57406  u.cd.pBt = db->aDb[pOp->p1].pBt;
57407  rc = sqlite3BtreeIncrVacuum(u.cd.pBt);
57408  if( rc==SQLITE_DONE ){
57409    pc = pOp->p2 - 1;
57410    rc = SQLITE_OK;
57411  }
57412  break;
57413}
57414#endif
57415
57416/* Opcode: Expire P1 * * * *
57417**
57418** Cause precompiled statements to become expired. An expired statement
57419** fails with an error code of SQLITE_SCHEMA if it is ever executed
57420** (via sqlite3_step()).
57421**
57422** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
57423** then only the currently executing statement is affected.
57424*/
57425case OP_Expire: {
57426  if( !pOp->p1 ){
57427    sqlite3ExpirePreparedStatements(db);
57428  }else{
57429    p->expired = 1;
57430  }
57431  break;
57432}
57433
57434#ifndef SQLITE_OMIT_SHARED_CACHE
57435/* Opcode: TableLock P1 P2 P3 P4 *
57436**
57437** Obtain a lock on a particular table. This instruction is only used when
57438** the shared-cache feature is enabled.
57439**
57440** P1 is the index of the database in sqlite3.aDb[] of the database
57441** on which the lock is acquired.  A readlock is obtained if P3==0 or
57442** a write lock if P3==1.
57443**
57444** P2 contains the root-page of the table to lock.
57445**
57446** P4 contains a pointer to the name of the table being locked. This is only
57447** used to generate an error message if the lock cannot be obtained.
57448*/
57449case OP_TableLock: {
57450  u8 isWriteLock = (u8)pOp->p3;
57451  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
57452    int p1 = pOp->p1;
57453    assert( p1>=0 && p1<db->nDb );
57454    assert( (p->btreeMask & (1<<p1))!=0 );
57455    assert( isWriteLock==0 || isWriteLock==1 );
57456    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
57457    if( (rc&0xFF)==SQLITE_LOCKED ){
57458      const char *z = pOp->p4.z;
57459      sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
57460    }
57461  }
57462  break;
57463}
57464#endif /* SQLITE_OMIT_SHARED_CACHE */
57465
57466#ifndef SQLITE_OMIT_VIRTUALTABLE
57467/* Opcode: VBegin * * * P4 *
57468**
57469** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
57470** xBegin method for that table.
57471**
57472** Also, whether or not P4 is set, check that this is not being called from
57473** within a callback to a virtual table xSync() method. If it is, the error
57474** code will be set to SQLITE_LOCKED.
57475*/
57476case OP_VBegin: {
57477#if 0  /* local variables moved into u.ce */
57478  VTable *pVTab;
57479#endif /* local variables moved into u.ce */
57480  u.ce.pVTab = pOp->p4.pVtab;
57481  rc = sqlite3VtabBegin(db, u.ce.pVTab);
57482  if( u.ce.pVTab ){
57483    sqlite3DbFree(db, p->zErrMsg);
57484    p->zErrMsg = u.ce.pVTab->pVtab->zErrMsg;
57485    u.ce.pVTab->pVtab->zErrMsg = 0;
57486  }
57487  break;
57488}
57489#endif /* SQLITE_OMIT_VIRTUALTABLE */
57490
57491#ifndef SQLITE_OMIT_VIRTUALTABLE
57492/* Opcode: VCreate P1 * * P4 *
57493**
57494** P4 is the name of a virtual table in database P1. Call the xCreate method
57495** for that table.
57496*/
57497case OP_VCreate: {
57498  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
57499  break;
57500}
57501#endif /* SQLITE_OMIT_VIRTUALTABLE */
57502
57503#ifndef SQLITE_OMIT_VIRTUALTABLE
57504/* Opcode: VDestroy P1 * * P4 *
57505**
57506** P4 is the name of a virtual table in database P1.  Call the xDestroy method
57507** of that table.
57508*/
57509case OP_VDestroy: {
57510  p->inVtabMethod = 2;
57511  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
57512  p->inVtabMethod = 0;
57513  break;
57514}
57515#endif /* SQLITE_OMIT_VIRTUALTABLE */
57516
57517#ifndef SQLITE_OMIT_VIRTUALTABLE
57518/* Opcode: VOpen P1 * * P4 *
57519**
57520** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
57521** P1 is a cursor number.  This opcode opens a cursor to the virtual
57522** table and stores that cursor in P1.
57523*/
57524case OP_VOpen: {
57525#if 0  /* local variables moved into u.cf */
57526  VdbeCursor *pCur;
57527  sqlite3_vtab_cursor *pVtabCursor;
57528  sqlite3_vtab *pVtab;
57529  sqlite3_module *pModule;
57530#endif /* local variables moved into u.cf */
57531
57532  u.cf.pCur = 0;
57533  u.cf.pVtabCursor = 0;
57534  u.cf.pVtab = pOp->p4.pVtab->pVtab;
57535  u.cf.pModule = (sqlite3_module *)u.cf.pVtab->pModule;
57536  assert(u.cf.pVtab && u.cf.pModule);
57537  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57538  rc = u.cf.pModule->xOpen(u.cf.pVtab, &u.cf.pVtabCursor);
57539  sqlite3DbFree(db, p->zErrMsg);
57540  p->zErrMsg = u.cf.pVtab->zErrMsg;
57541  u.cf.pVtab->zErrMsg = 0;
57542  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57543  if( SQLITE_OK==rc ){
57544    /* Initialize sqlite3_vtab_cursor base class */
57545    u.cf.pVtabCursor->pVtab = u.cf.pVtab;
57546
57547    /* Initialise vdbe cursor object */
57548    u.cf.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
57549    if( u.cf.pCur ){
57550      u.cf.pCur->pVtabCursor = u.cf.pVtabCursor;
57551      u.cf.pCur->pModule = u.cf.pVtabCursor->pVtab->pModule;
57552    }else{
57553      db->mallocFailed = 1;
57554      u.cf.pModule->xClose(u.cf.pVtabCursor);
57555    }
57556  }
57557  break;
57558}
57559#endif /* SQLITE_OMIT_VIRTUALTABLE */
57560
57561#ifndef SQLITE_OMIT_VIRTUALTABLE
57562/* Opcode: VFilter P1 P2 P3 P4 *
57563**
57564** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
57565** the filtered result set is empty.
57566**
57567** P4 is either NULL or a string that was generated by the xBestIndex
57568** method of the module.  The interpretation of the P4 string is left
57569** to the module implementation.
57570**
57571** This opcode invokes the xFilter method on the virtual table specified
57572** by P1.  The integer query plan parameter to xFilter is stored in register
57573** P3. Register P3+1 stores the argc parameter to be passed to the
57574** xFilter method. Registers P3+2..P3+1+argc are the argc
57575** additional parameters which are passed to
57576** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
57577**
57578** A jump is made to P2 if the result set after filtering would be empty.
57579*/
57580case OP_VFilter: {   /* jump */
57581#if 0  /* local variables moved into u.cg */
57582  int nArg;
57583  int iQuery;
57584  const sqlite3_module *pModule;
57585  Mem *pQuery;
57586  Mem *pArgc;
57587  sqlite3_vtab_cursor *pVtabCursor;
57588  sqlite3_vtab *pVtab;
57589  VdbeCursor *pCur;
57590  int res;
57591  int i;
57592  Mem **apArg;
57593#endif /* local variables moved into u.cg */
57594
57595  u.cg.pQuery = &aMem[pOp->p3];
57596  u.cg.pArgc = &u.cg.pQuery[1];
57597  u.cg.pCur = p->apCsr[pOp->p1];
57598  REGISTER_TRACE(pOp->p3, u.cg.pQuery);
57599  assert( u.cg.pCur->pVtabCursor );
57600  u.cg.pVtabCursor = u.cg.pCur->pVtabCursor;
57601  u.cg.pVtab = u.cg.pVtabCursor->pVtab;
57602  u.cg.pModule = u.cg.pVtab->pModule;
57603
57604  /* Grab the index number and argc parameters */
57605  assert( (u.cg.pQuery->flags&MEM_Int)!=0 && u.cg.pArgc->flags==MEM_Int );
57606  u.cg.nArg = (int)u.cg.pArgc->u.i;
57607  u.cg.iQuery = (int)u.cg.pQuery->u.i;
57608
57609  /* Invoke the xFilter method */
57610  {
57611    u.cg.res = 0;
57612    u.cg.apArg = p->apArg;
57613    for(u.cg.i = 0; u.cg.i<u.cg.nArg; u.cg.i++){
57614      u.cg.apArg[u.cg.i] = &u.cg.pArgc[u.cg.i+1];
57615      sqlite3VdbeMemStoreType(u.cg.apArg[u.cg.i]);
57616    }
57617
57618    if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57619    p->inVtabMethod = 1;
57620    rc = u.cg.pModule->xFilter(u.cg.pVtabCursor, u.cg.iQuery, pOp->p4.z, u.cg.nArg, u.cg.apArg);
57621    p->inVtabMethod = 0;
57622    sqlite3DbFree(db, p->zErrMsg);
57623    p->zErrMsg = u.cg.pVtab->zErrMsg;
57624    u.cg.pVtab->zErrMsg = 0;
57625    if( rc==SQLITE_OK ){
57626      u.cg.res = u.cg.pModule->xEof(u.cg.pVtabCursor);
57627    }
57628    if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57629
57630    if( u.cg.res ){
57631      pc = pOp->p2 - 1;
57632    }
57633  }
57634  u.cg.pCur->nullRow = 0;
57635
57636  break;
57637}
57638#endif /* SQLITE_OMIT_VIRTUALTABLE */
57639
57640#ifndef SQLITE_OMIT_VIRTUALTABLE
57641/* Opcode: VColumn P1 P2 P3 * *
57642**
57643** Store the value of the P2-th column of
57644** the row of the virtual-table that the
57645** P1 cursor is pointing to into register P3.
57646*/
57647case OP_VColumn: {
57648#if 0  /* local variables moved into u.ch */
57649  sqlite3_vtab *pVtab;
57650  const sqlite3_module *pModule;
57651  Mem *pDest;
57652  sqlite3_context sContext;
57653#endif /* local variables moved into u.ch */
57654
57655  VdbeCursor *pCur = p->apCsr[pOp->p1];
57656  assert( pCur->pVtabCursor );
57657  assert( pOp->p3>0 && pOp->p3<=p->nMem );
57658  u.ch.pDest = &aMem[pOp->p3];
57659  if( pCur->nullRow ){
57660    sqlite3VdbeMemSetNull(u.ch.pDest);
57661    break;
57662  }
57663  u.ch.pVtab = pCur->pVtabCursor->pVtab;
57664  u.ch.pModule = u.ch.pVtab->pModule;
57665  assert( u.ch.pModule->xColumn );
57666  memset(&u.ch.sContext, 0, sizeof(u.ch.sContext));
57667
57668  /* The output cell may already have a buffer allocated. Move
57669  ** the current contents to u.ch.sContext.s so in case the user-function
57670  ** can use the already allocated buffer instead of allocating a
57671  ** new one.
57672  */
57673  sqlite3VdbeMemMove(&u.ch.sContext.s, u.ch.pDest);
57674  MemSetTypeFlag(&u.ch.sContext.s, MEM_Null);
57675
57676  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57677  rc = u.ch.pModule->xColumn(pCur->pVtabCursor, &u.ch.sContext, pOp->p2);
57678  sqlite3DbFree(db, p->zErrMsg);
57679  p->zErrMsg = u.ch.pVtab->zErrMsg;
57680  u.ch.pVtab->zErrMsg = 0;
57681  if( u.ch.sContext.isError ){
57682    rc = u.ch.sContext.isError;
57683  }
57684
57685  /* Copy the result of the function to the P3 register. We
57686  ** do this regardless of whether or not an error occurred to ensure any
57687  ** dynamic allocation in u.ch.sContext.s (a Mem struct) is  released.
57688  */
57689  sqlite3VdbeChangeEncoding(&u.ch.sContext.s, encoding);
57690  sqlite3VdbeMemMove(u.ch.pDest, &u.ch.sContext.s);
57691  REGISTER_TRACE(pOp->p3, u.ch.pDest);
57692  UPDATE_MAX_BLOBSIZE(u.ch.pDest);
57693
57694  if( sqlite3SafetyOn(db) ){
57695    goto abort_due_to_misuse;
57696  }
57697  if( sqlite3VdbeMemTooBig(u.ch.pDest) ){
57698    goto too_big;
57699  }
57700  break;
57701}
57702#endif /* SQLITE_OMIT_VIRTUALTABLE */
57703
57704#ifndef SQLITE_OMIT_VIRTUALTABLE
57705/* Opcode: VNext P1 P2 * * *
57706**
57707** Advance virtual table P1 to the next row in its result set and
57708** jump to instruction P2.  Or, if the virtual table has reached
57709** the end of its result set, then fall through to the next instruction.
57710*/
57711case OP_VNext: {   /* jump */
57712#if 0  /* local variables moved into u.ci */
57713  sqlite3_vtab *pVtab;
57714  const sqlite3_module *pModule;
57715  int res;
57716  VdbeCursor *pCur;
57717#endif /* local variables moved into u.ci */
57718
57719  u.ci.res = 0;
57720  u.ci.pCur = p->apCsr[pOp->p1];
57721  assert( u.ci.pCur->pVtabCursor );
57722  if( u.ci.pCur->nullRow ){
57723    break;
57724  }
57725  u.ci.pVtab = u.ci.pCur->pVtabCursor->pVtab;
57726  u.ci.pModule = u.ci.pVtab->pModule;
57727  assert( u.ci.pModule->xNext );
57728
57729  /* Invoke the xNext() method of the module. There is no way for the
57730  ** underlying implementation to return an error if one occurs during
57731  ** xNext(). Instead, if an error occurs, true is returned (indicating that
57732  ** data is available) and the error code returned when xColumn or
57733  ** some other method is next invoked on the save virtual table cursor.
57734  */
57735  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57736  p->inVtabMethod = 1;
57737  rc = u.ci.pModule->xNext(u.ci.pCur->pVtabCursor);
57738  p->inVtabMethod = 0;
57739  sqlite3DbFree(db, p->zErrMsg);
57740  p->zErrMsg = u.ci.pVtab->zErrMsg;
57741  u.ci.pVtab->zErrMsg = 0;
57742  if( rc==SQLITE_OK ){
57743    u.ci.res = u.ci.pModule->xEof(u.ci.pCur->pVtabCursor);
57744  }
57745  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57746
57747  if( !u.ci.res ){
57748    /* If there is data, jump to P2 */
57749    pc = pOp->p2 - 1;
57750  }
57751  break;
57752}
57753#endif /* SQLITE_OMIT_VIRTUALTABLE */
57754
57755#ifndef SQLITE_OMIT_VIRTUALTABLE
57756/* Opcode: VRename P1 * * P4 *
57757**
57758** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
57759** This opcode invokes the corresponding xRename method. The value
57760** in register P1 is passed as the zName argument to the xRename method.
57761*/
57762case OP_VRename: {
57763#if 0  /* local variables moved into u.cj */
57764  sqlite3_vtab *pVtab;
57765  Mem *pName;
57766#endif /* local variables moved into u.cj */
57767
57768  u.cj.pVtab = pOp->p4.pVtab->pVtab;
57769  u.cj.pName = &aMem[pOp->p1];
57770  assert( u.cj.pVtab->pModule->xRename );
57771  REGISTER_TRACE(pOp->p1, u.cj.pName);
57772  assert( u.cj.pName->flags & MEM_Str );
57773  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57774  rc = u.cj.pVtab->pModule->xRename(u.cj.pVtab, u.cj.pName->z);
57775  sqlite3DbFree(db, p->zErrMsg);
57776  p->zErrMsg = u.cj.pVtab->zErrMsg;
57777  u.cj.pVtab->zErrMsg = 0;
57778  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57779
57780  break;
57781}
57782#endif
57783
57784#ifndef SQLITE_OMIT_VIRTUALTABLE
57785/* Opcode: VUpdate P1 P2 P3 P4 *
57786**
57787** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
57788** This opcode invokes the corresponding xUpdate method. P2 values
57789** are contiguous memory cells starting at P3 to pass to the xUpdate
57790** invocation. The value in register (P3+P2-1) corresponds to the
57791** p2th element of the argv array passed to xUpdate.
57792**
57793** The xUpdate method will do a DELETE or an INSERT or both.
57794** The argv[0] element (which corresponds to memory cell P3)
57795** is the rowid of a row to delete.  If argv[0] is NULL then no
57796** deletion occurs.  The argv[1] element is the rowid of the new
57797** row.  This can be NULL to have the virtual table select the new
57798** rowid for itself.  The subsequent elements in the array are
57799** the values of columns in the new row.
57800**
57801** If P2==1 then no insert is performed.  argv[0] is the rowid of
57802** a row to delete.
57803**
57804** P1 is a boolean flag. If it is set to true and the xUpdate call
57805** is successful, then the value returned by sqlite3_last_insert_rowid()
57806** is set to the value of the rowid for the row just inserted.
57807*/
57808case OP_VUpdate: {
57809#if 0  /* local variables moved into u.ck */
57810  sqlite3_vtab *pVtab;
57811  sqlite3_module *pModule;
57812  int nArg;
57813  int i;
57814  sqlite_int64 rowid;
57815  Mem **apArg;
57816  Mem *pX;
57817#endif /* local variables moved into u.ck */
57818
57819  u.ck.pVtab = pOp->p4.pVtab->pVtab;
57820  u.ck.pModule = (sqlite3_module *)u.ck.pVtab->pModule;
57821  u.ck.nArg = pOp->p2;
57822  assert( pOp->p4type==P4_VTAB );
57823  if( ALWAYS(u.ck.pModule->xUpdate) ){
57824    u.ck.apArg = p->apArg;
57825    u.ck.pX = &aMem[pOp->p3];
57826    for(u.ck.i=0; u.ck.i<u.ck.nArg; u.ck.i++){
57827      sqlite3VdbeMemStoreType(u.ck.pX);
57828      u.ck.apArg[u.ck.i] = u.ck.pX;
57829      u.ck.pX++;
57830    }
57831    if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
57832    rc = u.ck.pModule->xUpdate(u.ck.pVtab, u.ck.nArg, u.ck.apArg, &u.ck.rowid);
57833    sqlite3DbFree(db, p->zErrMsg);
57834    p->zErrMsg = u.ck.pVtab->zErrMsg;
57835    u.ck.pVtab->zErrMsg = 0;
57836    if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;
57837    if( rc==SQLITE_OK && pOp->p1 ){
57838      assert( u.ck.nArg>1 && u.ck.apArg[0] && (u.ck.apArg[0]->flags&MEM_Null) );
57839      db->lastRowid = u.ck.rowid;
57840    }
57841    p->nChange++;
57842  }
57843  break;
57844}
57845#endif /* SQLITE_OMIT_VIRTUALTABLE */
57846
57847#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
57848/* Opcode: Pagecount P1 P2 * * *
57849**
57850** Write the current number of pages in database P1 to memory cell P2.
57851*/
57852case OP_Pagecount: {            /* out2-prerelease */
57853#if 0  /* local variables moved into u.cl */
57854  int p1;
57855  int nPage;
57856  Pager *pPager;
57857#endif /* local variables moved into u.cl */
57858
57859  u.cl.p1 = pOp->p1;
57860  u.cl.pPager = sqlite3BtreePager(db->aDb[u.cl.p1].pBt);
57861  rc = sqlite3PagerPagecount(u.cl.pPager, &u.cl.nPage);
57862  /* OP_Pagecount is always called from within a read transaction.  The
57863  ** page count has already been successfully read and cached.  So the
57864  ** sqlite3PagerPagecount() call above cannot fail. */
57865  if( ALWAYS(rc==SQLITE_OK) ){
57866    pOut->u.i = u.cl.nPage;
57867  }
57868  break;
57869}
57870#endif
57871
57872#ifndef SQLITE_OMIT_TRACE
57873/* Opcode: Trace * * * P4 *
57874**
57875** If tracing is enabled (by the sqlite3_trace()) interface, then
57876** the UTF-8 string contained in P4 is emitted on the trace callback.
57877*/
57878case OP_Trace: {
57879#if 0  /* local variables moved into u.cm */
57880  char *zTrace;
57881#endif /* local variables moved into u.cm */
57882
57883  u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
57884  if( u.cm.zTrace ){
57885    if( db->xTrace ){
57886      char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
57887      db->xTrace(db->pTraceArg, z);
57888      sqlite3DbFree(db, z);
57889    }
57890#ifdef SQLITE_DEBUG
57891    if( (db->flags & SQLITE_SqlTrace)!=0 ){
57892      sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
57893    }
57894#endif /* SQLITE_DEBUG */
57895  }
57896  break;
57897}
57898#endif
57899
57900
57901/* Opcode: Noop * * * * *
57902**
57903** Do nothing.  This instruction is often useful as a jump
57904** destination.
57905*/
57906/*
57907** The magic Explain opcode are only inserted when explain==2 (which
57908** is to say when the EXPLAIN QUERY PLAN syntax is used.)
57909** This opcode records information from the optimizer.  It is the
57910** the same as a no-op.  This opcodesnever appears in a real VM program.
57911*/
57912default: {          /* This is really OP_Noop and OP_Explain */
57913  break;
57914}
57915
57916/*****************************************************************************
57917** The cases of the switch statement above this line should all be indented
57918** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
57919** readability.  From this point on down, the normal indentation rules are
57920** restored.
57921*****************************************************************************/
57922    }
57923
57924#ifdef VDBE_PROFILE
57925    {
57926      u64 elapsed = sqlite3Hwtime() - start;
57927      pOp->cycles += elapsed;
57928      pOp->cnt++;
57929#if 0
57930        fprintf(stdout, "%10llu ", elapsed);
57931        sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
57932#endif
57933    }
57934#endif
57935
57936    /* The following code adds nothing to the actual functionality
57937    ** of the program.  It is only here for testing and debugging.
57938    ** On the other hand, it does burn CPU cycles every time through
57939    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
57940    */
57941#ifndef NDEBUG
57942    assert( pc>=-1 && pc<p->nOp );
57943
57944#ifdef SQLITE_DEBUG
57945    if( p->trace ){
57946      if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
57947      if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
57948        registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
57949      }
57950      if( pOp->opflags & OPFLG_OUT3 ){
57951        registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
57952      }
57953    }
57954#endif  /* SQLITE_DEBUG */
57955#endif  /* NDEBUG */
57956  }  /* The end of the for(;;) loop the loops through opcodes */
57957
57958  /* If we reach this point, it means that execution is finished with
57959  ** an error of some kind.
57960  */
57961vdbe_error_halt:
57962  assert( rc );
57963  p->rc = rc;
57964  sqlite3VdbeHalt(p);
57965  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
57966  rc = SQLITE_ERROR;
57967  if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
57968
57969  /* This is the only way out of this procedure.  We have to
57970  ** release the mutexes on btrees that were acquired at the
57971  ** top. */
57972vdbe_return:
57973  sqlite3BtreeMutexArrayLeave(&p->aMutex);
57974  return rc;
57975
57976  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
57977  ** is encountered.
57978  */
57979too_big:
57980  sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
57981  rc = SQLITE_TOOBIG;
57982  goto vdbe_error_halt;
57983
57984  /* Jump to here if a malloc() fails.
57985  */
57986no_mem:
57987  db->mallocFailed = 1;
57988  sqlite3SetString(&p->zErrMsg, db, "out of memory");
57989  rc = SQLITE_NOMEM;
57990  goto vdbe_error_halt;
57991
57992  /* Jump to here for an SQLITE_MISUSE error.
57993  */
57994abort_due_to_misuse:
57995  rc = SQLITE_MISUSE;
57996  /* Fall thru into abort_due_to_error */
57997
57998  /* Jump to here for any other kind of fatal error.  The "rc" variable
57999  ** should hold the error number.
58000  */
58001abort_due_to_error:
58002  assert( p->zErrMsg==0 );
58003  if( db->mallocFailed ) rc = SQLITE_NOMEM;
58004  if( rc!=SQLITE_IOERR_NOMEM ){
58005    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
58006  }
58007  goto vdbe_error_halt;
58008
58009  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
58010  ** flag.
58011  */
58012abort_due_to_interrupt:
58013  assert( db->u1.isInterrupted );
58014  rc = SQLITE_INTERRUPT;
58015  p->rc = rc;
58016  sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
58017  goto vdbe_error_halt;
58018}
58019
58020/************** End of vdbe.c ************************************************/
58021/************** Begin file vdbeblob.c ****************************************/
58022/*
58023** 2007 May 1
58024**
58025** The author disclaims copyright to this source code.  In place of
58026** a legal notice, here is a blessing:
58027**
58028**    May you do good and not evil.
58029**    May you find forgiveness for yourself and forgive others.
58030**    May you share freely, never taking more than you give.
58031**
58032*************************************************************************
58033**
58034** This file contains code used to implement incremental BLOB I/O.
58035*/
58036
58037
58038#ifndef SQLITE_OMIT_INCRBLOB
58039
58040/*
58041** Valid sqlite3_blob* handles point to Incrblob structures.
58042*/
58043typedef struct Incrblob Incrblob;
58044struct Incrblob {
58045  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
58046  int nByte;              /* Size of open blob, in bytes */
58047  int iOffset;            /* Byte offset of blob in cursor data */
58048  BtCursor *pCsr;         /* Cursor pointing at blob row */
58049  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
58050  sqlite3 *db;            /* The associated database */
58051};
58052
58053/*
58054** Open a blob handle.
58055*/
58056SQLITE_API int sqlite3_blob_open(
58057  sqlite3* db,            /* The database connection */
58058  const char *zDb,        /* The attached database containing the blob */
58059  const char *zTable,     /* The table containing the blob */
58060  const char *zColumn,    /* The column containing the blob */
58061  sqlite_int64 iRow,      /* The row containing the glob */
58062  int flags,              /* True -> read/write access, false -> read-only */
58063  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
58064){
58065  int nAttempt = 0;
58066  int iCol;               /* Index of zColumn in row-record */
58067
58068  /* This VDBE program seeks a btree cursor to the identified
58069  ** db/table/row entry. The reason for using a vdbe program instead
58070  ** of writing code to use the b-tree layer directly is that the
58071  ** vdbe program will take advantage of the various transaction,
58072  ** locking and error handling infrastructure built into the vdbe.
58073  **
58074  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
58075  ** Code external to the Vdbe then "borrows" the b-tree cursor and
58076  ** uses it to implement the blob_read(), blob_write() and
58077  ** blob_bytes() functions.
58078  **
58079  ** The sqlite3_blob_close() function finalizes the vdbe program,
58080  ** which closes the b-tree cursor and (possibly) commits the
58081  ** transaction.
58082  */
58083  static const VdbeOpList openBlob[] = {
58084    {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
58085    {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
58086    {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
58087
58088    /* One of the following two instructions is replaced by an OP_Noop. */
58089    {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
58090    {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
58091
58092    {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
58093    {OP_NotExists, 0, 9, 1},       /* 6: Seek the cursor */
58094    {OP_Column, 0, 0, 1},          /* 7  */
58095    {OP_ResultRow, 1, 0, 0},       /* 8  */
58096    {OP_Close, 0, 0, 0},           /* 9  */
58097    {OP_Halt, 0, 0, 0},            /* 10 */
58098  };
58099
58100  Vdbe *v = 0;
58101  int rc = SQLITE_OK;
58102  char *zErr = 0;
58103  Table *pTab;
58104  Parse *pParse;
58105
58106  *ppBlob = 0;
58107  sqlite3_mutex_enter(db->mutex);
58108  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
58109  if( pParse==0 ){
58110    rc = SQLITE_NOMEM;
58111    goto blob_open_out;
58112  }
58113  do {
58114    memset(pParse, 0, sizeof(Parse));
58115    pParse->db = db;
58116
58117    if( sqlite3SafetyOn(db) ){
58118      sqlite3DbFree(db, zErr);
58119      sqlite3StackFree(db, pParse);
58120      sqlite3_mutex_leave(db->mutex);
58121      return SQLITE_MISUSE;
58122    }
58123
58124    sqlite3BtreeEnterAll(db);
58125    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
58126    if( pTab && IsVirtual(pTab) ){
58127      pTab = 0;
58128      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
58129    }
58130#ifndef SQLITE_OMIT_VIEW
58131    if( pTab && pTab->pSelect ){
58132      pTab = 0;
58133      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
58134    }
58135#endif
58136    if( !pTab ){
58137      if( pParse->zErrMsg ){
58138        sqlite3DbFree(db, zErr);
58139        zErr = pParse->zErrMsg;
58140        pParse->zErrMsg = 0;
58141      }
58142      rc = SQLITE_ERROR;
58143      (void)sqlite3SafetyOff(db);
58144      sqlite3BtreeLeaveAll(db);
58145      goto blob_open_out;
58146    }
58147
58148    /* Now search pTab for the exact column. */
58149    for(iCol=0; iCol < pTab->nCol; iCol++) {
58150      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
58151        break;
58152      }
58153    }
58154    if( iCol==pTab->nCol ){
58155      sqlite3DbFree(db, zErr);
58156      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
58157      rc = SQLITE_ERROR;
58158      (void)sqlite3SafetyOff(db);
58159      sqlite3BtreeLeaveAll(db);
58160      goto blob_open_out;
58161    }
58162
58163    /* If the value is being opened for writing, check that the
58164    ** column is not indexed, and that it is not part of a foreign key.
58165    ** It is against the rules to open a column to which either of these
58166    ** descriptions applies for writing.  */
58167    if( flags ){
58168      const char *zFault = 0;
58169      Index *pIdx;
58170#ifndef SQLITE_OMIT_FOREIGN_KEY
58171      if( db->flags&SQLITE_ForeignKeys ){
58172        /* Check that the column is not part of an FK child key definition. It
58173        ** is not necessary to check if it is part of a parent key, as parent
58174        ** key columns must be indexed. The check below will pick up this
58175        ** case.  */
58176        FKey *pFKey;
58177        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
58178          int j;
58179          for(j=0; j<pFKey->nCol; j++){
58180            if( pFKey->aCol[j].iFrom==iCol ){
58181              zFault = "foreign key";
58182            }
58183          }
58184        }
58185      }
58186#endif
58187      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
58188        int j;
58189        for(j=0; j<pIdx->nColumn; j++){
58190          if( pIdx->aiColumn[j]==iCol ){
58191            zFault = "indexed";
58192          }
58193        }
58194      }
58195      if( zFault ){
58196        sqlite3DbFree(db, zErr);
58197        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
58198        rc = SQLITE_ERROR;
58199        (void)sqlite3SafetyOff(db);
58200        sqlite3BtreeLeaveAll(db);
58201        goto blob_open_out;
58202      }
58203    }
58204
58205    v = sqlite3VdbeCreate(db);
58206    if( v ){
58207      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
58208      sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
58209      flags = !!flags;                 /* flags = (flags ? 1 : 0); */
58210
58211      /* Configure the OP_Transaction */
58212      sqlite3VdbeChangeP1(v, 0, iDb);
58213      sqlite3VdbeChangeP2(v, 0, flags);
58214
58215      /* Configure the OP_VerifyCookie */
58216      sqlite3VdbeChangeP1(v, 1, iDb);
58217      sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
58218
58219      /* Make sure a mutex is held on the table to be accessed */
58220      sqlite3VdbeUsesBtree(v, iDb);
58221
58222      /* Configure the OP_TableLock instruction */
58223      sqlite3VdbeChangeP1(v, 2, iDb);
58224      sqlite3VdbeChangeP2(v, 2, pTab->tnum);
58225      sqlite3VdbeChangeP3(v, 2, flags);
58226      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
58227
58228      /* Remove either the OP_OpenWrite or OpenRead. Set the P2
58229      ** parameter of the other to pTab->tnum.  */
58230      sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
58231      sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
58232      sqlite3VdbeChangeP3(v, 3 + flags, iDb);
58233
58234      /* Configure the number of columns. Configure the cursor to
58235      ** think that the table has one more column than it really
58236      ** does. An OP_Column to retrieve this imaginary column will
58237      ** always return an SQL NULL. This is useful because it means
58238      ** we can invoke OP_Column to fill in the vdbe cursors type
58239      ** and offset cache without causing any IO.
58240      */
58241      sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
58242      sqlite3VdbeChangeP2(v, 7, pTab->nCol);
58243      if( !db->mallocFailed ){
58244        sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
58245      }
58246    }
58247
58248    sqlite3BtreeLeaveAll(db);
58249    rc = sqlite3SafetyOff(db);
58250    if( NEVER(rc!=SQLITE_OK) || db->mallocFailed ){
58251      goto blob_open_out;
58252    }
58253
58254    sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
58255    rc = sqlite3_step((sqlite3_stmt *)v);
58256    if( rc!=SQLITE_ROW ){
58257      nAttempt++;
58258      rc = sqlite3_finalize((sqlite3_stmt *)v);
58259      sqlite3DbFree(db, zErr);
58260      zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
58261      v = 0;
58262    }
58263  } while( nAttempt<5 && rc==SQLITE_SCHEMA );
58264
58265  if( rc==SQLITE_ROW ){
58266    /* The row-record has been opened successfully. Check that the
58267    ** column in question contains text or a blob. If it contains
58268    ** text, it is up to the caller to get the encoding right.
58269    */
58270    Incrblob *pBlob;
58271    u32 type = v->apCsr[0]->aType[iCol];
58272
58273    if( type<12 ){
58274      sqlite3DbFree(db, zErr);
58275      zErr = sqlite3MPrintf(db, "cannot open value of type %s",
58276          type==0?"null": type==7?"real": "integer"
58277      );
58278      rc = SQLITE_ERROR;
58279      goto blob_open_out;
58280    }
58281    pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
58282    if( db->mallocFailed ){
58283      sqlite3DbFree(db, pBlob);
58284      goto blob_open_out;
58285    }
58286    pBlob->flags = flags;
58287    pBlob->pCsr =  v->apCsr[0]->pCursor;
58288    sqlite3BtreeEnterCursor(pBlob->pCsr);
58289    sqlite3BtreeCacheOverflow(pBlob->pCsr);
58290    sqlite3BtreeLeaveCursor(pBlob->pCsr);
58291    pBlob->pStmt = (sqlite3_stmt *)v;
58292    pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
58293    pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
58294    pBlob->db = db;
58295    *ppBlob = (sqlite3_blob *)pBlob;
58296    rc = SQLITE_OK;
58297  }else if( rc==SQLITE_OK ){
58298    sqlite3DbFree(db, zErr);
58299    zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
58300    rc = SQLITE_ERROR;
58301  }
58302
58303blob_open_out:
58304  if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
58305    sqlite3VdbeFinalize(v);
58306  }
58307  sqlite3Error(db, rc, zErr);
58308  sqlite3DbFree(db, zErr);
58309  sqlite3StackFree(db, pParse);
58310  rc = sqlite3ApiExit(db, rc);
58311  sqlite3_mutex_leave(db->mutex);
58312  return rc;
58313}
58314
58315/*
58316** Close a blob handle that was previously created using
58317** sqlite3_blob_open().
58318*/
58319SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
58320  Incrblob *p = (Incrblob *)pBlob;
58321  int rc;
58322  sqlite3 *db;
58323
58324  if( p ){
58325    db = p->db;
58326    sqlite3_mutex_enter(db->mutex);
58327    rc = sqlite3_finalize(p->pStmt);
58328    sqlite3DbFree(db, p);
58329    sqlite3_mutex_leave(db->mutex);
58330  }else{
58331    rc = SQLITE_OK;
58332  }
58333  return rc;
58334}
58335
58336/*
58337** Perform a read or write operation on a blob
58338*/
58339static int blobReadWrite(
58340  sqlite3_blob *pBlob,
58341  void *z,
58342  int n,
58343  int iOffset,
58344  int (*xCall)(BtCursor*, u32, u32, void*)
58345){
58346  int rc;
58347  Incrblob *p = (Incrblob *)pBlob;
58348  Vdbe *v;
58349  sqlite3 *db;
58350
58351  if( p==0 ) return SQLITE_MISUSE;
58352  db = p->db;
58353  sqlite3_mutex_enter(db->mutex);
58354  v = (Vdbe*)p->pStmt;
58355
58356  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
58357    /* Request is out of range. Return a transient error. */
58358    rc = SQLITE_ERROR;
58359    sqlite3Error(db, SQLITE_ERROR, 0);
58360  } else if( v==0 ){
58361    /* If there is no statement handle, then the blob-handle has
58362    ** already been invalidated. Return SQLITE_ABORT in this case.
58363    */
58364    rc = SQLITE_ABORT;
58365  }else{
58366    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
58367    ** returned, clean-up the statement handle.
58368    */
58369    assert( db == v->db );
58370    sqlite3BtreeEnterCursor(p->pCsr);
58371    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
58372    sqlite3BtreeLeaveCursor(p->pCsr);
58373    if( rc==SQLITE_ABORT ){
58374      sqlite3VdbeFinalize(v);
58375      p->pStmt = 0;
58376    }else{
58377      db->errCode = rc;
58378      v->rc = rc;
58379    }
58380  }
58381  rc = sqlite3ApiExit(db, rc);
58382  sqlite3_mutex_leave(db->mutex);
58383  return rc;
58384}
58385
58386/*
58387** Read data from a blob handle.
58388*/
58389SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
58390  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
58391}
58392
58393/*
58394** Write data to a blob handle.
58395*/
58396SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
58397  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
58398}
58399
58400/*
58401** Query a blob handle for the size of the data.
58402**
58403** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
58404** so no mutex is required for access.
58405*/
58406SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
58407  Incrblob *p = (Incrblob *)pBlob;
58408  return p ? p->nByte : 0;
58409}
58410
58411#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
58412
58413/************** End of vdbeblob.c ********************************************/
58414/************** Begin file journal.c *****************************************/
58415/*
58416** 2007 August 22
58417**
58418** The author disclaims copyright to this source code.  In place of
58419** a legal notice, here is a blessing:
58420**
58421**    May you do good and not evil.
58422**    May you find forgiveness for yourself and forgive others.
58423**    May you share freely, never taking more than you give.
58424**
58425*************************************************************************
58426**
58427** This file implements a special kind of sqlite3_file object used
58428** by SQLite to create journal files if the atomic-write optimization
58429** is enabled.
58430**
58431** The distinctive characteristic of this sqlite3_file is that the
58432** actual on disk file is created lazily. When the file is created,
58433** the caller specifies a buffer size for an in-memory buffer to
58434** be used to service read() and write() requests. The actual file
58435** on disk is not created or populated until either:
58436**
58437**   1) The in-memory representation grows too large for the allocated
58438**      buffer, or
58439**   2) The sqlite3JournalCreate() function is called.
58440*/
58441#ifdef SQLITE_ENABLE_ATOMIC_WRITE
58442
58443
58444/*
58445** A JournalFile object is a subclass of sqlite3_file used by
58446** as an open file handle for journal files.
58447*/
58448struct JournalFile {
58449  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
58450  int nBuf;                       /* Size of zBuf[] in bytes */
58451  char *zBuf;                     /* Space to buffer journal writes */
58452  int iSize;                      /* Amount of zBuf[] currently used */
58453  int flags;                      /* xOpen flags */
58454  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
58455  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
58456  const char *zJournal;           /* Name of the journal file */
58457};
58458typedef struct JournalFile JournalFile;
58459
58460/*
58461** If it does not already exists, create and populate the on-disk file
58462** for JournalFile p.
58463*/
58464static int createFile(JournalFile *p){
58465  int rc = SQLITE_OK;
58466  if( !p->pReal ){
58467    sqlite3_file *pReal = (sqlite3_file *)&p[1];
58468    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
58469    if( rc==SQLITE_OK ){
58470      p->pReal = pReal;
58471      if( p->iSize>0 ){
58472        assert(p->iSize<=p->nBuf);
58473        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
58474      }
58475    }
58476  }
58477  return rc;
58478}
58479
58480/*
58481** Close the file.
58482*/
58483static int jrnlClose(sqlite3_file *pJfd){
58484  JournalFile *p = (JournalFile *)pJfd;
58485  if( p->pReal ){
58486    sqlite3OsClose(p->pReal);
58487  }
58488  sqlite3_free(p->zBuf);
58489  return SQLITE_OK;
58490}
58491
58492/*
58493** Read data from the file.
58494*/
58495static int jrnlRead(
58496  sqlite3_file *pJfd,    /* The journal file from which to read */
58497  void *zBuf,            /* Put the results here */
58498  int iAmt,              /* Number of bytes to read */
58499  sqlite_int64 iOfst     /* Begin reading at this offset */
58500){
58501  int rc = SQLITE_OK;
58502  JournalFile *p = (JournalFile *)pJfd;
58503  if( p->pReal ){
58504    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
58505  }else if( (iAmt+iOfst)>p->iSize ){
58506    rc = SQLITE_IOERR_SHORT_READ;
58507  }else{
58508    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
58509  }
58510  return rc;
58511}
58512
58513/*
58514** Write data to the file.
58515*/
58516static int jrnlWrite(
58517  sqlite3_file *pJfd,    /* The journal file into which to write */
58518  const void *zBuf,      /* Take data to be written from here */
58519  int iAmt,              /* Number of bytes to write */
58520  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
58521){
58522  int rc = SQLITE_OK;
58523  JournalFile *p = (JournalFile *)pJfd;
58524  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
58525    rc = createFile(p);
58526  }
58527  if( rc==SQLITE_OK ){
58528    if( p->pReal ){
58529      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
58530    }else{
58531      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
58532      if( p->iSize<(iOfst+iAmt) ){
58533        p->iSize = (iOfst+iAmt);
58534      }
58535    }
58536  }
58537  return rc;
58538}
58539
58540/*
58541** Truncate the file.
58542*/
58543static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
58544  int rc = SQLITE_OK;
58545  JournalFile *p = (JournalFile *)pJfd;
58546  if( p->pReal ){
58547    rc = sqlite3OsTruncate(p->pReal, size);
58548  }else if( size<p->iSize ){
58549    p->iSize = size;
58550  }
58551  return rc;
58552}
58553
58554/*
58555** Sync the file.
58556*/
58557static int jrnlSync(sqlite3_file *pJfd, int flags){
58558  int rc;
58559  JournalFile *p = (JournalFile *)pJfd;
58560  if( p->pReal ){
58561    rc = sqlite3OsSync(p->pReal, flags);
58562  }else{
58563    rc = SQLITE_OK;
58564  }
58565  return rc;
58566}
58567
58568/*
58569** Query the size of the file in bytes.
58570*/
58571static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
58572  int rc = SQLITE_OK;
58573  JournalFile *p = (JournalFile *)pJfd;
58574  if( p->pReal ){
58575    rc = sqlite3OsFileSize(p->pReal, pSize);
58576  }else{
58577    *pSize = (sqlite_int64) p->iSize;
58578  }
58579  return rc;
58580}
58581
58582/*
58583** Table of methods for JournalFile sqlite3_file object.
58584*/
58585static struct sqlite3_io_methods JournalFileMethods = {
58586  1,             /* iVersion */
58587  jrnlClose,     /* xClose */
58588  jrnlRead,      /* xRead */
58589  jrnlWrite,     /* xWrite */
58590  jrnlTruncate,  /* xTruncate */
58591  jrnlSync,      /* xSync */
58592  jrnlFileSize,  /* xFileSize */
58593  0,             /* xLock */
58594  0,             /* xUnlock */
58595  0,             /* xCheckReservedLock */
58596  0,             /* xFileControl */
58597  0,             /* xSectorSize */
58598  0              /* xDeviceCharacteristics */
58599};
58600
58601/*
58602** Open a journal file.
58603*/
58604SQLITE_PRIVATE int sqlite3JournalOpen(
58605  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
58606  const char *zName,         /* Name of the journal file */
58607  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
58608  int flags,                 /* Opening flags */
58609  int nBuf                   /* Bytes buffered before opening the file */
58610){
58611  JournalFile *p = (JournalFile *)pJfd;
58612  memset(p, 0, sqlite3JournalSize(pVfs));
58613  if( nBuf>0 ){
58614    p->zBuf = sqlite3MallocZero(nBuf);
58615    if( !p->zBuf ){
58616      return SQLITE_NOMEM;
58617    }
58618  }else{
58619    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
58620  }
58621  p->pMethod = &JournalFileMethods;
58622  p->nBuf = nBuf;
58623  p->flags = flags;
58624  p->zJournal = zName;
58625  p->pVfs = pVfs;
58626  return SQLITE_OK;
58627}
58628
58629/*
58630** If the argument p points to a JournalFile structure, and the underlying
58631** file has not yet been created, create it now.
58632*/
58633SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
58634  if( p->pMethods!=&JournalFileMethods ){
58635    return SQLITE_OK;
58636  }
58637  return createFile((JournalFile *)p);
58638}
58639
58640/*
58641** Return the number of bytes required to store a JournalFile that uses vfs
58642** pVfs to create the underlying on-disk files.
58643*/
58644SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
58645  return (pVfs->szOsFile+sizeof(JournalFile));
58646}
58647#endif
58648
58649/************** End of journal.c *********************************************/
58650/************** Begin file memjournal.c **************************************/
58651/*
58652** 2008 October 7
58653**
58654** The author disclaims copyright to this source code.  In place of
58655** a legal notice, here is a blessing:
58656**
58657**    May you do good and not evil.
58658**    May you find forgiveness for yourself and forgive others.
58659**    May you share freely, never taking more than you give.
58660**
58661*************************************************************************
58662**
58663** This file contains code use to implement an in-memory rollback journal.
58664** The in-memory rollback journal is used to journal transactions for
58665** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
58666*/
58667
58668/* Forward references to internal structures */
58669typedef struct MemJournal MemJournal;
58670typedef struct FilePoint FilePoint;
58671typedef struct FileChunk FileChunk;
58672
58673/* Space to hold the rollback journal is allocated in increments of
58674** this many bytes.
58675**
58676** The size chosen is a little less than a power of two.  That way,
58677** the FileChunk object will have a size that almost exactly fills
58678** a power-of-two allocation.  This mimimizes wasted space in power-of-two
58679** memory allocators.
58680*/
58681#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
58682
58683/* Macro to find the minimum of two numeric values.
58684*/
58685#ifndef MIN
58686# define MIN(x,y) ((x)<(y)?(x):(y))
58687#endif
58688
58689/*
58690** The rollback journal is composed of a linked list of these structures.
58691*/
58692struct FileChunk {
58693  FileChunk *pNext;               /* Next chunk in the journal */
58694  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
58695};
58696
58697/*
58698** An instance of this object serves as a cursor into the rollback journal.
58699** The cursor can be either for reading or writing.
58700*/
58701struct FilePoint {
58702  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
58703  FileChunk *pChunk;              /* Specific chunk into which cursor points */
58704};
58705
58706/*
58707** This subclass is a subclass of sqlite3_file.  Each open memory-journal
58708** is an instance of this class.
58709*/
58710struct MemJournal {
58711  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
58712  FileChunk *pFirst;              /* Head of in-memory chunk-list */
58713  FilePoint endpoint;             /* Pointer to the end of the file */
58714  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
58715};
58716
58717/*
58718** Read data from the in-memory journal file.  This is the implementation
58719** of the sqlite3_vfs.xRead method.
58720*/
58721static int memjrnlRead(
58722  sqlite3_file *pJfd,    /* The journal file from which to read */
58723  void *zBuf,            /* Put the results here */
58724  int iAmt,              /* Number of bytes to read */
58725  sqlite_int64 iOfst     /* Begin reading at this offset */
58726){
58727  MemJournal *p = (MemJournal *)pJfd;
58728  u8 *zOut = zBuf;
58729  int nRead = iAmt;
58730  int iChunkOffset;
58731  FileChunk *pChunk;
58732
58733  /* SQLite never tries to read past the end of a rollback journal file */
58734  assert( iOfst+iAmt<=p->endpoint.iOffset );
58735
58736  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
58737    sqlite3_int64 iOff = 0;
58738    for(pChunk=p->pFirst;
58739        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
58740        pChunk=pChunk->pNext
58741    ){
58742      iOff += JOURNAL_CHUNKSIZE;
58743    }
58744  }else{
58745    pChunk = p->readpoint.pChunk;
58746  }
58747
58748  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
58749  do {
58750    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
58751    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
58752    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
58753    zOut += nCopy;
58754    nRead -= iSpace;
58755    iChunkOffset = 0;
58756  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
58757  p->readpoint.iOffset = iOfst+iAmt;
58758  p->readpoint.pChunk = pChunk;
58759
58760  return SQLITE_OK;
58761}
58762
58763/*
58764** Write data to the file.
58765*/
58766static int memjrnlWrite(
58767  sqlite3_file *pJfd,    /* The journal file into which to write */
58768  const void *zBuf,      /* Take data to be written from here */
58769  int iAmt,              /* Number of bytes to write */
58770  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
58771){
58772  MemJournal *p = (MemJournal *)pJfd;
58773  int nWrite = iAmt;
58774  u8 *zWrite = (u8 *)zBuf;
58775
58776  /* An in-memory journal file should only ever be appended to. Random
58777  ** access writes are not required by sqlite.
58778  */
58779  assert( iOfst==p->endpoint.iOffset );
58780  UNUSED_PARAMETER(iOfst);
58781
58782  while( nWrite>0 ){
58783    FileChunk *pChunk = p->endpoint.pChunk;
58784    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
58785    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
58786
58787    if( iChunkOffset==0 ){
58788      /* New chunk is required to extend the file. */
58789      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
58790      if( !pNew ){
58791        return SQLITE_IOERR_NOMEM;
58792      }
58793      pNew->pNext = 0;
58794      if( pChunk ){
58795        assert( p->pFirst );
58796        pChunk->pNext = pNew;
58797      }else{
58798        assert( !p->pFirst );
58799        p->pFirst = pNew;
58800      }
58801      p->endpoint.pChunk = pNew;
58802    }
58803
58804    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
58805    zWrite += iSpace;
58806    nWrite -= iSpace;
58807    p->endpoint.iOffset += iSpace;
58808  }
58809
58810  return SQLITE_OK;
58811}
58812
58813/*
58814** Truncate the file.
58815*/
58816static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
58817  MemJournal *p = (MemJournal *)pJfd;
58818  FileChunk *pChunk;
58819  assert(size==0);
58820  UNUSED_PARAMETER(size);
58821  pChunk = p->pFirst;
58822  while( pChunk ){
58823    FileChunk *pTmp = pChunk;
58824    pChunk = pChunk->pNext;
58825    sqlite3_free(pTmp);
58826  }
58827  sqlite3MemJournalOpen(pJfd);
58828  return SQLITE_OK;
58829}
58830
58831/*
58832** Close the file.
58833*/
58834static int memjrnlClose(sqlite3_file *pJfd){
58835  memjrnlTruncate(pJfd, 0);
58836  return SQLITE_OK;
58837}
58838
58839
58840/*
58841** Sync the file.
58842**
58843** Syncing an in-memory journal is a no-op.  And, in fact, this routine
58844** is never called in a working implementation.  This implementation
58845** exists purely as a contingency, in case some malfunction in some other
58846** part of SQLite causes Sync to be called by mistake.
58847*/
58848static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){   /*NO_TEST*/
58849  UNUSED_PARAMETER2(NotUsed, NotUsed2);                        /*NO_TEST*/
58850  assert( 0 );                                                 /*NO_TEST*/
58851  return SQLITE_OK;                                            /*NO_TEST*/
58852}                                                              /*NO_TEST*/
58853
58854/*
58855** Query the size of the file in bytes.
58856*/
58857static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
58858  MemJournal *p = (MemJournal *)pJfd;
58859  *pSize = (sqlite_int64) p->endpoint.iOffset;
58860  return SQLITE_OK;
58861}
58862
58863/*
58864** Table of methods for MemJournal sqlite3_file object.
58865*/
58866static struct sqlite3_io_methods MemJournalMethods = {
58867  1,                /* iVersion */
58868  memjrnlClose,     /* xClose */
58869  memjrnlRead,      /* xRead */
58870  memjrnlWrite,     /* xWrite */
58871  memjrnlTruncate,  /* xTruncate */
58872  memjrnlSync,      /* xSync */
58873  memjrnlFileSize,  /* xFileSize */
58874  0,                /* xLock */
58875  0,                /* xUnlock */
58876  0,                /* xCheckReservedLock */
58877  0,                /* xFileControl */
58878  0,                /* xSectorSize */
58879  0                 /* xDeviceCharacteristics */
58880};
58881
58882/*
58883** Open a journal file.
58884*/
58885SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
58886  MemJournal *p = (MemJournal *)pJfd;
58887  assert( EIGHT_BYTE_ALIGNMENT(p) );
58888  memset(p, 0, sqlite3MemJournalSize());
58889  p->pMethod = &MemJournalMethods;
58890}
58891
58892/*
58893** Return true if the file-handle passed as an argument is
58894** an in-memory journal
58895*/
58896SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
58897  return pJfd->pMethods==&MemJournalMethods;
58898}
58899
58900/*
58901** Return the number of bytes required to store a MemJournal that uses vfs
58902** pVfs to create the underlying on-disk files.
58903*/
58904SQLITE_PRIVATE int sqlite3MemJournalSize(void){
58905  return sizeof(MemJournal);
58906}
58907
58908/************** End of memjournal.c ******************************************/
58909/************** Begin file walker.c ******************************************/
58910/*
58911** 2008 August 16
58912**
58913** The author disclaims copyright to this source code.  In place of
58914** a legal notice, here is a blessing:
58915**
58916**    May you do good and not evil.
58917**    May you find forgiveness for yourself and forgive others.
58918**    May you share freely, never taking more than you give.
58919**
58920*************************************************************************
58921** This file contains routines used for walking the parser tree for
58922** an SQL statement.
58923*/
58924
58925
58926/*
58927** Walk an expression tree.  Invoke the callback once for each node
58928** of the expression, while decending.  (In other words, the callback
58929** is invoked before visiting children.)
58930**
58931** The return value from the callback should be one of the WRC_*
58932** constants to specify how to proceed with the walk.
58933**
58934**    WRC_Continue      Continue descending down the tree.
58935**
58936**    WRC_Prune         Do not descend into child nodes.  But allow
58937**                      the walk to continue with sibling nodes.
58938**
58939**    WRC_Abort         Do no more callbacks.  Unwind the stack and
58940**                      return the top-level walk call.
58941**
58942** The return value from this routine is WRC_Abort to abandon the tree walk
58943** and WRC_Continue to continue.
58944*/
58945SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
58946  int rc;
58947  if( pExpr==0 ) return WRC_Continue;
58948  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
58949  testcase( ExprHasProperty(pExpr, EP_Reduced) );
58950  rc = pWalker->xExprCallback(pWalker, pExpr);
58951  if( rc==WRC_Continue
58952              && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
58953    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
58954    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
58955    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
58956      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
58957    }else{
58958      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
58959    }
58960  }
58961  return rc & WRC_Abort;
58962}
58963
58964/*
58965** Call sqlite3WalkExpr() for every expression in list p or until
58966** an abort request is seen.
58967*/
58968SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
58969  int i;
58970  struct ExprList_item *pItem;
58971  if( p ){
58972    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
58973      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
58974    }
58975  }
58976  return WRC_Continue;
58977}
58978
58979/*
58980** Walk all expressions associated with SELECT statement p.  Do
58981** not invoke the SELECT callback on p, but do (of course) invoke
58982** any expr callbacks and SELECT callbacks that come from subqueries.
58983** Return WRC_Abort or WRC_Continue.
58984*/
58985SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
58986  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
58987  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
58988  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
58989  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
58990  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
58991  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
58992  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
58993  return WRC_Continue;
58994}
58995
58996/*
58997** Walk the parse trees associated with all subqueries in the
58998** FROM clause of SELECT statement p.  Do not invoke the select
58999** callback on p, but do invoke it on each FROM clause subquery
59000** and on any subqueries further down in the tree.  Return
59001** WRC_Abort or WRC_Continue;
59002*/
59003SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
59004  SrcList *pSrc;
59005  int i;
59006  struct SrcList_item *pItem;
59007
59008  pSrc = p->pSrc;
59009  if( ALWAYS(pSrc) ){
59010    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
59011      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
59012        return WRC_Abort;
59013      }
59014    }
59015  }
59016  return WRC_Continue;
59017}
59018
59019/*
59020** Call sqlite3WalkExpr() for every expression in Select statement p.
59021** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
59022** on the compound select chain, p->pPrior.
59023**
59024** Return WRC_Continue under normal conditions.  Return WRC_Abort if
59025** there is an abort request.
59026**
59027** If the Walker does not have an xSelectCallback() then this routine
59028** is a no-op returning WRC_Continue.
59029*/
59030SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
59031  int rc;
59032  if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
59033  rc = WRC_Continue;
59034  while( p  ){
59035    rc = pWalker->xSelectCallback(pWalker, p);
59036    if( rc ) break;
59037    if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
59038    if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
59039    p = p->pPrior;
59040  }
59041  return rc & WRC_Abort;
59042}
59043
59044/************** End of walker.c **********************************************/
59045/************** Begin file resolve.c *****************************************/
59046/*
59047** 2008 August 18
59048**
59049** The author disclaims copyright to this source code.  In place of
59050** a legal notice, here is a blessing:
59051**
59052**    May you do good and not evil.
59053**    May you find forgiveness for yourself and forgive others.
59054**    May you share freely, never taking more than you give.
59055**
59056*************************************************************************
59057**
59058** This file contains routines used for walking the parser tree and
59059** resolve all identifiers by associating them with a particular
59060** table and column.
59061*/
59062
59063/*
59064** Turn the pExpr expression into an alias for the iCol-th column of the
59065** result set in pEList.
59066**
59067** If the result set column is a simple column reference, then this routine
59068** makes an exact copy.  But for any other kind of expression, this
59069** routine make a copy of the result set column as the argument to the
59070** TK_AS operator.  The TK_AS operator causes the expression to be
59071** evaluated just once and then reused for each alias.
59072**
59073** The reason for suppressing the TK_AS term when the expression is a simple
59074** column reference is so that the column reference will be recognized as
59075** usable by indices within the WHERE clause processing logic.
59076**
59077** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
59078** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
59079**
59080**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
59081**
59082** Is equivalent to:
59083**
59084**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
59085**
59086** The result of random()%5 in the GROUP BY clause is probably different
59087** from the result in the result-set.  We might fix this someday.  Or
59088** then again, we might not...
59089*/
59090static void resolveAlias(
59091  Parse *pParse,         /* Parsing context */
59092  ExprList *pEList,      /* A result set */
59093  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
59094  Expr *pExpr,           /* Transform this into an alias to the result set */
59095  const char *zType      /* "GROUP" or "ORDER" or "" */
59096){
59097  Expr *pOrig;           /* The iCol-th column of the result set */
59098  Expr *pDup;            /* Copy of pOrig */
59099  sqlite3 *db;           /* The database connection */
59100
59101  assert( iCol>=0 && iCol<pEList->nExpr );
59102  pOrig = pEList->a[iCol].pExpr;
59103  assert( pOrig!=0 );
59104  assert( pOrig->flags & EP_Resolved );
59105  db = pParse->db;
59106  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
59107    pDup = sqlite3ExprDup(db, pOrig, 0);
59108    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
59109    if( pDup==0 ) return;
59110    if( pEList->a[iCol].iAlias==0 ){
59111      pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
59112    }
59113    pDup->iTable = pEList->a[iCol].iAlias;
59114  }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
59115    pDup = sqlite3ExprDup(db, pOrig, 0);
59116    if( pDup==0 ) return;
59117  }else{
59118    char *zToken = pOrig->u.zToken;
59119    assert( zToken!=0 );
59120    pOrig->u.zToken = 0;
59121    pDup = sqlite3ExprDup(db, pOrig, 0);
59122    pOrig->u.zToken = zToken;
59123    if( pDup==0 ) return;
59124    assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
59125    pDup->flags2 |= EP2_MallocedToken;
59126    pDup->u.zToken = sqlite3DbStrDup(db, zToken);
59127  }
59128  if( pExpr->flags & EP_ExpCollate ){
59129    pDup->pColl = pExpr->pColl;
59130    pDup->flags |= EP_ExpCollate;
59131  }
59132
59133  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
59134  ** prevents ExprDelete() from deleting the Expr structure itself,
59135  ** allowing it to be repopulated by the memcpy() on the following line.
59136  */
59137  ExprSetProperty(pExpr, EP_Static);
59138  sqlite3ExprDelete(db, pExpr);
59139  memcpy(pExpr, pDup, sizeof(*pExpr));
59140  sqlite3DbFree(db, pDup);
59141}
59142
59143/*
59144** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
59145** that name in the set of source tables in pSrcList and make the pExpr
59146** expression node refer back to that source column.  The following changes
59147** are made to pExpr:
59148**
59149**    pExpr->iDb           Set the index in db->aDb[] of the database X
59150**                         (even if X is implied).
59151**    pExpr->iTable        Set to the cursor number for the table obtained
59152**                         from pSrcList.
59153**    pExpr->pTab          Points to the Table structure of X.Y (even if
59154**                         X and/or Y are implied.)
59155**    pExpr->iColumn       Set to the column number within the table.
59156**    pExpr->op            Set to TK_COLUMN.
59157**    pExpr->pLeft         Any expression this points to is deleted
59158**    pExpr->pRight        Any expression this points to is deleted.
59159**
59160** The zDb variable is the name of the database (the "X").  This value may be
59161** NULL meaning that name is of the form Y.Z or Z.  Any available database
59162** can be used.  The zTable variable is the name of the table (the "Y").  This
59163** value can be NULL if zDb is also NULL.  If zTable is NULL it
59164** means that the form of the name is Z and that columns from any table
59165** can be used.
59166**
59167** If the name cannot be resolved unambiguously, leave an error message
59168** in pParse and return WRC_Abort.  Return WRC_Prune on success.
59169*/
59170static int lookupName(
59171  Parse *pParse,       /* The parsing context */
59172  const char *zDb,     /* Name of the database containing table, or NULL */
59173  const char *zTab,    /* Name of table containing column, or NULL */
59174  const char *zCol,    /* Name of the column. */
59175  NameContext *pNC,    /* The name context used to resolve the name */
59176  Expr *pExpr          /* Make this EXPR node point to the selected column */
59177){
59178  int i, j;            /* Loop counters */
59179  int cnt = 0;                      /* Number of matching column names */
59180  int cntTab = 0;                   /* Number of matching table names */
59181  sqlite3 *db = pParse->db;         /* The database connection */
59182  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
59183  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
59184  NameContext *pTopNC = pNC;        /* First namecontext in the list */
59185  Schema *pSchema = 0;              /* Schema of the expression */
59186  int isTrigger = 0;
59187
59188  assert( pNC );     /* the name context cannot be NULL. */
59189  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
59190  assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
59191
59192  /* Initialize the node to no-match */
59193  pExpr->iTable = -1;
59194  pExpr->pTab = 0;
59195  ExprSetIrreducible(pExpr);
59196
59197  /* Start at the inner-most context and move outward until a match is found */
59198  while( pNC && cnt==0 ){
59199    ExprList *pEList;
59200    SrcList *pSrcList = pNC->pSrcList;
59201
59202    if( pSrcList ){
59203      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
59204        Table *pTab;
59205        int iDb;
59206        Column *pCol;
59207
59208        pTab = pItem->pTab;
59209        assert( pTab!=0 && pTab->zName!=0 );
59210        iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
59211        assert( pTab->nCol>0 );
59212        if( zTab ){
59213          if( pItem->zAlias ){
59214            char *zTabName = pItem->zAlias;
59215            if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
59216          }else{
59217            char *zTabName = pTab->zName;
59218            if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
59219              continue;
59220            }
59221            if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
59222              continue;
59223            }
59224          }
59225        }
59226        if( 0==(cntTab++) ){
59227          pExpr->iTable = pItem->iCursor;
59228          pExpr->pTab = pTab;
59229          pSchema = pTab->pSchema;
59230          pMatch = pItem;
59231        }
59232        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
59233          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
59234            IdList *pUsing;
59235            cnt++;
59236            pExpr->iTable = pItem->iCursor;
59237            pExpr->pTab = pTab;
59238            pMatch = pItem;
59239            pSchema = pTab->pSchema;
59240            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
59241            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
59242            if( i<pSrcList->nSrc-1 ){
59243              if( pItem[1].jointype & JT_NATURAL ){
59244                /* If this match occurred in the left table of a natural join,
59245                ** then skip the right table to avoid a duplicate match */
59246                pItem++;
59247                i++;
59248              }else if( (pUsing = pItem[1].pUsing)!=0 ){
59249                /* If this match occurs on a column that is in the USING clause
59250                ** of a join, skip the search of the right table of the join
59251                ** to avoid a duplicate match there. */
59252                int k;
59253                for(k=0; k<pUsing->nId; k++){
59254                  if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
59255                    pItem++;
59256                    i++;
59257                    break;
59258                  }
59259                }
59260              }
59261            }
59262            break;
59263          }
59264        }
59265      }
59266    }
59267
59268#ifndef SQLITE_OMIT_TRIGGER
59269    /* If we have not already resolved the name, then maybe
59270    ** it is a new.* or old.* trigger argument reference
59271    */
59272    if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
59273      int op = pParse->eTriggerOp;
59274      Table *pTab = 0;
59275      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
59276      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
59277        pExpr->iTable = 1;
59278        pTab = pParse->pTriggerTab;
59279      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
59280        pExpr->iTable = 0;
59281        pTab = pParse->pTriggerTab;
59282      }
59283
59284      if( pTab ){
59285        int iCol;
59286        pSchema = pTab->pSchema;
59287        cntTab++;
59288        for(iCol=0; iCol<pTab->nCol; iCol++){
59289          Column *pCol = &pTab->aCol[iCol];
59290          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
59291            if( iCol==pTab->iPKey ){
59292              iCol = -1;
59293            }
59294            break;
59295          }
59296        }
59297        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
59298          iCol = -1;        /* IMP: R-44911-55124 */
59299        }
59300        if( iCol<pTab->nCol ){
59301          cnt++;
59302          if( iCol<0 ){
59303            pExpr->affinity = SQLITE_AFF_INTEGER;
59304          }else if( pExpr->iTable==0 ){
59305            testcase( iCol==31 );
59306            testcase( iCol==32 );
59307            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
59308          }else{
59309            testcase( iCol==31 );
59310            testcase( iCol==32 );
59311            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
59312          }
59313          pExpr->iColumn = (i16)iCol;
59314          pExpr->pTab = pTab;
59315          isTrigger = 1;
59316        }
59317      }
59318    }
59319#endif /* !defined(SQLITE_OMIT_TRIGGER) */
59320
59321    /*
59322    ** Perhaps the name is a reference to the ROWID
59323    */
59324    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
59325      cnt = 1;
59326      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
59327      pExpr->affinity = SQLITE_AFF_INTEGER;
59328    }
59329
59330    /*
59331    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
59332    ** might refer to an result-set alias.  This happens, for example, when
59333    ** we are resolving names in the WHERE clause of the following command:
59334    **
59335    **     SELECT a+b AS x FROM table WHERE x<10;
59336    **
59337    ** In cases like this, replace pExpr with a copy of the expression that
59338    ** forms the result set entry ("a+b" in the example) and return immediately.
59339    ** Note that the expression in the result set should have already been
59340    ** resolved by the time the WHERE clause is resolved.
59341    */
59342    if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
59343      for(j=0; j<pEList->nExpr; j++){
59344        char *zAs = pEList->a[j].zName;
59345        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
59346          Expr *pOrig;
59347          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
59348          assert( pExpr->x.pList==0 );
59349          assert( pExpr->x.pSelect==0 );
59350          pOrig = pEList->a[j].pExpr;
59351          if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
59352            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
59353            return WRC_Abort;
59354          }
59355          resolveAlias(pParse, pEList, j, pExpr, "");
59356          cnt = 1;
59357          pMatch = 0;
59358          assert( zTab==0 && zDb==0 );
59359          goto lookupname_end;
59360        }
59361      }
59362    }
59363
59364    /* Advance to the next name context.  The loop will exit when either
59365    ** we have a match (cnt>0) or when we run out of name contexts.
59366    */
59367    if( cnt==0 ){
59368      pNC = pNC->pNext;
59369    }
59370  }
59371
59372  /*
59373  ** If X and Y are NULL (in other words if only the column name Z is
59374  ** supplied) and the value of Z is enclosed in double-quotes, then
59375  ** Z is a string literal if it doesn't match any column names.  In that
59376  ** case, we need to return right away and not make any changes to
59377  ** pExpr.
59378  **
59379  ** Because no reference was made to outer contexts, the pNC->nRef
59380  ** fields are not changed in any context.
59381  */
59382  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
59383    pExpr->op = TK_STRING;
59384    pExpr->pTab = 0;
59385    return WRC_Prune;
59386  }
59387
59388  /*
59389  ** cnt==0 means there was not match.  cnt>1 means there were two or
59390  ** more matches.  Either way, we have an error.
59391  */
59392  if( cnt!=1 ){
59393    const char *zErr;
59394    zErr = cnt==0 ? "no such column" : "ambiguous column name";
59395    if( zDb ){
59396      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
59397    }else if( zTab ){
59398      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
59399    }else{
59400      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
59401    }
59402    pTopNC->nErr++;
59403  }
59404
59405  /* If a column from a table in pSrcList is referenced, then record
59406  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
59407  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
59408  ** column number is greater than the number of bits in the bitmask
59409  ** then set the high-order bit of the bitmask.
59410  */
59411  if( pExpr->iColumn>=0 && pMatch!=0 ){
59412    int n = pExpr->iColumn;
59413    testcase( n==BMS-1 );
59414    if( n>=BMS ){
59415      n = BMS-1;
59416    }
59417    assert( pMatch->iCursor==pExpr->iTable );
59418    pMatch->colUsed |= ((Bitmask)1)<<n;
59419  }
59420
59421  /* Clean up and return
59422  */
59423  sqlite3ExprDelete(db, pExpr->pLeft);
59424  pExpr->pLeft = 0;
59425  sqlite3ExprDelete(db, pExpr->pRight);
59426  pExpr->pRight = 0;
59427  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
59428lookupname_end:
59429  if( cnt==1 ){
59430    assert( pNC!=0 );
59431    sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
59432    /* Increment the nRef value on all name contexts from TopNC up to
59433    ** the point where the name matched. */
59434    for(;;){
59435      assert( pTopNC!=0 );
59436      pTopNC->nRef++;
59437      if( pTopNC==pNC ) break;
59438      pTopNC = pTopNC->pNext;
59439    }
59440    return WRC_Prune;
59441  } else {
59442    return WRC_Abort;
59443  }
59444}
59445
59446/*
59447** Allocate and return a pointer to an expression to load the column iCol
59448** from datasource iSrc datasource in SrcList pSrc.
59449*/
59450SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
59451  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
59452  if( p ){
59453    struct SrcList_item *pItem = &pSrc->a[iSrc];
59454    p->pTab = pItem->pTab;
59455    p->iTable = pItem->iCursor;
59456    if( p->pTab->iPKey==iCol ){
59457      p->iColumn = -1;
59458    }else{
59459      p->iColumn = (ynVar)iCol;
59460      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
59461    }
59462    ExprSetProperty(p, EP_Resolved);
59463  }
59464  return p;
59465}
59466
59467/*
59468** This routine is callback for sqlite3WalkExpr().
59469**
59470** Resolve symbolic names into TK_COLUMN operators for the current
59471** node in the expression tree.  Return 0 to continue the search down
59472** the tree or 2 to abort the tree walk.
59473**
59474** This routine also does error checking and name resolution for
59475** function names.  The operator for aggregate functions is changed
59476** to TK_AGG_FUNCTION.
59477*/
59478static int resolveExprStep(Walker *pWalker, Expr *pExpr){
59479  NameContext *pNC;
59480  Parse *pParse;
59481
59482  pNC = pWalker->u.pNC;
59483  assert( pNC!=0 );
59484  pParse = pNC->pParse;
59485  assert( pParse==pWalker->pParse );
59486
59487  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
59488  ExprSetProperty(pExpr, EP_Resolved);
59489#ifndef NDEBUG
59490  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
59491    SrcList *pSrcList = pNC->pSrcList;
59492    int i;
59493    for(i=0; i<pNC->pSrcList->nSrc; i++){
59494      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
59495    }
59496  }
59497#endif
59498  switch( pExpr->op ){
59499
59500#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
59501    /* The special operator TK_ROW means use the rowid for the first
59502    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
59503    ** clause processing on UPDATE and DELETE statements.
59504    */
59505    case TK_ROW: {
59506      SrcList *pSrcList = pNC->pSrcList;
59507      struct SrcList_item *pItem;
59508      assert( pSrcList && pSrcList->nSrc==1 );
59509      pItem = pSrcList->a;
59510      pExpr->op = TK_COLUMN;
59511      pExpr->pTab = pItem->pTab;
59512      pExpr->iTable = pItem->iCursor;
59513      pExpr->iColumn = -1;
59514      pExpr->affinity = SQLITE_AFF_INTEGER;
59515      break;
59516    }
59517#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
59518
59519    /* A lone identifier is the name of a column.
59520    */
59521    case TK_ID: {
59522      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
59523    }
59524
59525    /* A table name and column name:     ID.ID
59526    ** Or a database, table and column:  ID.ID.ID
59527    */
59528    case TK_DOT: {
59529      const char *zColumn;
59530      const char *zTable;
59531      const char *zDb;
59532      Expr *pRight;
59533
59534      /* if( pSrcList==0 ) break; */
59535      pRight = pExpr->pRight;
59536      if( pRight->op==TK_ID ){
59537        zDb = 0;
59538        zTable = pExpr->pLeft->u.zToken;
59539        zColumn = pRight->u.zToken;
59540      }else{
59541        assert( pRight->op==TK_DOT );
59542        zDb = pExpr->pLeft->u.zToken;
59543        zTable = pRight->pLeft->u.zToken;
59544        zColumn = pRight->pRight->u.zToken;
59545      }
59546      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
59547    }
59548
59549    /* Resolve function names
59550    */
59551    case TK_CONST_FUNC:
59552    case TK_FUNCTION: {
59553      ExprList *pList = pExpr->x.pList;    /* The argument list */
59554      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
59555      int no_such_func = 0;       /* True if no such function exists */
59556      int wrong_num_args = 0;     /* True if wrong number of arguments */
59557      int is_agg = 0;             /* True if is an aggregate function */
59558      int auth;                   /* Authorization to use the function */
59559      int nId;                    /* Number of characters in function name */
59560      const char *zId;            /* The function name. */
59561      FuncDef *pDef;              /* Information about the function */
59562      u8 enc = ENC(pParse->db);   /* The database encoding */
59563
59564      testcase( pExpr->op==TK_CONST_FUNC );
59565      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
59566      zId = pExpr->u.zToken;
59567      nId = sqlite3Strlen30(zId);
59568      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
59569      if( pDef==0 ){
59570        pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
59571        if( pDef==0 ){
59572          no_such_func = 1;
59573        }else{
59574          wrong_num_args = 1;
59575        }
59576      }else{
59577        is_agg = pDef->xFunc==0;
59578      }
59579#ifndef SQLITE_OMIT_AUTHORIZATION
59580      if( pDef ){
59581        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
59582        if( auth!=SQLITE_OK ){
59583          if( auth==SQLITE_DENY ){
59584            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
59585                                    pDef->zName);
59586            pNC->nErr++;
59587          }
59588          pExpr->op = TK_NULL;
59589          return WRC_Prune;
59590        }
59591      }
59592#endif
59593      if( is_agg && !pNC->allowAgg ){
59594        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
59595        pNC->nErr++;
59596        is_agg = 0;
59597      }else if( no_such_func ){
59598        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
59599        pNC->nErr++;
59600      }else if( wrong_num_args ){
59601        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
59602             nId, zId);
59603        pNC->nErr++;
59604      }
59605      if( is_agg ){
59606        pExpr->op = TK_AGG_FUNCTION;
59607        pNC->hasAgg = 1;
59608      }
59609      if( is_agg ) pNC->allowAgg = 0;
59610      sqlite3WalkExprList(pWalker, pList);
59611      if( is_agg ) pNC->allowAgg = 1;
59612      /* FIX ME:  Compute pExpr->affinity based on the expected return
59613      ** type of the function
59614      */
59615      return WRC_Prune;
59616    }
59617#ifndef SQLITE_OMIT_SUBQUERY
59618    case TK_SELECT:
59619    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
59620#endif
59621    case TK_IN: {
59622      testcase( pExpr->op==TK_IN );
59623      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
59624        int nRef = pNC->nRef;
59625#ifndef SQLITE_OMIT_CHECK
59626        if( pNC->isCheck ){
59627          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
59628        }
59629#endif
59630        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
59631        assert( pNC->nRef>=nRef );
59632        if( nRef!=pNC->nRef ){
59633          ExprSetProperty(pExpr, EP_VarSelect);
59634        }
59635      }
59636      break;
59637    }
59638#ifndef SQLITE_OMIT_CHECK
59639    case TK_VARIABLE: {
59640      if( pNC->isCheck ){
59641        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
59642      }
59643      break;
59644    }
59645#endif
59646  }
59647  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
59648}
59649
59650/*
59651** pEList is a list of expressions which are really the result set of the
59652** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
59653** This routine checks to see if pE is a simple identifier which corresponds
59654** to the AS-name of one of the terms of the expression list.  If it is,
59655** this routine return an integer between 1 and N where N is the number of
59656** elements in pEList, corresponding to the matching entry.  If there is
59657** no match, or if pE is not a simple identifier, then this routine
59658** return 0.
59659**
59660** pEList has been resolved.  pE has not.
59661*/
59662static int resolveAsName(
59663  Parse *pParse,     /* Parsing context for error messages */
59664  ExprList *pEList,  /* List of expressions to scan */
59665  Expr *pE           /* Expression we are trying to match */
59666){
59667  int i;             /* Loop counter */
59668
59669  UNUSED_PARAMETER(pParse);
59670
59671  if( pE->op==TK_ID ){
59672    char *zCol = pE->u.zToken;
59673    for(i=0; i<pEList->nExpr; i++){
59674      char *zAs = pEList->a[i].zName;
59675      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
59676        return i+1;
59677      }
59678    }
59679  }
59680  return 0;
59681}
59682
59683/*
59684** pE is a pointer to an expression which is a single term in the
59685** ORDER BY of a compound SELECT.  The expression has not been
59686** name resolved.
59687**
59688** At the point this routine is called, we already know that the
59689** ORDER BY term is not an integer index into the result set.  That
59690** case is handled by the calling routine.
59691**
59692** Attempt to match pE against result set columns in the left-most
59693** SELECT statement.  Return the index i of the matching column,
59694** as an indication to the caller that it should sort by the i-th column.
59695** The left-most column is 1.  In other words, the value returned is the
59696** same integer value that would be used in the SQL statement to indicate
59697** the column.
59698**
59699** If there is no match, return 0.  Return -1 if an error occurs.
59700*/
59701static int resolveOrderByTermToExprList(
59702  Parse *pParse,     /* Parsing context for error messages */
59703  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
59704  Expr *pE           /* The specific ORDER BY term */
59705){
59706  int i;             /* Loop counter */
59707  ExprList *pEList;  /* The columns of the result set */
59708  NameContext nc;    /* Name context for resolving pE */
59709
59710  assert( sqlite3ExprIsInteger(pE, &i)==0 );
59711  pEList = pSelect->pEList;
59712
59713  /* Resolve all names in the ORDER BY term expression
59714  */
59715  memset(&nc, 0, sizeof(nc));
59716  nc.pParse = pParse;
59717  nc.pSrcList = pSelect->pSrc;
59718  nc.pEList = pEList;
59719  nc.allowAgg = 1;
59720  nc.nErr = 0;
59721  if( sqlite3ResolveExprNames(&nc, pE) ){
59722    sqlite3ErrorClear(pParse);
59723    return 0;
59724  }
59725
59726  /* Try to match the ORDER BY expression against an expression
59727  ** in the result set.  Return an 1-based index of the matching
59728  ** result-set entry.
59729  */
59730  for(i=0; i<pEList->nExpr; i++){
59731    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
59732      return i+1;
59733    }
59734  }
59735
59736  /* If no match, return 0. */
59737  return 0;
59738}
59739
59740/*
59741** Generate an ORDER BY or GROUP BY term out-of-range error.
59742*/
59743static void resolveOutOfRangeError(
59744  Parse *pParse,         /* The error context into which to write the error */
59745  const char *zType,     /* "ORDER" or "GROUP" */
59746  int i,                 /* The index (1-based) of the term out of range */
59747  int mx                 /* Largest permissible value of i */
59748){
59749  sqlite3ErrorMsg(pParse,
59750    "%r %s BY term out of range - should be "
59751    "between 1 and %d", i, zType, mx);
59752}
59753
59754/*
59755** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
59756** each term of the ORDER BY clause is a constant integer between 1
59757** and N where N is the number of columns in the compound SELECT.
59758**
59759** ORDER BY terms that are already an integer between 1 and N are
59760** unmodified.  ORDER BY terms that are integers outside the range of
59761** 1 through N generate an error.  ORDER BY terms that are expressions
59762** are matched against result set expressions of compound SELECT
59763** beginning with the left-most SELECT and working toward the right.
59764** At the first match, the ORDER BY expression is transformed into
59765** the integer column number.
59766**
59767** Return the number of errors seen.
59768*/
59769static int resolveCompoundOrderBy(
59770  Parse *pParse,        /* Parsing context.  Leave error messages here */
59771  Select *pSelect       /* The SELECT statement containing the ORDER BY */
59772){
59773  int i;
59774  ExprList *pOrderBy;
59775  ExprList *pEList;
59776  sqlite3 *db;
59777  int moreToDo = 1;
59778
59779  pOrderBy = pSelect->pOrderBy;
59780  if( pOrderBy==0 ) return 0;
59781  db = pParse->db;
59782#if SQLITE_MAX_COLUMN
59783  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
59784    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
59785    return 1;
59786  }
59787#endif
59788  for(i=0; i<pOrderBy->nExpr; i++){
59789    pOrderBy->a[i].done = 0;
59790  }
59791  pSelect->pNext = 0;
59792  while( pSelect->pPrior ){
59793    pSelect->pPrior->pNext = pSelect;
59794    pSelect = pSelect->pPrior;
59795  }
59796  while( pSelect && moreToDo ){
59797    struct ExprList_item *pItem;
59798    moreToDo = 0;
59799    pEList = pSelect->pEList;
59800    assert( pEList!=0 );
59801    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
59802      int iCol = -1;
59803      Expr *pE, *pDup;
59804      if( pItem->done ) continue;
59805      pE = pItem->pExpr;
59806      if( sqlite3ExprIsInteger(pE, &iCol) ){
59807        if( iCol<=0 || iCol>pEList->nExpr ){
59808          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
59809          return 1;
59810        }
59811      }else{
59812        iCol = resolveAsName(pParse, pEList, pE);
59813        if( iCol==0 ){
59814          pDup = sqlite3ExprDup(db, pE, 0);
59815          if( !db->mallocFailed ){
59816            assert(pDup);
59817            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
59818          }
59819          sqlite3ExprDelete(db, pDup);
59820        }
59821      }
59822      if( iCol>0 ){
59823        CollSeq *pColl = pE->pColl;
59824        int flags = pE->flags & EP_ExpCollate;
59825        sqlite3ExprDelete(db, pE);
59826        pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
59827        if( pE==0 ) return 1;
59828        pE->pColl = pColl;
59829        pE->flags |= EP_IntValue | flags;
59830        pE->u.iValue = iCol;
59831        pItem->iCol = (u16)iCol;
59832        pItem->done = 1;
59833      }else{
59834        moreToDo = 1;
59835      }
59836    }
59837    pSelect = pSelect->pNext;
59838  }
59839  for(i=0; i<pOrderBy->nExpr; i++){
59840    if( pOrderBy->a[i].done==0 ){
59841      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
59842            "column in the result set", i+1);
59843      return 1;
59844    }
59845  }
59846  return 0;
59847}
59848
59849/*
59850** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
59851** the SELECT statement pSelect.  If any term is reference to a
59852** result set expression (as determined by the ExprList.a.iCol field)
59853** then convert that term into a copy of the corresponding result set
59854** column.
59855**
59856** If any errors are detected, add an error message to pParse and
59857** return non-zero.  Return zero if no errors are seen.
59858*/
59859SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
59860  Parse *pParse,        /* Parsing context.  Leave error messages here */
59861  Select *pSelect,      /* The SELECT statement containing the clause */
59862  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
59863  const char *zType     /* "ORDER" or "GROUP" */
59864){
59865  int i;
59866  sqlite3 *db = pParse->db;
59867  ExprList *pEList;
59868  struct ExprList_item *pItem;
59869
59870  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
59871#if SQLITE_MAX_COLUMN
59872  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
59873    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
59874    return 1;
59875  }
59876#endif
59877  pEList = pSelect->pEList;
59878  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
59879  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
59880    if( pItem->iCol ){
59881      if( pItem->iCol>pEList->nExpr ){
59882        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
59883        return 1;
59884      }
59885      resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
59886    }
59887  }
59888  return 0;
59889}
59890
59891/*
59892** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
59893** The Name context of the SELECT statement is pNC.  zType is either
59894** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
59895**
59896** This routine resolves each term of the clause into an expression.
59897** If the order-by term is an integer I between 1 and N (where N is the
59898** number of columns in the result set of the SELECT) then the expression
59899** in the resolution is a copy of the I-th result-set expression.  If
59900** the order-by term is an identify that corresponds to the AS-name of
59901** a result-set expression, then the term resolves to a copy of the
59902** result-set expression.  Otherwise, the expression is resolved in
59903** the usual way - using sqlite3ResolveExprNames().
59904**
59905** This routine returns the number of errors.  If errors occur, then
59906** an appropriate error message might be left in pParse.  (OOM errors
59907** excepted.)
59908*/
59909static int resolveOrderGroupBy(
59910  NameContext *pNC,     /* The name context of the SELECT statement */
59911  Select *pSelect,      /* The SELECT statement holding pOrderBy */
59912  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
59913  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
59914){
59915  int i;                         /* Loop counter */
59916  int iCol;                      /* Column number */
59917  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
59918  Parse *pParse;                 /* Parsing context */
59919  int nResult;                   /* Number of terms in the result set */
59920
59921  if( pOrderBy==0 ) return 0;
59922  nResult = pSelect->pEList->nExpr;
59923  pParse = pNC->pParse;
59924  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
59925    Expr *pE = pItem->pExpr;
59926    iCol = resolveAsName(pParse, pSelect->pEList, pE);
59927    if( iCol>0 ){
59928      /* If an AS-name match is found, mark this ORDER BY column as being
59929      ** a copy of the iCol-th result-set column.  The subsequent call to
59930      ** sqlite3ResolveOrderGroupBy() will convert the expression to a
59931      ** copy of the iCol-th result-set expression. */
59932      pItem->iCol = (u16)iCol;
59933      continue;
59934    }
59935    if( sqlite3ExprIsInteger(pE, &iCol) ){
59936      /* The ORDER BY term is an integer constant.  Again, set the column
59937      ** number so that sqlite3ResolveOrderGroupBy() will convert the
59938      ** order-by term to a copy of the result-set expression */
59939      if( iCol<1 ){
59940        resolveOutOfRangeError(pParse, zType, i+1, nResult);
59941        return 1;
59942      }
59943      pItem->iCol = (u16)iCol;
59944      continue;
59945    }
59946
59947    /* Otherwise, treat the ORDER BY term as an ordinary expression */
59948    pItem->iCol = 0;
59949    if( sqlite3ResolveExprNames(pNC, pE) ){
59950      return 1;
59951    }
59952  }
59953  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
59954}
59955
59956/*
59957** Resolve names in the SELECT statement p and all of its descendents.
59958*/
59959static int resolveSelectStep(Walker *pWalker, Select *p){
59960  NameContext *pOuterNC;  /* Context that contains this SELECT */
59961  NameContext sNC;        /* Name context of this SELECT */
59962  int isCompound;         /* True if p is a compound select */
59963  int nCompound;          /* Number of compound terms processed so far */
59964  Parse *pParse;          /* Parsing context */
59965  ExprList *pEList;       /* Result set expression list */
59966  int i;                  /* Loop counter */
59967  ExprList *pGroupBy;     /* The GROUP BY clause */
59968  Select *pLeftmost;      /* Left-most of SELECT of a compound */
59969  sqlite3 *db;            /* Database connection */
59970
59971
59972  assert( p!=0 );
59973  if( p->selFlags & SF_Resolved ){
59974    return WRC_Prune;
59975  }
59976  pOuterNC = pWalker->u.pNC;
59977  pParse = pWalker->pParse;
59978  db = pParse->db;
59979
59980  /* Normally sqlite3SelectExpand() will be called first and will have
59981  ** already expanded this SELECT.  However, if this is a subquery within
59982  ** an expression, sqlite3ResolveExprNames() will be called without a
59983  ** prior call to sqlite3SelectExpand().  When that happens, let
59984  ** sqlite3SelectPrep() do all of the processing for this SELECT.
59985  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
59986  ** this routine in the correct order.
59987  */
59988  if( (p->selFlags & SF_Expanded)==0 ){
59989    sqlite3SelectPrep(pParse, p, pOuterNC);
59990    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
59991  }
59992
59993  isCompound = p->pPrior!=0;
59994  nCompound = 0;
59995  pLeftmost = p;
59996  while( p ){
59997    assert( (p->selFlags & SF_Expanded)!=0 );
59998    assert( (p->selFlags & SF_Resolved)==0 );
59999    p->selFlags |= SF_Resolved;
60000
60001    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
60002    ** are not allowed to refer to any names, so pass an empty NameContext.
60003    */
60004    memset(&sNC, 0, sizeof(sNC));
60005    sNC.pParse = pParse;
60006    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
60007        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
60008      return WRC_Abort;
60009    }
60010
60011    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
60012    ** resolve the result-set expression list.
60013    */
60014    sNC.allowAgg = 1;
60015    sNC.pSrcList = p->pSrc;
60016    sNC.pNext = pOuterNC;
60017
60018    /* Resolve names in the result set. */
60019    pEList = p->pEList;
60020    assert( pEList!=0 );
60021    for(i=0; i<pEList->nExpr; i++){
60022      Expr *pX = pEList->a[i].pExpr;
60023      if( sqlite3ResolveExprNames(&sNC, pX) ){
60024        return WRC_Abort;
60025      }
60026    }
60027
60028    /* Recursively resolve names in all subqueries
60029    */
60030    for(i=0; i<p->pSrc->nSrc; i++){
60031      struct SrcList_item *pItem = &p->pSrc->a[i];
60032      if( pItem->pSelect ){
60033        const char *zSavedContext = pParse->zAuthContext;
60034        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
60035        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
60036        pParse->zAuthContext = zSavedContext;
60037        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
60038      }
60039    }
60040
60041    /* If there are no aggregate functions in the result-set, and no GROUP BY
60042    ** expression, do not allow aggregates in any of the other expressions.
60043    */
60044    assert( (p->selFlags & SF_Aggregate)==0 );
60045    pGroupBy = p->pGroupBy;
60046    if( pGroupBy || sNC.hasAgg ){
60047      p->selFlags |= SF_Aggregate;
60048    }else{
60049      sNC.allowAgg = 0;
60050    }
60051
60052    /* If a HAVING clause is present, then there must be a GROUP BY clause.
60053    */
60054    if( p->pHaving && !pGroupBy ){
60055      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
60056      return WRC_Abort;
60057    }
60058
60059    /* Add the expression list to the name-context before parsing the
60060    ** other expressions in the SELECT statement. This is so that
60061    ** expressions in the WHERE clause (etc.) can refer to expressions by
60062    ** aliases in the result set.
60063    **
60064    ** Minor point: If this is the case, then the expression will be
60065    ** re-evaluated for each reference to it.
60066    */
60067    sNC.pEList = p->pEList;
60068    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
60069       sqlite3ResolveExprNames(&sNC, p->pHaving)
60070    ){
60071      return WRC_Abort;
60072    }
60073
60074    /* The ORDER BY and GROUP BY clauses may not refer to terms in
60075    ** outer queries
60076    */
60077    sNC.pNext = 0;
60078    sNC.allowAgg = 1;
60079
60080    /* Process the ORDER BY clause for singleton SELECT statements.
60081    ** The ORDER BY clause for compounds SELECT statements is handled
60082    ** below, after all of the result-sets for all of the elements of
60083    ** the compound have been resolved.
60084    */
60085    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
60086      return WRC_Abort;
60087    }
60088    if( db->mallocFailed ){
60089      return WRC_Abort;
60090    }
60091
60092    /* Resolve the GROUP BY clause.  At the same time, make sure
60093    ** the GROUP BY clause does not contain aggregate functions.
60094    */
60095    if( pGroupBy ){
60096      struct ExprList_item *pItem;
60097
60098      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
60099        return WRC_Abort;
60100      }
60101      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
60102        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
60103          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
60104              "the GROUP BY clause");
60105          return WRC_Abort;
60106        }
60107      }
60108    }
60109
60110    /* Advance to the next term of the compound
60111    */
60112    p = p->pPrior;
60113    nCompound++;
60114  }
60115
60116  /* Resolve the ORDER BY on a compound SELECT after all terms of
60117  ** the compound have been resolved.
60118  */
60119  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
60120    return WRC_Abort;
60121  }
60122
60123  return WRC_Prune;
60124}
60125
60126/*
60127** This routine walks an expression tree and resolves references to
60128** table columns and result-set columns.  At the same time, do error
60129** checking on function usage and set a flag if any aggregate functions
60130** are seen.
60131**
60132** To resolve table columns references we look for nodes (or subtrees) of the
60133** form X.Y.Z or Y.Z or just Z where
60134**
60135**      X:   The name of a database.  Ex:  "main" or "temp" or
60136**           the symbolic name assigned to an ATTACH-ed database.
60137**
60138**      Y:   The name of a table in a FROM clause.  Or in a trigger
60139**           one of the special names "old" or "new".
60140**
60141**      Z:   The name of a column in table Y.
60142**
60143** The node at the root of the subtree is modified as follows:
60144**
60145**    Expr.op        Changed to TK_COLUMN
60146**    Expr.pTab      Points to the Table object for X.Y
60147**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
60148**    Expr.iTable    The VDBE cursor number for X.Y
60149**
60150**
60151** To resolve result-set references, look for expression nodes of the
60152** form Z (with no X and Y prefix) where the Z matches the right-hand
60153** size of an AS clause in the result-set of a SELECT.  The Z expression
60154** is replaced by a copy of the left-hand side of the result-set expression.
60155** Table-name and function resolution occurs on the substituted expression
60156** tree.  For example, in:
60157**
60158**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
60159**
60160** The "x" term of the order by is replaced by "a+b" to render:
60161**
60162**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
60163**
60164** Function calls are checked to make sure that the function is
60165** defined and that the correct number of arguments are specified.
60166** If the function is an aggregate function, then the pNC->hasAgg is
60167** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
60168** If an expression contains aggregate functions then the EP_Agg
60169** property on the expression is set.
60170**
60171** An error message is left in pParse if anything is amiss.  The number
60172** if errors is returned.
60173*/
60174SQLITE_PRIVATE int sqlite3ResolveExprNames(
60175  NameContext *pNC,       /* Namespace to resolve expressions in. */
60176  Expr *pExpr             /* The expression to be analyzed. */
60177){
60178  int savedHasAgg;
60179  Walker w;
60180
60181  if( pExpr==0 ) return 0;
60182#if SQLITE_MAX_EXPR_DEPTH>0
60183  {
60184    Parse *pParse = pNC->pParse;
60185    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
60186      return 1;
60187    }
60188    pParse->nHeight += pExpr->nHeight;
60189  }
60190#endif
60191  savedHasAgg = pNC->hasAgg;
60192  pNC->hasAgg = 0;
60193  w.xExprCallback = resolveExprStep;
60194  w.xSelectCallback = resolveSelectStep;
60195  w.pParse = pNC->pParse;
60196  w.u.pNC = pNC;
60197  sqlite3WalkExpr(&w, pExpr);
60198#if SQLITE_MAX_EXPR_DEPTH>0
60199  pNC->pParse->nHeight -= pExpr->nHeight;
60200#endif
60201  if( pNC->nErr>0 || w.pParse->nErr>0 ){
60202    ExprSetProperty(pExpr, EP_Error);
60203  }
60204  if( pNC->hasAgg ){
60205    ExprSetProperty(pExpr, EP_Agg);
60206  }else if( savedHasAgg ){
60207    pNC->hasAgg = 1;
60208  }
60209  return ExprHasProperty(pExpr, EP_Error);
60210}
60211
60212
60213/*
60214** Resolve all names in all expressions of a SELECT and in all
60215** decendents of the SELECT, including compounds off of p->pPrior,
60216** subqueries in expressions, and subqueries used as FROM clause
60217** terms.
60218**
60219** See sqlite3ResolveExprNames() for a description of the kinds of
60220** transformations that occur.
60221**
60222** All SELECT statements should have been expanded using
60223** sqlite3SelectExpand() prior to invoking this routine.
60224*/
60225SQLITE_PRIVATE void sqlite3ResolveSelectNames(
60226  Parse *pParse,         /* The parser context */
60227  Select *p,             /* The SELECT statement being coded. */
60228  NameContext *pOuterNC  /* Name context for parent SELECT statement */
60229){
60230  Walker w;
60231
60232  assert( p!=0 );
60233  w.xExprCallback = resolveExprStep;
60234  w.xSelectCallback = resolveSelectStep;
60235  w.pParse = pParse;
60236  w.u.pNC = pOuterNC;
60237  sqlite3WalkSelect(&w, p);
60238}
60239
60240/************** End of resolve.c *********************************************/
60241/************** Begin file expr.c ********************************************/
60242/*
60243** 2001 September 15
60244**
60245** The author disclaims copyright to this source code.  In place of
60246** a legal notice, here is a blessing:
60247**
60248**    May you do good and not evil.
60249**    May you find forgiveness for yourself and forgive others.
60250**    May you share freely, never taking more than you give.
60251**
60252*************************************************************************
60253** This file contains routines used for analyzing expressions and
60254** for generating VDBE code that evaluates expressions in SQLite.
60255*/
60256
60257/*
60258** Return the 'affinity' of the expression pExpr if any.
60259**
60260** If pExpr is a column, a reference to a column via an 'AS' alias,
60261** or a sub-select with a column as the return value, then the
60262** affinity of that column is returned. Otherwise, 0x00 is returned,
60263** indicating no affinity for the expression.
60264**
60265** i.e. the WHERE clause expresssions in the following statements all
60266** have an affinity:
60267**
60268** CREATE TABLE t1(a);
60269** SELECT * FROM t1 WHERE a;
60270** SELECT a AS b FROM t1 WHERE b;
60271** SELECT * FROM t1 WHERE (select a from t1);
60272*/
60273SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
60274  int op = pExpr->op;
60275  if( op==TK_SELECT ){
60276    assert( pExpr->flags&EP_xIsSelect );
60277    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
60278  }
60279#ifndef SQLITE_OMIT_CAST
60280  if( op==TK_CAST ){
60281    assert( !ExprHasProperty(pExpr, EP_IntValue) );
60282    return sqlite3AffinityType(pExpr->u.zToken);
60283  }
60284#endif
60285  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
60286   && pExpr->pTab!=0
60287  ){
60288    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
60289    ** a TK_COLUMN but was previously evaluated and cached in a register */
60290    int j = pExpr->iColumn;
60291    if( j<0 ) return SQLITE_AFF_INTEGER;
60292    assert( pExpr->pTab && j<pExpr->pTab->nCol );
60293    return pExpr->pTab->aCol[j].affinity;
60294  }
60295  return pExpr->affinity;
60296}
60297
60298/*
60299** Set the collating sequence for expression pExpr to be the collating
60300** sequence named by pToken.   Return a pointer to the revised expression.
60301** The collating sequence is marked as "explicit" using the EP_ExpCollate
60302** flag.  An explicit collating sequence will override implicit
60303** collating sequences.
60304*/
60305SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
60306  char *zColl = 0;            /* Dequoted name of collation sequence */
60307  CollSeq *pColl;
60308  sqlite3 *db = pParse->db;
60309  zColl = sqlite3NameFromToken(db, pCollName);
60310  if( pExpr && zColl ){
60311    pColl = sqlite3LocateCollSeq(pParse, zColl);
60312    if( pColl ){
60313      pExpr->pColl = pColl;
60314      pExpr->flags |= EP_ExpCollate;
60315    }
60316  }
60317  sqlite3DbFree(db, zColl);
60318  return pExpr;
60319}
60320
60321/*
60322** Return the default collation sequence for the expression pExpr. If
60323** there is no default collation type, return 0.
60324*/
60325SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
60326  CollSeq *pColl = 0;
60327  Expr *p = pExpr;
60328  while( ALWAYS(p) ){
60329    int op;
60330    pColl = p->pColl;
60331    if( pColl ) break;
60332    op = p->op;
60333    if( p->pTab!=0 && (
60334        op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
60335    )){
60336      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
60337      ** a TK_COLUMN but was previously evaluated and cached in a register */
60338      const char *zColl;
60339      int j = p->iColumn;
60340      if( j>=0 ){
60341        sqlite3 *db = pParse->db;
60342        zColl = p->pTab->aCol[j].zColl;
60343        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
60344        pExpr->pColl = pColl;
60345      }
60346      break;
60347    }
60348    if( op!=TK_CAST && op!=TK_UPLUS ){
60349      break;
60350    }
60351    p = p->pLeft;
60352  }
60353  if( sqlite3CheckCollSeq(pParse, pColl) ){
60354    pColl = 0;
60355  }
60356  return pColl;
60357}
60358
60359/*
60360** pExpr is an operand of a comparison operator.  aff2 is the
60361** type affinity of the other operand.  This routine returns the
60362** type affinity that should be used for the comparison operator.
60363*/
60364SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
60365  char aff1 = sqlite3ExprAffinity(pExpr);
60366  if( aff1 && aff2 ){
60367    /* Both sides of the comparison are columns. If one has numeric
60368    ** affinity, use that. Otherwise use no affinity.
60369    */
60370    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
60371      return SQLITE_AFF_NUMERIC;
60372    }else{
60373      return SQLITE_AFF_NONE;
60374    }
60375  }else if( !aff1 && !aff2 ){
60376    /* Neither side of the comparison is a column.  Compare the
60377    ** results directly.
60378    */
60379    return SQLITE_AFF_NONE;
60380  }else{
60381    /* One side is a column, the other is not. Use the columns affinity. */
60382    assert( aff1==0 || aff2==0 );
60383    return (aff1 + aff2);
60384  }
60385}
60386
60387/*
60388** pExpr is a comparison operator.  Return the type affinity that should
60389** be applied to both operands prior to doing the comparison.
60390*/
60391static char comparisonAffinity(Expr *pExpr){
60392  char aff;
60393  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
60394          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
60395          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
60396  assert( pExpr->pLeft );
60397  aff = sqlite3ExprAffinity(pExpr->pLeft);
60398  if( pExpr->pRight ){
60399    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
60400  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
60401    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
60402  }else if( !aff ){
60403    aff = SQLITE_AFF_NONE;
60404  }
60405  return aff;
60406}
60407
60408/*
60409** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
60410** idx_affinity is the affinity of an indexed column. Return true
60411** if the index with affinity idx_affinity may be used to implement
60412** the comparison in pExpr.
60413*/
60414SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
60415  char aff = comparisonAffinity(pExpr);
60416  switch( aff ){
60417    case SQLITE_AFF_NONE:
60418      return 1;
60419    case SQLITE_AFF_TEXT:
60420      return idx_affinity==SQLITE_AFF_TEXT;
60421    default:
60422      return sqlite3IsNumericAffinity(idx_affinity);
60423  }
60424}
60425
60426/*
60427** Return the P5 value that should be used for a binary comparison
60428** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
60429*/
60430static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
60431  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
60432  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
60433  return aff;
60434}
60435
60436/*
60437** Return a pointer to the collation sequence that should be used by
60438** a binary comparison operator comparing pLeft and pRight.
60439**
60440** If the left hand expression has a collating sequence type, then it is
60441** used. Otherwise the collation sequence for the right hand expression
60442** is used, or the default (BINARY) if neither expression has a collating
60443** type.
60444**
60445** Argument pRight (but not pLeft) may be a null pointer. In this case,
60446** it is not considered.
60447*/
60448SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
60449  Parse *pParse,
60450  Expr *pLeft,
60451  Expr *pRight
60452){
60453  CollSeq *pColl;
60454  assert( pLeft );
60455  if( pLeft->flags & EP_ExpCollate ){
60456    assert( pLeft->pColl );
60457    pColl = pLeft->pColl;
60458  }else if( pRight && pRight->flags & EP_ExpCollate ){
60459    assert( pRight->pColl );
60460    pColl = pRight->pColl;
60461  }else{
60462    pColl = sqlite3ExprCollSeq(pParse, pLeft);
60463    if( !pColl ){
60464      pColl = sqlite3ExprCollSeq(pParse, pRight);
60465    }
60466  }
60467  return pColl;
60468}
60469
60470/*
60471** Generate code for a comparison operator.
60472*/
60473static int codeCompare(
60474  Parse *pParse,    /* The parsing (and code generating) context */
60475  Expr *pLeft,      /* The left operand */
60476  Expr *pRight,     /* The right operand */
60477  int opcode,       /* The comparison opcode */
60478  int in1, int in2, /* Register holding operands */
60479  int dest,         /* Jump here if true.  */
60480  int jumpIfNull    /* If true, jump if either operand is NULL */
60481){
60482  int p5;
60483  int addr;
60484  CollSeq *p4;
60485
60486  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
60487  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
60488  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
60489                           (void*)p4, P4_COLLSEQ);
60490  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
60491  if( (p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_NONE ){
60492    sqlite3ExprCacheAffinityChange(pParse, in1, 1);
60493    sqlite3ExprCacheAffinityChange(pParse, in2, 1);
60494  }
60495  return addr;
60496}
60497
60498#if SQLITE_MAX_EXPR_DEPTH>0
60499/*
60500** Check that argument nHeight is less than or equal to the maximum
60501** expression depth allowed. If it is not, leave an error message in
60502** pParse.
60503*/
60504SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
60505  int rc = SQLITE_OK;
60506  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
60507  if( nHeight>mxHeight ){
60508    sqlite3ErrorMsg(pParse,
60509       "Expression tree is too large (maximum depth %d)", mxHeight
60510    );
60511    rc = SQLITE_ERROR;
60512  }
60513  return rc;
60514}
60515
60516/* The following three functions, heightOfExpr(), heightOfExprList()
60517** and heightOfSelect(), are used to determine the maximum height
60518** of any expression tree referenced by the structure passed as the
60519** first argument.
60520**
60521** If this maximum height is greater than the current value pointed
60522** to by pnHeight, the second parameter, then set *pnHeight to that
60523** value.
60524*/
60525static void heightOfExpr(Expr *p, int *pnHeight){
60526  if( p ){
60527    if( p->nHeight>*pnHeight ){
60528      *pnHeight = p->nHeight;
60529    }
60530  }
60531}
60532static void heightOfExprList(ExprList *p, int *pnHeight){
60533  if( p ){
60534    int i;
60535    for(i=0; i<p->nExpr; i++){
60536      heightOfExpr(p->a[i].pExpr, pnHeight);
60537    }
60538  }
60539}
60540static void heightOfSelect(Select *p, int *pnHeight){
60541  if( p ){
60542    heightOfExpr(p->pWhere, pnHeight);
60543    heightOfExpr(p->pHaving, pnHeight);
60544    heightOfExpr(p->pLimit, pnHeight);
60545    heightOfExpr(p->pOffset, pnHeight);
60546    heightOfExprList(p->pEList, pnHeight);
60547    heightOfExprList(p->pGroupBy, pnHeight);
60548    heightOfExprList(p->pOrderBy, pnHeight);
60549    heightOfSelect(p->pPrior, pnHeight);
60550  }
60551}
60552
60553/*
60554** Set the Expr.nHeight variable in the structure passed as an
60555** argument. An expression with no children, Expr.pList or
60556** Expr.pSelect member has a height of 1. Any other expression
60557** has a height equal to the maximum height of any other
60558** referenced Expr plus one.
60559*/
60560static void exprSetHeight(Expr *p){
60561  int nHeight = 0;
60562  heightOfExpr(p->pLeft, &nHeight);
60563  heightOfExpr(p->pRight, &nHeight);
60564  if( ExprHasProperty(p, EP_xIsSelect) ){
60565    heightOfSelect(p->x.pSelect, &nHeight);
60566  }else{
60567    heightOfExprList(p->x.pList, &nHeight);
60568  }
60569  p->nHeight = nHeight + 1;
60570}
60571
60572/*
60573** Set the Expr.nHeight variable using the exprSetHeight() function. If
60574** the height is greater than the maximum allowed expression depth,
60575** leave an error in pParse.
60576*/
60577SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
60578  exprSetHeight(p);
60579  sqlite3ExprCheckHeight(pParse, p->nHeight);
60580}
60581
60582/*
60583** Return the maximum height of any expression tree referenced
60584** by the select statement passed as an argument.
60585*/
60586SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
60587  int nHeight = 0;
60588  heightOfSelect(p, &nHeight);
60589  return nHeight;
60590}
60591#else
60592  #define exprSetHeight(y)
60593#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
60594
60595/*
60596** This routine is the core allocator for Expr nodes.
60597**
60598** Construct a new expression node and return a pointer to it.  Memory
60599** for this node and for the pToken argument is a single allocation
60600** obtained from sqlite3DbMalloc().  The calling function
60601** is responsible for making sure the node eventually gets freed.
60602**
60603** If dequote is true, then the token (if it exists) is dequoted.
60604** If dequote is false, no dequoting is performance.  The deQuote
60605** parameter is ignored if pToken is NULL or if the token does not
60606** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
60607** then the EP_DblQuoted flag is set on the expression node.
60608**
60609** Special case:  If op==TK_INTEGER and pToken points to a string that
60610** can be translated into a 32-bit integer, then the token is not
60611** stored in u.zToken.  Instead, the integer values is written
60612** into u.iValue and the EP_IntValue flag is set.  No extra storage
60613** is allocated to hold the integer text and the dequote flag is ignored.
60614*/
60615SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
60616  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
60617  int op,                 /* Expression opcode */
60618  const Token *pToken,    /* Token argument.  Might be NULL */
60619  int dequote             /* True to dequote */
60620){
60621  Expr *pNew;
60622  int nExtra = 0;
60623  int iValue = 0;
60624
60625  if( pToken ){
60626    if( op!=TK_INTEGER || pToken->z==0
60627          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
60628      nExtra = pToken->n+1;
60629    }
60630  }
60631  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
60632  if( pNew ){
60633    pNew->op = (u8)op;
60634    pNew->iAgg = -1;
60635    if( pToken ){
60636      if( nExtra==0 ){
60637        pNew->flags |= EP_IntValue;
60638        pNew->u.iValue = iValue;
60639      }else{
60640        int c;
60641        pNew->u.zToken = (char*)&pNew[1];
60642        memcpy(pNew->u.zToken, pToken->z, pToken->n);
60643        pNew->u.zToken[pToken->n] = 0;
60644        if( dequote && nExtra>=3
60645             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
60646          sqlite3Dequote(pNew->u.zToken);
60647          if( c=='"' ) pNew->flags |= EP_DblQuoted;
60648        }
60649      }
60650    }
60651#if SQLITE_MAX_EXPR_DEPTH>0
60652    pNew->nHeight = 1;
60653#endif
60654  }
60655  return pNew;
60656}
60657
60658/*
60659** Allocate a new expression node from a zero-terminated token that has
60660** already been dequoted.
60661*/
60662SQLITE_PRIVATE Expr *sqlite3Expr(
60663  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
60664  int op,                 /* Expression opcode */
60665  const char *zToken      /* Token argument.  Might be NULL */
60666){
60667  Token x;
60668  x.z = zToken;
60669  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
60670  return sqlite3ExprAlloc(db, op, &x, 0);
60671}
60672
60673/*
60674** Attach subtrees pLeft and pRight to the Expr node pRoot.
60675**
60676** If pRoot==NULL that means that a memory allocation error has occurred.
60677** In that case, delete the subtrees pLeft and pRight.
60678*/
60679SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
60680  sqlite3 *db,
60681  Expr *pRoot,
60682  Expr *pLeft,
60683  Expr *pRight
60684){
60685  if( pRoot==0 ){
60686    assert( db->mallocFailed );
60687    sqlite3ExprDelete(db, pLeft);
60688    sqlite3ExprDelete(db, pRight);
60689  }else{
60690    if( pRight ){
60691      pRoot->pRight = pRight;
60692      if( pRight->flags & EP_ExpCollate ){
60693        pRoot->flags |= EP_ExpCollate;
60694        pRoot->pColl = pRight->pColl;
60695      }
60696    }
60697    if( pLeft ){
60698      pRoot->pLeft = pLeft;
60699      if( pLeft->flags & EP_ExpCollate ){
60700        pRoot->flags |= EP_ExpCollate;
60701        pRoot->pColl = pLeft->pColl;
60702      }
60703    }
60704    exprSetHeight(pRoot);
60705  }
60706}
60707
60708/*
60709** Allocate a Expr node which joins as many as two subtrees.
60710**
60711** One or both of the subtrees can be NULL.  Return a pointer to the new
60712** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
60713** free the subtrees and return NULL.
60714*/
60715SQLITE_PRIVATE Expr *sqlite3PExpr(
60716  Parse *pParse,          /* Parsing context */
60717  int op,                 /* Expression opcode */
60718  Expr *pLeft,            /* Left operand */
60719  Expr *pRight,           /* Right operand */
60720  const Token *pToken     /* Argument token */
60721){
60722  Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
60723  sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
60724  return p;
60725}
60726
60727/*
60728** Join two expressions using an AND operator.  If either expression is
60729** NULL, then just return the other expression.
60730*/
60731SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
60732  if( pLeft==0 ){
60733    return pRight;
60734  }else if( pRight==0 ){
60735    return pLeft;
60736  }else{
60737    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
60738    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
60739    return pNew;
60740  }
60741}
60742
60743/*
60744** Construct a new expression node for a function with multiple
60745** arguments.
60746*/
60747SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
60748  Expr *pNew;
60749  sqlite3 *db = pParse->db;
60750  assert( pToken );
60751  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
60752  if( pNew==0 ){
60753    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
60754    return 0;
60755  }
60756  pNew->x.pList = pList;
60757  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
60758  sqlite3ExprSetHeight(pParse, pNew);
60759  return pNew;
60760}
60761
60762/*
60763** Assign a variable number to an expression that encodes a wildcard
60764** in the original SQL statement.
60765**
60766** Wildcards consisting of a single "?" are assigned the next sequential
60767** variable number.
60768**
60769** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
60770** sure "nnn" is not too be to avoid a denial of service attack when
60771** the SQL statement comes from an external source.
60772**
60773** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
60774** as the previous instance of the same wildcard.  Or if this is the first
60775** instance of the wildcard, the next sequenial variable number is
60776** assigned.
60777*/
60778SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
60779  sqlite3 *db = pParse->db;
60780  const char *z;
60781
60782  if( pExpr==0 ) return;
60783  assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
60784  z = pExpr->u.zToken;
60785  assert( z!=0 );
60786  assert( z[0]!=0 );
60787  if( z[1]==0 ){
60788    /* Wildcard of the form "?".  Assign the next variable number */
60789    assert( z[0]=='?' );
60790    pExpr->iColumn = (ynVar)(++pParse->nVar);
60791  }else if( z[0]=='?' ){
60792    /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
60793    ** use it as the variable number */
60794    int i = atoi((char*)&z[1]);
60795    pExpr->iColumn = (ynVar)i;
60796    testcase( i==0 );
60797    testcase( i==1 );
60798    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
60799    testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
60800    if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
60801      sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
60802          db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
60803    }
60804    if( i>pParse->nVar ){
60805      pParse->nVar = i;
60806    }
60807  }else{
60808    /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
60809    ** number as the prior appearance of the same name, or if the name
60810    ** has never appeared before, reuse the same variable number
60811    */
60812    int i;
60813    u32 n;
60814    n = sqlite3Strlen30(z);
60815    for(i=0; i<pParse->nVarExpr; i++){
60816      Expr *pE = pParse->apVarExpr[i];
60817      assert( pE!=0 );
60818      if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
60819        pExpr->iColumn = pE->iColumn;
60820        break;
60821      }
60822    }
60823    if( i>=pParse->nVarExpr ){
60824      pExpr->iColumn = (ynVar)(++pParse->nVar);
60825      if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
60826        pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
60827        pParse->apVarExpr =
60828            sqlite3DbReallocOrFree(
60829              db,
60830              pParse->apVarExpr,
60831              pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
60832            );
60833      }
60834      if( !db->mallocFailed ){
60835        assert( pParse->apVarExpr!=0 );
60836        pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
60837      }
60838    }
60839  }
60840  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
60841    sqlite3ErrorMsg(pParse, "too many SQL variables");
60842  }
60843}
60844
60845/*
60846** Recursively delete an expression tree.
60847*/
60848SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
60849  if( p==0 ) return;
60850  if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
60851    sqlite3ExprDelete(db, p->pLeft);
60852    sqlite3ExprDelete(db, p->pRight);
60853    if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
60854      sqlite3DbFree(db, p->u.zToken);
60855    }
60856    if( ExprHasProperty(p, EP_xIsSelect) ){
60857      sqlite3SelectDelete(db, p->x.pSelect);
60858    }else{
60859      sqlite3ExprListDelete(db, p->x.pList);
60860    }
60861  }
60862  if( !ExprHasProperty(p, EP_Static) ){
60863    sqlite3DbFree(db, p);
60864  }
60865}
60866
60867/*
60868** Return the number of bytes allocated for the expression structure
60869** passed as the first argument. This is always one of EXPR_FULLSIZE,
60870** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
60871*/
60872static int exprStructSize(Expr *p){
60873  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
60874  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
60875  return EXPR_FULLSIZE;
60876}
60877
60878/*
60879** The dupedExpr*Size() routines each return the number of bytes required
60880** to store a copy of an expression or expression tree.  They differ in
60881** how much of the tree is measured.
60882**
60883**     dupedExprStructSize()     Size of only the Expr structure
60884**     dupedExprNodeSize()       Size of Expr + space for token
60885**     dupedExprSize()           Expr + token + subtree components
60886**
60887***************************************************************************
60888**
60889** The dupedExprStructSize() function returns two values OR-ed together:
60890** (1) the space required for a copy of the Expr structure only and
60891** (2) the EP_xxx flags that indicate what the structure size should be.
60892** The return values is always one of:
60893**
60894**      EXPR_FULLSIZE
60895**      EXPR_REDUCEDSIZE   | EP_Reduced
60896**      EXPR_TOKENONLYSIZE | EP_TokenOnly
60897**
60898** The size of the structure can be found by masking the return value
60899** of this routine with 0xfff.  The flags can be found by masking the
60900** return value with EP_Reduced|EP_TokenOnly.
60901**
60902** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
60903** (unreduced) Expr objects as they or originally constructed by the parser.
60904** During expression analysis, extra information is computed and moved into
60905** later parts of teh Expr object and that extra information might get chopped
60906** off if the expression is reduced.  Note also that it does not work to
60907** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
60908** to reduce a pristine expression tree from the parser.  The implementation
60909** of dupedExprStructSize() contain multiple assert() statements that attempt
60910** to enforce this constraint.
60911*/
60912static int dupedExprStructSize(Expr *p, int flags){
60913  int nSize;
60914  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
60915  if( 0==(flags&EXPRDUP_REDUCE) ){
60916    nSize = EXPR_FULLSIZE;
60917  }else{
60918    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
60919    assert( !ExprHasProperty(p, EP_FromJoin) );
60920    assert( (p->flags2 & EP2_MallocedToken)==0 );
60921    assert( (p->flags2 & EP2_Irreducible)==0 );
60922    if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
60923      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
60924    }else{
60925      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
60926    }
60927  }
60928  return nSize;
60929}
60930
60931/*
60932** This function returns the space in bytes required to store the copy
60933** of the Expr structure and a copy of the Expr.u.zToken string (if that
60934** string is defined.)
60935*/
60936static int dupedExprNodeSize(Expr *p, int flags){
60937  int nByte = dupedExprStructSize(p, flags) & 0xfff;
60938  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
60939    nByte += sqlite3Strlen30(p->u.zToken)+1;
60940  }
60941  return ROUND8(nByte);
60942}
60943
60944/*
60945** Return the number of bytes required to create a duplicate of the
60946** expression passed as the first argument. The second argument is a
60947** mask containing EXPRDUP_XXX flags.
60948**
60949** The value returned includes space to create a copy of the Expr struct
60950** itself and the buffer referred to by Expr.u.zToken, if any.
60951**
60952** If the EXPRDUP_REDUCE flag is set, then the return value includes
60953** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
60954** and Expr.pRight variables (but not for any structures pointed to or
60955** descended from the Expr.x.pList or Expr.x.pSelect variables).
60956*/
60957static int dupedExprSize(Expr *p, int flags){
60958  int nByte = 0;
60959  if( p ){
60960    nByte = dupedExprNodeSize(p, flags);
60961    if( flags&EXPRDUP_REDUCE ){
60962      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
60963    }
60964  }
60965  return nByte;
60966}
60967
60968/*
60969** This function is similar to sqlite3ExprDup(), except that if pzBuffer
60970** is not NULL then *pzBuffer is assumed to point to a buffer large enough
60971** to store the copy of expression p, the copies of p->u.zToken
60972** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
60973** if any. Before returning, *pzBuffer is set to the first byte passed the
60974** portion of the buffer copied into by this function.
60975*/
60976static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
60977  Expr *pNew = 0;                      /* Value to return */
60978  if( p ){
60979    const int isReduced = (flags&EXPRDUP_REDUCE);
60980    u8 *zAlloc;
60981    u32 staticFlag = 0;
60982
60983    assert( pzBuffer==0 || isReduced );
60984
60985    /* Figure out where to write the new Expr structure. */
60986    if( pzBuffer ){
60987      zAlloc = *pzBuffer;
60988      staticFlag = EP_Static;
60989    }else{
60990      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
60991    }
60992    pNew = (Expr *)zAlloc;
60993
60994    if( pNew ){
60995      /* Set nNewSize to the size allocated for the structure pointed to
60996      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
60997      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
60998      ** by the copy of the p->u.zToken string (if any).
60999      */
61000      const unsigned nStructSize = dupedExprStructSize(p, flags);
61001      const int nNewSize = nStructSize & 0xfff;
61002      int nToken;
61003      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
61004        nToken = sqlite3Strlen30(p->u.zToken) + 1;
61005      }else{
61006        nToken = 0;
61007      }
61008      if( isReduced ){
61009        assert( ExprHasProperty(p, EP_Reduced)==0 );
61010        memcpy(zAlloc, p, nNewSize);
61011      }else{
61012        int nSize = exprStructSize(p);
61013        memcpy(zAlloc, p, nSize);
61014        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
61015      }
61016
61017      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
61018      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
61019      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
61020      pNew->flags |= staticFlag;
61021
61022      /* Copy the p->u.zToken string, if any. */
61023      if( nToken ){
61024        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
61025        memcpy(zToken, p->u.zToken, nToken);
61026      }
61027
61028      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
61029        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
61030        if( ExprHasProperty(p, EP_xIsSelect) ){
61031          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
61032        }else{
61033          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
61034        }
61035      }
61036
61037      /* Fill in pNew->pLeft and pNew->pRight. */
61038      if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
61039        zAlloc += dupedExprNodeSize(p, flags);
61040        if( ExprHasProperty(pNew, EP_Reduced) ){
61041          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
61042          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
61043        }
61044        if( pzBuffer ){
61045          *pzBuffer = zAlloc;
61046        }
61047      }else{
61048        pNew->flags2 = 0;
61049        if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
61050          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
61051          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
61052        }
61053      }
61054
61055    }
61056  }
61057  return pNew;
61058}
61059
61060/*
61061** The following group of routines make deep copies of expressions,
61062** expression lists, ID lists, and select statements.  The copies can
61063** be deleted (by being passed to their respective ...Delete() routines)
61064** without effecting the originals.
61065**
61066** The expression list, ID, and source lists return by sqlite3ExprListDup(),
61067** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
61068** by subsequent calls to sqlite*ListAppend() routines.
61069**
61070** Any tables that the SrcList might point to are not duplicated.
61071**
61072** The flags parameter contains a combination of the EXPRDUP_XXX flags.
61073** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
61074** truncated version of the usual Expr structure that will be stored as
61075** part of the in-memory representation of the database schema.
61076*/
61077SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
61078  return exprDup(db, p, flags, 0);
61079}
61080SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
61081  ExprList *pNew;
61082  struct ExprList_item *pItem, *pOldItem;
61083  int i;
61084  if( p==0 ) return 0;
61085  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
61086  if( pNew==0 ) return 0;
61087  pNew->iECursor = 0;
61088  pNew->nExpr = pNew->nAlloc = p->nExpr;
61089  pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
61090  if( pItem==0 ){
61091    sqlite3DbFree(db, pNew);
61092    return 0;
61093  }
61094  pOldItem = p->a;
61095  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
61096    Expr *pOldExpr = pOldItem->pExpr;
61097    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
61098    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61099    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
61100    pItem->sortOrder = pOldItem->sortOrder;
61101    pItem->done = 0;
61102    pItem->iCol = pOldItem->iCol;
61103    pItem->iAlias = pOldItem->iAlias;
61104  }
61105  return pNew;
61106}
61107
61108/*
61109** If cursors, triggers, views and subqueries are all omitted from
61110** the build, then none of the following routines, except for
61111** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
61112** called with a NULL argument.
61113*/
61114#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
61115 || !defined(SQLITE_OMIT_SUBQUERY)
61116SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
61117  SrcList *pNew;
61118  int i;
61119  int nByte;
61120  if( p==0 ) return 0;
61121  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
61122  pNew = sqlite3DbMallocRaw(db, nByte );
61123  if( pNew==0 ) return 0;
61124  pNew->nSrc = pNew->nAlloc = p->nSrc;
61125  for(i=0; i<p->nSrc; i++){
61126    struct SrcList_item *pNewItem = &pNew->a[i];
61127    struct SrcList_item *pOldItem = &p->a[i];
61128    Table *pTab;
61129    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
61130    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61131    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
61132    pNewItem->jointype = pOldItem->jointype;
61133    pNewItem->iCursor = pOldItem->iCursor;
61134    pNewItem->isPopulated = pOldItem->isPopulated;
61135    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
61136    pNewItem->notIndexed = pOldItem->notIndexed;
61137    pNewItem->pIndex = pOldItem->pIndex;
61138    pTab = pNewItem->pTab = pOldItem->pTab;
61139    if( pTab ){
61140      pTab->nRef++;
61141    }
61142    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
61143    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
61144    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
61145    pNewItem->colUsed = pOldItem->colUsed;
61146  }
61147  return pNew;
61148}
61149SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
61150  IdList *pNew;
61151  int i;
61152  if( p==0 ) return 0;
61153  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
61154  if( pNew==0 ) return 0;
61155  pNew->nId = pNew->nAlloc = p->nId;
61156  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
61157  if( pNew->a==0 ){
61158    sqlite3DbFree(db, pNew);
61159    return 0;
61160  }
61161  for(i=0; i<p->nId; i++){
61162    struct IdList_item *pNewItem = &pNew->a[i];
61163    struct IdList_item *pOldItem = &p->a[i];
61164    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
61165    pNewItem->idx = pOldItem->idx;
61166  }
61167  return pNew;
61168}
61169SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
61170  Select *pNew;
61171  if( p==0 ) return 0;
61172  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
61173  if( pNew==0 ) return 0;
61174  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
61175  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
61176  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
61177  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
61178  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
61179  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
61180  pNew->op = p->op;
61181  pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
61182  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
61183  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
61184  pNew->iLimit = 0;
61185  pNew->iOffset = 0;
61186  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
61187  pNew->pRightmost = 0;
61188  pNew->addrOpenEphm[0] = -1;
61189  pNew->addrOpenEphm[1] = -1;
61190  pNew->addrOpenEphm[2] = -1;
61191  return pNew;
61192}
61193#else
61194SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
61195  assert( p==0 );
61196  return 0;
61197}
61198#endif
61199
61200
61201/*
61202** Add a new element to the end of an expression list.  If pList is
61203** initially NULL, then create a new expression list.
61204**
61205** If a memory allocation error occurs, the entire list is freed and
61206** NULL is returned.  If non-NULL is returned, then it is guaranteed
61207** that the new entry was successfully appended.
61208*/
61209SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
61210  Parse *pParse,          /* Parsing context */
61211  ExprList *pList,        /* List to which to append. Might be NULL */
61212  Expr *pExpr             /* Expression to be appended. Might be NULL */
61213){
61214  sqlite3 *db = pParse->db;
61215  if( pList==0 ){
61216    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
61217    if( pList==0 ){
61218      goto no_mem;
61219    }
61220    assert( pList->nAlloc==0 );
61221  }
61222  if( pList->nAlloc<=pList->nExpr ){
61223    struct ExprList_item *a;
61224    int n = pList->nAlloc*2 + 4;
61225    a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
61226    if( a==0 ){
61227      goto no_mem;
61228    }
61229    pList->a = a;
61230    pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
61231  }
61232  assert( pList->a!=0 );
61233  if( 1 ){
61234    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
61235    memset(pItem, 0, sizeof(*pItem));
61236    pItem->pExpr = pExpr;
61237  }
61238  return pList;
61239
61240no_mem:
61241  /* Avoid leaking memory if malloc has failed. */
61242  sqlite3ExprDelete(db, pExpr);
61243  sqlite3ExprListDelete(db, pList);
61244  return 0;
61245}
61246
61247/*
61248** Set the ExprList.a[].zName element of the most recently added item
61249** on the expression list.
61250**
61251** pList might be NULL following an OOM error.  But pName should never be
61252** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
61253** is set.
61254*/
61255SQLITE_PRIVATE void sqlite3ExprListSetName(
61256  Parse *pParse,          /* Parsing context */
61257  ExprList *pList,        /* List to which to add the span. */
61258  Token *pName,           /* Name to be added */
61259  int dequote             /* True to cause the name to be dequoted */
61260){
61261  assert( pList!=0 || pParse->db->mallocFailed!=0 );
61262  if( pList ){
61263    struct ExprList_item *pItem;
61264    assert( pList->nExpr>0 );
61265    pItem = &pList->a[pList->nExpr-1];
61266    assert( pItem->zName==0 );
61267    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
61268    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
61269  }
61270}
61271
61272/*
61273** Set the ExprList.a[].zSpan element of the most recently added item
61274** on the expression list.
61275**
61276** pList might be NULL following an OOM error.  But pSpan should never be
61277** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
61278** is set.
61279*/
61280SQLITE_PRIVATE void sqlite3ExprListSetSpan(
61281  Parse *pParse,          /* Parsing context */
61282  ExprList *pList,        /* List to which to add the span. */
61283  ExprSpan *pSpan         /* The span to be added */
61284){
61285  sqlite3 *db = pParse->db;
61286  assert( pList!=0 || db->mallocFailed!=0 );
61287  if( pList ){
61288    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
61289    assert( pList->nExpr>0 );
61290    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
61291    sqlite3DbFree(db, pItem->zSpan);
61292    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
61293                                    (int)(pSpan->zEnd - pSpan->zStart));
61294  }
61295}
61296
61297/*
61298** If the expression list pEList contains more than iLimit elements,
61299** leave an error message in pParse.
61300*/
61301SQLITE_PRIVATE void sqlite3ExprListCheckLength(
61302  Parse *pParse,
61303  ExprList *pEList,
61304  const char *zObject
61305){
61306  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
61307  testcase( pEList && pEList->nExpr==mx );
61308  testcase( pEList && pEList->nExpr==mx+1 );
61309  if( pEList && pEList->nExpr>mx ){
61310    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
61311  }
61312}
61313
61314/*
61315** Delete an entire expression list.
61316*/
61317SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
61318  int i;
61319  struct ExprList_item *pItem;
61320  if( pList==0 ) return;
61321  assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
61322  assert( pList->nExpr<=pList->nAlloc );
61323  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
61324    sqlite3ExprDelete(db, pItem->pExpr);
61325    sqlite3DbFree(db, pItem->zName);
61326    sqlite3DbFree(db, pItem->zSpan);
61327  }
61328  sqlite3DbFree(db, pList->a);
61329  sqlite3DbFree(db, pList);
61330}
61331
61332/*
61333** These routines are Walker callbacks.  Walker.u.pi is a pointer
61334** to an integer.  These routines are checking an expression to see
61335** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
61336** not constant.
61337**
61338** These callback routines are used to implement the following:
61339**
61340**     sqlite3ExprIsConstant()
61341**     sqlite3ExprIsConstantNotJoin()
61342**     sqlite3ExprIsConstantOrFunction()
61343**
61344*/
61345static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
61346
61347  /* If pWalker->u.i is 3 then any term of the expression that comes from
61348  ** the ON or USING clauses of a join disqualifies the expression
61349  ** from being considered constant. */
61350  if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
61351    pWalker->u.i = 0;
61352    return WRC_Abort;
61353  }
61354
61355  switch( pExpr->op ){
61356    /* Consider functions to be constant if all their arguments are constant
61357    ** and pWalker->u.i==2 */
61358    case TK_FUNCTION:
61359      if( pWalker->u.i==2 ) return 0;
61360      /* Fall through */
61361    case TK_ID:
61362    case TK_COLUMN:
61363    case TK_AGG_FUNCTION:
61364    case TK_AGG_COLUMN:
61365      testcase( pExpr->op==TK_ID );
61366      testcase( pExpr->op==TK_COLUMN );
61367      testcase( pExpr->op==TK_AGG_FUNCTION );
61368      testcase( pExpr->op==TK_AGG_COLUMN );
61369      pWalker->u.i = 0;
61370      return WRC_Abort;
61371    default:
61372      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
61373      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
61374      return WRC_Continue;
61375  }
61376}
61377static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
61378  UNUSED_PARAMETER(NotUsed);
61379  pWalker->u.i = 0;
61380  return WRC_Abort;
61381}
61382static int exprIsConst(Expr *p, int initFlag){
61383  Walker w;
61384  w.u.i = initFlag;
61385  w.xExprCallback = exprNodeIsConstant;
61386  w.xSelectCallback = selectNodeIsConstant;
61387  sqlite3WalkExpr(&w, p);
61388  return w.u.i;
61389}
61390
61391/*
61392** Walk an expression tree.  Return 1 if the expression is constant
61393** and 0 if it involves variables or function calls.
61394**
61395** For the purposes of this function, a double-quoted string (ex: "abc")
61396** is considered a variable but a single-quoted string (ex: 'abc') is
61397** a constant.
61398*/
61399SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
61400  return exprIsConst(p, 1);
61401}
61402
61403/*
61404** Walk an expression tree.  Return 1 if the expression is constant
61405** that does no originate from the ON or USING clauses of a join.
61406** Return 0 if it involves variables or function calls or terms from
61407** an ON or USING clause.
61408*/
61409SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
61410  return exprIsConst(p, 3);
61411}
61412
61413/*
61414** Walk an expression tree.  Return 1 if the expression is constant
61415** or a function call with constant arguments.  Return and 0 if there
61416** are any variables.
61417**
61418** For the purposes of this function, a double-quoted string (ex: "abc")
61419** is considered a variable but a single-quoted string (ex: 'abc') is
61420** a constant.
61421*/
61422SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
61423  return exprIsConst(p, 2);
61424}
61425
61426/*
61427** If the expression p codes a constant integer that is small enough
61428** to fit in a 32-bit integer, return 1 and put the value of the integer
61429** in *pValue.  If the expression is not an integer or if it is too big
61430** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
61431*/
61432SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
61433  int rc = 0;
61434  if( p->flags & EP_IntValue ){
61435    *pValue = p->u.iValue;
61436    return 1;
61437  }
61438  switch( p->op ){
61439    case TK_INTEGER: {
61440      rc = sqlite3GetInt32(p->u.zToken, pValue);
61441      assert( rc==0 );
61442      break;
61443    }
61444    case TK_UPLUS: {
61445      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
61446      break;
61447    }
61448    case TK_UMINUS: {
61449      int v;
61450      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
61451        *pValue = -v;
61452        rc = 1;
61453      }
61454      break;
61455    }
61456    default: break;
61457  }
61458  if( rc ){
61459    assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
61460               || (p->flags2 & EP2_MallocedToken)==0 );
61461    p->op = TK_INTEGER;
61462    p->flags |= EP_IntValue;
61463    p->u.iValue = *pValue;
61464  }
61465  return rc;
61466}
61467
61468/*
61469** Return FALSE if there is no chance that the expression can be NULL.
61470**
61471** If the expression might be NULL or if the expression is too complex
61472** to tell return TRUE.
61473**
61474** This routine is used as an optimization, to skip OP_IsNull opcodes
61475** when we know that a value cannot be NULL.  Hence, a false positive
61476** (returning TRUE when in fact the expression can never be NULL) might
61477** be a small performance hit but is otherwise harmless.  On the other
61478** hand, a false negative (returning FALSE when the result could be NULL)
61479** will likely result in an incorrect answer.  So when in doubt, return
61480** TRUE.
61481*/
61482SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
61483  u8 op;
61484  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
61485  op = p->op;
61486  if( op==TK_REGISTER ) op = p->op2;
61487  switch( op ){
61488    case TK_INTEGER:
61489    case TK_STRING:
61490    case TK_FLOAT:
61491    case TK_BLOB:
61492      return 0;
61493    default:
61494      return 1;
61495  }
61496}
61497
61498/*
61499** Generate an OP_IsNull instruction that tests register iReg and jumps
61500** to location iDest if the value in iReg is NULL.  The value in iReg
61501** was computed by pExpr.  If we can look at pExpr at compile-time and
61502** determine that it can never generate a NULL, then the OP_IsNull operation
61503** can be omitted.
61504*/
61505SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
61506  Vdbe *v,            /* The VDBE under construction */
61507  const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
61508  int iReg,           /* Test the value in this register for NULL */
61509  int iDest           /* Jump here if the value is null */
61510){
61511  if( sqlite3ExprCanBeNull(pExpr) ){
61512    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
61513  }
61514}
61515
61516/*
61517** Return TRUE if the given expression is a constant which would be
61518** unchanged by OP_Affinity with the affinity given in the second
61519** argument.
61520**
61521** This routine is used to determine if the OP_Affinity operation
61522** can be omitted.  When in doubt return FALSE.  A false negative
61523** is harmless.  A false positive, however, can result in the wrong
61524** answer.
61525*/
61526SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
61527  u8 op;
61528  if( aff==SQLITE_AFF_NONE ) return 1;
61529  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
61530  op = p->op;
61531  if( op==TK_REGISTER ) op = p->op2;
61532  switch( op ){
61533    case TK_INTEGER: {
61534      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
61535    }
61536    case TK_FLOAT: {
61537      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
61538    }
61539    case TK_STRING: {
61540      return aff==SQLITE_AFF_TEXT;
61541    }
61542    case TK_BLOB: {
61543      return 1;
61544    }
61545    case TK_COLUMN: {
61546      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
61547      return p->iColumn<0
61548          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
61549    }
61550    default: {
61551      return 0;
61552    }
61553  }
61554}
61555
61556/*
61557** Return TRUE if the given string is a row-id column name.
61558*/
61559SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
61560  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
61561  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
61562  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
61563  return 0;
61564}
61565
61566/*
61567** Return true if we are able to the IN operator optimization on a
61568** query of the form
61569**
61570**       x IN (SELECT ...)
61571**
61572** Where the SELECT... clause is as specified by the parameter to this
61573** routine.
61574**
61575** The Select object passed in has already been preprocessed and no
61576** errors have been found.
61577*/
61578#ifndef SQLITE_OMIT_SUBQUERY
61579static int isCandidateForInOpt(Select *p){
61580  SrcList *pSrc;
61581  ExprList *pEList;
61582  Table *pTab;
61583  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
61584  if( p->pPrior ) return 0;              /* Not a compound SELECT */
61585  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
61586    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
61587    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
61588    return 0; /* No DISTINCT keyword and no aggregate functions */
61589  }
61590  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
61591  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
61592  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
61593  if( p->pWhere ) return 0;              /* Has no WHERE clause */
61594  pSrc = p->pSrc;
61595  assert( pSrc!=0 );
61596  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
61597  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
61598  pTab = pSrc->a[0].pTab;
61599  if( NEVER(pTab==0) ) return 0;
61600  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
61601  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
61602  pEList = p->pEList;
61603  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
61604  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
61605  return 1;
61606}
61607#endif /* SQLITE_OMIT_SUBQUERY */
61608
61609/*
61610** This function is used by the implementation of the IN (...) operator.
61611** It's job is to find or create a b-tree structure that may be used
61612** either to test for membership of the (...) set or to iterate through
61613** its members, skipping duplicates.
61614**
61615** The index of the cursor opened on the b-tree (database table, database index
61616** or ephermal table) is stored in pX->iTable before this function returns.
61617** The returned value of this function indicates the b-tree type, as follows:
61618**
61619**   IN_INDEX_ROWID - The cursor was opened on a database table.
61620**   IN_INDEX_INDEX - The cursor was opened on a database index.
61621**   IN_INDEX_EPH -   The cursor was opened on a specially created and
61622**                    populated epheremal table.
61623**
61624** An existing b-tree may only be used if the SELECT is of the simple
61625** form:
61626**
61627**     SELECT <column> FROM <table>
61628**
61629** If the prNotFound parameter is 0, then the b-tree will be used to iterate
61630** through the set members, skipping any duplicates. In this case an
61631** epheremal table must be used unless the selected <column> is guaranteed
61632** to be unique - either because it is an INTEGER PRIMARY KEY or it
61633** has a UNIQUE constraint or UNIQUE index.
61634**
61635** If the prNotFound parameter is not 0, then the b-tree will be used
61636** for fast set membership tests. In this case an epheremal table must
61637** be used unless <column> is an INTEGER PRIMARY KEY or an index can
61638** be found with <column> as its left-most column.
61639**
61640** When the b-tree is being used for membership tests, the calling function
61641** needs to know whether or not the structure contains an SQL NULL
61642** value in order to correctly evaluate expressions like "X IN (Y, Z)".
61643** If there is any chance that the (...) might contain a NULL value at
61644** runtime, then a register is allocated and the register number written
61645** to *prNotFound. If there is no chance that the (...) contains a
61646** NULL value, then *prNotFound is left unchanged.
61647**
61648** If a register is allocated and its location stored in *prNotFound, then
61649** its initial value is NULL.  If the (...) does not remain constant
61650** for the duration of the query (i.e. the SELECT within the (...)
61651** is a correlated subquery) then the value of the allocated register is
61652** reset to NULL each time the subquery is rerun. This allows the
61653** caller to use vdbe code equivalent to the following:
61654**
61655**   if( register==NULL ){
61656**     has_null = <test if data structure contains null>
61657**     register = 1
61658**   }
61659**
61660** in order to avoid running the <test if data structure contains null>
61661** test more often than is necessary.
61662*/
61663#ifndef SQLITE_OMIT_SUBQUERY
61664SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
61665  Select *p;                            /* SELECT to the right of IN operator */
61666  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
61667  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
61668  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
61669
61670  assert( pX->op==TK_IN );
61671
61672  /* Check to see if an existing table or index can be used to
61673  ** satisfy the query.  This is preferable to generating a new
61674  ** ephemeral table.
61675  */
61676  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
61677  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
61678    sqlite3 *db = pParse->db;              /* Database connection */
61679    Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
61680    int iCol = pExpr->iColumn;             /* Index of column <column> */
61681    Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
61682    Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
61683    int iDb;                               /* Database idx for pTab */
61684
61685    /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
61686    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
61687    sqlite3CodeVerifySchema(pParse, iDb);
61688    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
61689
61690    /* This function is only called from two places. In both cases the vdbe
61691    ** has already been allocated. So assume sqlite3GetVdbe() is always
61692    ** successful here.
61693    */
61694    assert(v);
61695    if( iCol<0 ){
61696      int iMem = ++pParse->nMem;
61697      int iAddr;
61698
61699      iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
61700      sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
61701
61702      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
61703      eType = IN_INDEX_ROWID;
61704
61705      sqlite3VdbeJumpHere(v, iAddr);
61706    }else{
61707      Index *pIdx;                         /* Iterator variable */
61708
61709      /* The collation sequence used by the comparison. If an index is to
61710      ** be used in place of a temp-table, it must be ordered according
61711      ** to this collation sequence.  */
61712      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
61713
61714      /* Check that the affinity that will be used to perform the
61715      ** comparison is the same as the affinity of the column. If
61716      ** it is not, it is not possible to use any index.
61717      */
61718      char aff = comparisonAffinity(pX);
61719      int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
61720
61721      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
61722        if( (pIdx->aiColumn[0]==iCol)
61723         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
61724         && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
61725        ){
61726          int iMem = ++pParse->nMem;
61727          int iAddr;
61728          char *pKey;
61729
61730          pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
61731          iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
61732          sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
61733
61734          sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
61735                               pKey,P4_KEYINFO_HANDOFF);
61736          VdbeComment((v, "%s", pIdx->zName));
61737          eType = IN_INDEX_INDEX;
61738
61739          sqlite3VdbeJumpHere(v, iAddr);
61740          if( prNotFound && !pTab->aCol[iCol].notNull ){
61741            *prNotFound = ++pParse->nMem;
61742          }
61743        }
61744      }
61745    }
61746  }
61747
61748  if( eType==0 ){
61749    /* Could not found an existing table or index to use as the RHS b-tree.
61750    ** We will have to generate an ephemeral table to do the job.
61751    */
61752    int rMayHaveNull = 0;
61753    eType = IN_INDEX_EPH;
61754    if( prNotFound ){
61755      *prNotFound = rMayHaveNull = ++pParse->nMem;
61756    }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
61757      eType = IN_INDEX_ROWID;
61758    }
61759    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
61760  }else{
61761    pX->iTable = iTab;
61762  }
61763  return eType;
61764}
61765#endif
61766
61767/*
61768** Generate code for scalar subqueries used as an expression
61769** and IN operators.  Examples:
61770**
61771**     (SELECT a FROM b)          -- subquery
61772**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
61773**     x IN (4,5,11)              -- IN operator with list on right-hand side
61774**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
61775**
61776** The pExpr parameter describes the expression that contains the IN
61777** operator or subquery.
61778**
61779** If parameter isRowid is non-zero, then expression pExpr is guaranteed
61780** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
61781** to some integer key column of a table B-Tree. In this case, use an
61782** intkey B-Tree to store the set of IN(...) values instead of the usual
61783** (slower) variable length keys B-Tree.
61784**
61785** If rMayHaveNull is non-zero, that means that the operation is an IN
61786** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
61787** Furthermore, the IN is in a WHERE clause and that we really want
61788** to iterate over the RHS of the IN operator in order to quickly locate
61789** all corresponding LHS elements.  All this routine does is initialize
61790** the register given by rMayHaveNull to NULL.  Calling routines will take
61791** care of changing this register value to non-NULL if the RHS is NULL-free.
61792**
61793** If rMayHaveNull is zero, that means that the subquery is being used
61794** for membership testing only.  There is no need to initialize any
61795** registers to indicate the presense or absence of NULLs on the RHS.
61796**
61797** For a SELECT or EXISTS operator, return the register that holds the
61798** result.  For IN operators or if an error occurs, the return value is 0.
61799*/
61800#ifndef SQLITE_OMIT_SUBQUERY
61801SQLITE_PRIVATE int sqlite3CodeSubselect(
61802  Parse *pParse,          /* Parsing context */
61803  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
61804  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
61805  int isRowid             /* If true, LHS of IN operator is a rowid */
61806){
61807  int testAddr = 0;                       /* One-time test address */
61808  int rReg = 0;                           /* Register storing resulting */
61809  Vdbe *v = sqlite3GetVdbe(pParse);
61810  if( NEVER(v==0) ) return 0;
61811  sqlite3ExprCachePush(pParse);
61812
61813  /* This code must be run in its entirety every time it is encountered
61814  ** if any of the following is true:
61815  **
61816  **    *  The right-hand side is a correlated subquery
61817  **    *  The right-hand side is an expression list containing variables
61818  **    *  We are inside a trigger
61819  **
61820  ** If all of the above are false, then we can run this code just once
61821  ** save the results, and reuse the same result on subsequent invocations.
61822  */
61823  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
61824    int mem = ++pParse->nMem;
61825    sqlite3VdbeAddOp1(v, OP_If, mem);
61826    testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
61827    assert( testAddr>0 || pParse->db->mallocFailed );
61828  }
61829
61830  switch( pExpr->op ){
61831    case TK_IN: {
61832      char affinity;
61833      KeyInfo keyInfo;
61834      int addr;        /* Address of OP_OpenEphemeral instruction */
61835      Expr *pLeft = pExpr->pLeft;
61836
61837      if( rMayHaveNull ){
61838        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
61839      }
61840
61841      affinity = sqlite3ExprAffinity(pLeft);
61842
61843      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
61844      ** expression it is handled the same way.  An ephemeral table is
61845      ** filled with single-field index keys representing the results
61846      ** from the SELECT or the <exprlist>.
61847      **
61848      ** If the 'x' expression is a column value, or the SELECT...
61849      ** statement returns a column value, then the affinity of that
61850      ** column is used to build the index keys. If both 'x' and the
61851      ** SELECT... statement are columns, then numeric affinity is used
61852      ** if either column has NUMERIC or INTEGER affinity. If neither
61853      ** 'x' nor the SELECT... statement are columns, then numeric affinity
61854      ** is used.
61855      */
61856      pExpr->iTable = pParse->nTab++;
61857      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
61858      memset(&keyInfo, 0, sizeof(keyInfo));
61859      keyInfo.nField = 1;
61860
61861      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
61862        /* Case 1:     expr IN (SELECT ...)
61863        **
61864        ** Generate code to write the results of the select into the temporary
61865        ** table allocated and opened above.
61866        */
61867        SelectDest dest;
61868        ExprList *pEList;
61869
61870        assert( !isRowid );
61871        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
61872        dest.affinity = (u8)affinity;
61873        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
61874        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
61875          return 0;
61876        }
61877        pEList = pExpr->x.pSelect->pEList;
61878        if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
61879          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
61880              pEList->a[0].pExpr);
61881        }
61882      }else if( pExpr->x.pList!=0 ){
61883        /* Case 2:     expr IN (exprlist)
61884        **
61885        ** For each expression, build an index key from the evaluation and
61886        ** store it in the temporary table. If <expr> is a column, then use
61887        ** that columns affinity when building index keys. If <expr> is not
61888        ** a column, use numeric affinity.
61889        */
61890        int i;
61891        ExprList *pList = pExpr->x.pList;
61892        struct ExprList_item *pItem;
61893        int r1, r2, r3;
61894
61895        if( !affinity ){
61896          affinity = SQLITE_AFF_NONE;
61897        }
61898        keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
61899
61900        /* Loop through each expression in <exprlist>. */
61901        r1 = sqlite3GetTempReg(pParse);
61902        r2 = sqlite3GetTempReg(pParse);
61903        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
61904        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
61905          Expr *pE2 = pItem->pExpr;
61906          int iValToIns;
61907
61908          /* If the expression is not constant then we will need to
61909          ** disable the test that was generated above that makes sure
61910          ** this code only executes once.  Because for a non-constant
61911          ** expression we need to rerun this code each time.
61912          */
61913          if( testAddr && !sqlite3ExprIsConstant(pE2) ){
61914            sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
61915            testAddr = 0;
61916          }
61917
61918          /* Evaluate the expression and insert it into the temp table */
61919          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
61920            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
61921          }else{
61922            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
61923            if( isRowid ){
61924              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
61925                                sqlite3VdbeCurrentAddr(v)+2);
61926              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
61927            }else{
61928              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
61929              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
61930              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
61931            }
61932          }
61933        }
61934        sqlite3ReleaseTempReg(pParse, r1);
61935        sqlite3ReleaseTempReg(pParse, r2);
61936      }
61937      if( !isRowid ){
61938        sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
61939      }
61940      break;
61941    }
61942
61943    case TK_EXISTS:
61944    case TK_SELECT:
61945    default: {
61946      /* If this has to be a scalar SELECT.  Generate code to put the
61947      ** value of this select in a memory cell and record the number
61948      ** of the memory cell in iColumn.  If this is an EXISTS, write
61949      ** an integer 0 (not exists) or 1 (exists) into a memory cell
61950      ** and record that memory cell in iColumn.
61951      */
61952      static const Token one = { "1", 1 };  /* Token for literal value 1 */
61953      Select *pSel;                         /* SELECT statement to encode */
61954      SelectDest dest;                      /* How to deal with SELECt result */
61955
61956      testcase( pExpr->op==TK_EXISTS );
61957      testcase( pExpr->op==TK_SELECT );
61958      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
61959
61960      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
61961      pSel = pExpr->x.pSelect;
61962      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
61963      if( pExpr->op==TK_SELECT ){
61964        dest.eDest = SRT_Mem;
61965        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
61966        VdbeComment((v, "Init subquery result"));
61967      }else{
61968        dest.eDest = SRT_Exists;
61969        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
61970        VdbeComment((v, "Init EXISTS result"));
61971      }
61972      sqlite3ExprDelete(pParse->db, pSel->pLimit);
61973      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
61974      if( sqlite3Select(pParse, pSel, &dest) ){
61975        return 0;
61976      }
61977      rReg = dest.iParm;
61978      ExprSetIrreducible(pExpr);
61979      break;
61980    }
61981  }
61982
61983  if( testAddr ){
61984    sqlite3VdbeJumpHere(v, testAddr-1);
61985  }
61986  sqlite3ExprCachePop(pParse, 1);
61987
61988  return rReg;
61989}
61990#endif /* SQLITE_OMIT_SUBQUERY */
61991
61992#ifndef SQLITE_OMIT_SUBQUERY
61993/*
61994** Generate code for an IN expression.
61995**
61996**      x IN (SELECT ...)
61997**      x IN (value, value, ...)
61998**
61999** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
62000** is an array of zero or more values.  The expression is true if the LHS is
62001** contained within the RHS.  The value of the expression is unknown (NULL)
62002** if the LHS is NULL or if the LHS is not contained within the RHS and the
62003** RHS contains one or more NULL values.
62004**
62005** This routine generates code will jump to destIfFalse if the LHS is not
62006** contained within the RHS.  If due to NULLs we cannot determine if the LHS
62007** is contained in the RHS then jump to destIfNull.  If the LHS is contained
62008** within the RHS then fall through.
62009*/
62010static void sqlite3ExprCodeIN(
62011  Parse *pParse,        /* Parsing and code generating context */
62012  Expr *pExpr,          /* The IN expression */
62013  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
62014  int destIfNull        /* Jump here if the results are unknown due to NULLs */
62015){
62016  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
62017  char affinity;        /* Comparison affinity to use */
62018  int eType;            /* Type of the RHS */
62019  int r1;               /* Temporary use register */
62020  Vdbe *v;              /* Statement under construction */
62021
62022  /* Compute the RHS.   After this step, the table with cursor
62023  ** pExpr->iTable will contains the values that make up the RHS.
62024  */
62025  v = pParse->pVdbe;
62026  assert( v!=0 );       /* OOM detected prior to this routine */
62027  VdbeNoopComment((v, "begin IN expr"));
62028  eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
62029
62030  /* Figure out the affinity to use to create a key from the results
62031  ** of the expression. affinityStr stores a static string suitable for
62032  ** P4 of OP_MakeRecord.
62033  */
62034  affinity = comparisonAffinity(pExpr);
62035
62036  /* Code the LHS, the <expr> from "<expr> IN (...)".
62037  */
62038  sqlite3ExprCachePush(pParse);
62039  r1 = sqlite3GetTempReg(pParse);
62040  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
62041  sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
62042
62043
62044  if( eType==IN_INDEX_ROWID ){
62045    /* In this case, the RHS is the ROWID of table b-tree
62046    */
62047    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
62048    sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
62049  }else{
62050    /* In this case, the RHS is an index b-tree.
62051    */
62052    sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
62053
62054    /* If the set membership test fails, then the result of the
62055    ** "x IN (...)" expression must be either 0 or NULL. If the set
62056    ** contains no NULL values, then the result is 0. If the set
62057    ** contains one or more NULL values, then the result of the
62058    ** expression is also NULL.
62059    */
62060    if( rRhsHasNull==0 || destIfFalse==destIfNull ){
62061      /* This branch runs if it is known at compile time that the RHS
62062      ** cannot contain NULL values. This happens as the result
62063      ** of a "NOT NULL" constraint in the database schema.
62064      **
62065      ** Also run this branch if NULL is equivalent to FALSE
62066      ** for this particular IN operator.
62067      */
62068      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
62069
62070    }else{
62071      /* In this branch, the RHS of the IN might contain a NULL and
62072      ** the presence of a NULL on the RHS makes a difference in the
62073      ** outcome.
62074      */
62075      int j1, j2, j3;
62076
62077      /* First check to see if the LHS is contained in the RHS.  If so,
62078      ** then the presence of NULLs in the RHS does not matter, so jump
62079      ** over all of the code that follows.
62080      */
62081      j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
62082
62083      /* Here we begin generating code that runs if the LHS is not
62084      ** contained within the RHS.  Generate additional code that
62085      ** tests the RHS for NULLs.  If the RHS contains a NULL then
62086      ** jump to destIfNull.  If there are no NULLs in the RHS then
62087      ** jump to destIfFalse.
62088      */
62089      j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
62090      j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
62091      sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
62092      sqlite3VdbeJumpHere(v, j3);
62093      sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
62094      sqlite3VdbeJumpHere(v, j2);
62095
62096      /* Jump to the appropriate target depending on whether or not
62097      ** the RHS contains a NULL
62098      */
62099      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
62100      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
62101
62102      /* The OP_Found at the top of this branch jumps here when true,
62103      ** causing the overall IN expression evaluation to fall through.
62104      */
62105      sqlite3VdbeJumpHere(v, j1);
62106    }
62107  }
62108  sqlite3ReleaseTempReg(pParse, r1);
62109  sqlite3ExprCachePop(pParse, 1);
62110  VdbeComment((v, "end IN expr"));
62111}
62112#endif /* SQLITE_OMIT_SUBQUERY */
62113
62114/*
62115** Duplicate an 8-byte value
62116*/
62117static char *dup8bytes(Vdbe *v, const char *in){
62118  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
62119  if( out ){
62120    memcpy(out, in, 8);
62121  }
62122  return out;
62123}
62124
62125/*
62126** Generate an instruction that will put the floating point
62127** value described by z[0..n-1] into register iMem.
62128**
62129** The z[] string will probably not be zero-terminated.  But the
62130** z[n] character is guaranteed to be something that does not look
62131** like the continuation of the number.
62132*/
62133static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
62134  if( ALWAYS(z!=0) ){
62135    double value;
62136    char *zV;
62137    sqlite3AtoF(z, &value);
62138    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
62139    if( negateFlag ) value = -value;
62140    zV = dup8bytes(v, (char*)&value);
62141    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
62142  }
62143}
62144
62145
62146/*
62147** Generate an instruction that will put the integer describe by
62148** text z[0..n-1] into register iMem.
62149**
62150** The z[] string will probably not be zero-terminated.  But the
62151** z[n] character is guaranteed to be something that does not look
62152** like the continuation of the number.
62153*/
62154static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){
62155  if( pExpr->flags & EP_IntValue ){
62156    int i = pExpr->u.iValue;
62157    if( negFlag ) i = -i;
62158    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
62159  }else{
62160    const char *z = pExpr->u.zToken;
62161    assert( z!=0 );
62162    if( sqlite3FitsIn64Bits(z, negFlag) ){
62163      i64 value;
62164      char *zV;
62165      sqlite3Atoi64(z, &value);
62166      if( negFlag ) value = -value;
62167      zV = dup8bytes(v, (char*)&value);
62168      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
62169    }else{
62170      codeReal(v, z, negFlag, iMem);
62171    }
62172  }
62173}
62174
62175/*
62176** Clear a cache entry.
62177*/
62178static void cacheEntryClear(Parse *pParse, struct yColCache *p){
62179  if( p->tempReg ){
62180    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
62181      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
62182    }
62183    p->tempReg = 0;
62184  }
62185}
62186
62187
62188/*
62189** Record in the column cache that a particular column from a
62190** particular table is stored in a particular register.
62191*/
62192SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
62193  int i;
62194  int minLru;
62195  int idxLru;
62196  struct yColCache *p;
62197
62198  assert( iReg>0 );  /* Register numbers are always positive */
62199  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
62200
62201  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
62202  ** for testing only - to verify that SQLite always gets the same answer
62203  ** with and without the column cache.
62204  */
62205  if( pParse->db->flags & SQLITE_ColumnCache ) return;
62206
62207  /* First replace any existing entry.
62208  **
62209  ** Actually, the way the column cache is currently used, we are guaranteed
62210  ** that the object will never already be in cache.  Verify this guarantee.
62211  */
62212#ifndef NDEBUG
62213  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62214#if 0 /* This code wold remove the entry from the cache if it existed */
62215    if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
62216      cacheEntryClear(pParse, p);
62217      p->iLevel = pParse->iCacheLevel;
62218      p->iReg = iReg;
62219      p->lru = pParse->iCacheCnt++;
62220      return;
62221    }
62222#endif
62223    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
62224  }
62225#endif
62226
62227  /* Find an empty slot and replace it */
62228  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62229    if( p->iReg==0 ){
62230      p->iLevel = pParse->iCacheLevel;
62231      p->iTable = iTab;
62232      p->iColumn = iCol;
62233      p->iReg = iReg;
62234      p->tempReg = 0;
62235      p->lru = pParse->iCacheCnt++;
62236      return;
62237    }
62238  }
62239
62240  /* Replace the last recently used */
62241  minLru = 0x7fffffff;
62242  idxLru = -1;
62243  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62244    if( p->lru<minLru ){
62245      idxLru = i;
62246      minLru = p->lru;
62247    }
62248  }
62249  if( ALWAYS(idxLru>=0) ){
62250    p = &pParse->aColCache[idxLru];
62251    p->iLevel = pParse->iCacheLevel;
62252    p->iTable = iTab;
62253    p->iColumn = iCol;
62254    p->iReg = iReg;
62255    p->tempReg = 0;
62256    p->lru = pParse->iCacheCnt++;
62257    return;
62258  }
62259}
62260
62261/*
62262** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
62263** Purge the range of registers from the column cache.
62264*/
62265SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
62266  int i;
62267  int iLast = iReg + nReg - 1;
62268  struct yColCache *p;
62269  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62270    int r = p->iReg;
62271    if( r>=iReg && r<=iLast ){
62272      cacheEntryClear(pParse, p);
62273      p->iReg = 0;
62274    }
62275  }
62276}
62277
62278/*
62279** Remember the current column cache context.  Any new entries added
62280** added to the column cache after this call are removed when the
62281** corresponding pop occurs.
62282*/
62283SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
62284  pParse->iCacheLevel++;
62285}
62286
62287/*
62288** Remove from the column cache any entries that were added since the
62289** the previous N Push operations.  In other words, restore the cache
62290** to the state it was in N Pushes ago.
62291*/
62292SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
62293  int i;
62294  struct yColCache *p;
62295  assert( N>0 );
62296  assert( pParse->iCacheLevel>=N );
62297  pParse->iCacheLevel -= N;
62298  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62299    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
62300      cacheEntryClear(pParse, p);
62301      p->iReg = 0;
62302    }
62303  }
62304}
62305
62306/*
62307** When a cached column is reused, make sure that its register is
62308** no longer available as a temp register.  ticket #3879:  that same
62309** register might be in the cache in multiple places, so be sure to
62310** get them all.
62311*/
62312static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
62313  int i;
62314  struct yColCache *p;
62315  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62316    if( p->iReg==iReg ){
62317      p->tempReg = 0;
62318    }
62319  }
62320}
62321
62322/*
62323** Generate code that will extract the iColumn-th column from
62324** table pTab and store the column value in a register.  An effort
62325** is made to store the column value in register iReg, but this is
62326** not guaranteed.  The location of the column value is returned.
62327**
62328** There must be an open cursor to pTab in iTable when this routine
62329** is called.  If iColumn<0 then code is generated that extracts the rowid.
62330*/
62331SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
62332  Parse *pParse,   /* Parsing and code generating context */
62333  Table *pTab,     /* Description of the table we are reading from */
62334  int iColumn,     /* Index of the table column */
62335  int iTable,      /* The cursor pointing to the table */
62336  int iReg         /* Store results here */
62337){
62338  Vdbe *v = pParse->pVdbe;
62339  int i;
62340  struct yColCache *p;
62341
62342  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62343    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
62344      p->lru = pParse->iCacheCnt++;
62345      sqlite3ExprCachePinRegister(pParse, p->iReg);
62346      return p->iReg;
62347    }
62348  }
62349  assert( v!=0 );
62350  if( iColumn<0 ){
62351    sqlite3VdbeAddOp2(v, OP_Rowid, iTable, iReg);
62352  }else if( ALWAYS(pTab!=0) ){
62353    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
62354    sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
62355    sqlite3ColumnDefault(v, pTab, iColumn, iReg);
62356  }
62357  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
62358  return iReg;
62359}
62360
62361/*
62362** Clear all column cache entries.
62363*/
62364SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
62365  int i;
62366  struct yColCache *p;
62367
62368  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62369    if( p->iReg ){
62370      cacheEntryClear(pParse, p);
62371      p->iReg = 0;
62372    }
62373  }
62374}
62375
62376/*
62377** Record the fact that an affinity change has occurred on iCount
62378** registers starting with iStart.
62379*/
62380SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
62381  sqlite3ExprCacheRemove(pParse, iStart, iCount);
62382}
62383
62384/*
62385** Generate code to move content from registers iFrom...iFrom+nReg-1
62386** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
62387*/
62388SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
62389  int i;
62390  struct yColCache *p;
62391  if( NEVER(iFrom==iTo) ) return;
62392  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
62393  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62394    int x = p->iReg;
62395    if( x>=iFrom && x<iFrom+nReg ){
62396      p->iReg += iTo-iFrom;
62397    }
62398  }
62399}
62400
62401/*
62402** Generate code to copy content from registers iFrom...iFrom+nReg-1
62403** over to iTo..iTo+nReg-1.
62404*/
62405SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
62406  int i;
62407  if( NEVER(iFrom==iTo) ) return;
62408  for(i=0; i<nReg; i++){
62409    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
62410  }
62411}
62412
62413#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
62414/*
62415** Return true if any register in the range iFrom..iTo (inclusive)
62416** is used as part of the column cache.
62417**
62418** This routine is used within assert() and testcase() macros only
62419** and does not appear in a normal build.
62420*/
62421static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
62422  int i;
62423  struct yColCache *p;
62424  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
62425    int r = p->iReg;
62426    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
62427  }
62428  return 0;
62429}
62430#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
62431
62432/*
62433** If the last instruction coded is an ephemeral copy of any of
62434** the registers in the nReg registers beginning with iReg, then
62435** convert the last instruction from OP_SCopy to OP_Copy.
62436*/
62437SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
62438  VdbeOp *pOp;
62439  Vdbe *v;
62440
62441  assert( pParse->db->mallocFailed==0 );
62442  v = pParse->pVdbe;
62443  assert( v!=0 );
62444  pOp = sqlite3VdbeGetOp(v, -1);
62445  assert( pOp!=0 );
62446  if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
62447    pOp->opcode = OP_Copy;
62448  }
62449}
62450
62451/*
62452** Generate code to store the value of the iAlias-th alias in register
62453** target.  The first time this is called, pExpr is evaluated to compute
62454** the value of the alias.  The value is stored in an auxiliary register
62455** and the number of that register is returned.  On subsequent calls,
62456** the register number is returned without generating any code.
62457**
62458** Note that in order for this to work, code must be generated in the
62459** same order that it is executed.
62460**
62461** Aliases are numbered starting with 1.  So iAlias is in the range
62462** of 1 to pParse->nAlias inclusive.
62463**
62464** pParse->aAlias[iAlias-1] records the register number where the value
62465** of the iAlias-th alias is stored.  If zero, that means that the
62466** alias has not yet been computed.
62467*/
62468static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
62469#if 0
62470  sqlite3 *db = pParse->db;
62471  int iReg;
62472  if( pParse->nAliasAlloc<pParse->nAlias ){
62473    pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
62474                                 sizeof(pParse->aAlias[0])*pParse->nAlias );
62475    testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
62476    if( db->mallocFailed ) return 0;
62477    memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
62478           (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
62479    pParse->nAliasAlloc = pParse->nAlias;
62480  }
62481  assert( iAlias>0 && iAlias<=pParse->nAlias );
62482  iReg = pParse->aAlias[iAlias-1];
62483  if( iReg==0 ){
62484    if( pParse->iCacheLevel>0 ){
62485      iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
62486    }else{
62487      iReg = ++pParse->nMem;
62488      sqlite3ExprCode(pParse, pExpr, iReg);
62489      pParse->aAlias[iAlias-1] = iReg;
62490    }
62491  }
62492  return iReg;
62493#else
62494  UNUSED_PARAMETER(iAlias);
62495  return sqlite3ExprCodeTarget(pParse, pExpr, target);
62496#endif
62497}
62498
62499/*
62500** Generate code into the current Vdbe to evaluate the given
62501** expression.  Attempt to store the results in register "target".
62502** Return the register where results are stored.
62503**
62504** With this routine, there is no guarantee that results will
62505** be stored in target.  The result might be stored in some other
62506** register if it is convenient to do so.  The calling function
62507** must check the return code and move the results to the desired
62508** register.
62509*/
62510SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
62511  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
62512  int op;                   /* The opcode being coded */
62513  int inReg = target;       /* Results stored in register inReg */
62514  int regFree1 = 0;         /* If non-zero free this temporary register */
62515  int regFree2 = 0;         /* If non-zero free this temporary register */
62516  int r1, r2, r3, r4;       /* Various register numbers */
62517  sqlite3 *db = pParse->db; /* The database connection */
62518
62519  assert( target>0 && target<=pParse->nMem );
62520  if( v==0 ){
62521    assert( pParse->db->mallocFailed );
62522    return 0;
62523  }
62524
62525  if( pExpr==0 ){
62526    op = TK_NULL;
62527  }else{
62528    op = pExpr->op;
62529  }
62530  switch( op ){
62531    case TK_AGG_COLUMN: {
62532      AggInfo *pAggInfo = pExpr->pAggInfo;
62533      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
62534      if( !pAggInfo->directMode ){
62535        assert( pCol->iMem>0 );
62536        inReg = pCol->iMem;
62537        break;
62538      }else if( pAggInfo->useSortingIdx ){
62539        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
62540                              pCol->iSorterColumn, target);
62541        break;
62542      }
62543      /* Otherwise, fall thru into the TK_COLUMN case */
62544    }
62545    case TK_COLUMN: {
62546      if( pExpr->iTable<0 ){
62547        /* This only happens when coding check constraints */
62548        assert( pParse->ckBase>0 );
62549        inReg = pExpr->iColumn + pParse->ckBase;
62550      }else{
62551        inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
62552                                 pExpr->iColumn, pExpr->iTable, target);
62553      }
62554      break;
62555    }
62556    case TK_INTEGER: {
62557      codeInteger(v, pExpr, 0, target);
62558      break;
62559    }
62560    case TK_FLOAT: {
62561      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62562      codeReal(v, pExpr->u.zToken, 0, target);
62563      break;
62564    }
62565    case TK_STRING: {
62566      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62567      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
62568      break;
62569    }
62570    case TK_NULL: {
62571      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
62572      break;
62573    }
62574#ifndef SQLITE_OMIT_BLOB_LITERAL
62575    case TK_BLOB: {
62576      int n;
62577      const char *z;
62578      char *zBlob;
62579      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62580      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
62581      assert( pExpr->u.zToken[1]=='\'' );
62582      z = &pExpr->u.zToken[2];
62583      n = sqlite3Strlen30(z) - 1;
62584      assert( z[n]=='\'' );
62585      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
62586      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
62587      break;
62588    }
62589#endif
62590    case TK_VARIABLE: {
62591      VdbeOp *pOp;
62592      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62593      assert( pExpr->u.zToken!=0 );
62594      assert( pExpr->u.zToken[0]!=0 );
62595      if( pExpr->u.zToken[1]==0
62596         && (pOp = sqlite3VdbeGetOp(v, -1))->opcode==OP_Variable
62597         && pOp->p1+pOp->p3==pExpr->iColumn
62598         && pOp->p2+pOp->p3==target
62599         && pOp->p4.z==0
62600      ){
62601        /* If the previous instruction was a copy of the previous unnamed
62602        ** parameter into the previous register, then simply increment the
62603        ** repeat count on the prior instruction rather than making a new
62604        ** instruction.
62605        */
62606        pOp->p3++;
62607      }else{
62608        sqlite3VdbeAddOp3(v, OP_Variable, pExpr->iColumn, target, 1);
62609        if( pExpr->u.zToken[1]!=0 ){
62610          sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
62611        }
62612      }
62613      break;
62614    }
62615    case TK_REGISTER: {
62616      inReg = pExpr->iTable;
62617      break;
62618    }
62619    case TK_AS: {
62620      inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
62621      break;
62622    }
62623#ifndef SQLITE_OMIT_CAST
62624    case TK_CAST: {
62625      /* Expressions of the form:   CAST(pLeft AS token) */
62626      int aff, to_op;
62627      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
62628      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62629      aff = sqlite3AffinityType(pExpr->u.zToken);
62630      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
62631      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
62632      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
62633      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
62634      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
62635      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
62636      testcase( to_op==OP_ToText );
62637      testcase( to_op==OP_ToBlob );
62638      testcase( to_op==OP_ToNumeric );
62639      testcase( to_op==OP_ToInt );
62640      testcase( to_op==OP_ToReal );
62641      if( inReg!=target ){
62642        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
62643        inReg = target;
62644      }
62645      sqlite3VdbeAddOp1(v, to_op, inReg);
62646      testcase( usedAsColumnCache(pParse, inReg, inReg) );
62647      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
62648      break;
62649    }
62650#endif /* SQLITE_OMIT_CAST */
62651    case TK_LT:
62652    case TK_LE:
62653    case TK_GT:
62654    case TK_GE:
62655    case TK_NE:
62656    case TK_EQ: {
62657      assert( TK_LT==OP_Lt );
62658      assert( TK_LE==OP_Le );
62659      assert( TK_GT==OP_Gt );
62660      assert( TK_GE==OP_Ge );
62661      assert( TK_EQ==OP_Eq );
62662      assert( TK_NE==OP_Ne );
62663      testcase( op==TK_LT );
62664      testcase( op==TK_LE );
62665      testcase( op==TK_GT );
62666      testcase( op==TK_GE );
62667      testcase( op==TK_EQ );
62668      testcase( op==TK_NE );
62669      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62670      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62671      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
62672                  r1, r2, inReg, SQLITE_STOREP2);
62673      testcase( regFree1==0 );
62674      testcase( regFree2==0 );
62675      break;
62676    }
62677    case TK_IS:
62678    case TK_ISNOT: {
62679      testcase( op==TK_IS );
62680      testcase( op==TK_ISNOT );
62681      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62682      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62683      op = (op==TK_IS) ? TK_EQ : TK_NE;
62684      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
62685                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
62686      testcase( regFree1==0 );
62687      testcase( regFree2==0 );
62688      break;
62689    }
62690    case TK_AND:
62691    case TK_OR:
62692    case TK_PLUS:
62693    case TK_STAR:
62694    case TK_MINUS:
62695    case TK_REM:
62696    case TK_BITAND:
62697    case TK_BITOR:
62698    case TK_SLASH:
62699    case TK_LSHIFT:
62700    case TK_RSHIFT:
62701    case TK_CONCAT: {
62702      assert( TK_AND==OP_And );
62703      assert( TK_OR==OP_Or );
62704      assert( TK_PLUS==OP_Add );
62705      assert( TK_MINUS==OP_Subtract );
62706      assert( TK_REM==OP_Remainder );
62707      assert( TK_BITAND==OP_BitAnd );
62708      assert( TK_BITOR==OP_BitOr );
62709      assert( TK_SLASH==OP_Divide );
62710      assert( TK_LSHIFT==OP_ShiftLeft );
62711      assert( TK_RSHIFT==OP_ShiftRight );
62712      assert( TK_CONCAT==OP_Concat );
62713      testcase( op==TK_AND );
62714      testcase( op==TK_OR );
62715      testcase( op==TK_PLUS );
62716      testcase( op==TK_MINUS );
62717      testcase( op==TK_REM );
62718      testcase( op==TK_BITAND );
62719      testcase( op==TK_BITOR );
62720      testcase( op==TK_SLASH );
62721      testcase( op==TK_LSHIFT );
62722      testcase( op==TK_RSHIFT );
62723      testcase( op==TK_CONCAT );
62724      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62725      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
62726      sqlite3VdbeAddOp3(v, op, r2, r1, target);
62727      testcase( regFree1==0 );
62728      testcase( regFree2==0 );
62729      break;
62730    }
62731    case TK_UMINUS: {
62732      Expr *pLeft = pExpr->pLeft;
62733      assert( pLeft );
62734      if( pLeft->op==TK_FLOAT ){
62735        assert( !ExprHasProperty(pExpr, EP_IntValue) );
62736        codeReal(v, pLeft->u.zToken, 1, target);
62737      }else if( pLeft->op==TK_INTEGER ){
62738        codeInteger(v, pLeft, 1, target);
62739      }else{
62740        regFree1 = r1 = sqlite3GetTempReg(pParse);
62741        sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
62742        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
62743        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
62744        testcase( regFree2==0 );
62745      }
62746      inReg = target;
62747      break;
62748    }
62749    case TK_BITNOT:
62750    case TK_NOT: {
62751      assert( TK_BITNOT==OP_BitNot );
62752      assert( TK_NOT==OP_Not );
62753      testcase( op==TK_BITNOT );
62754      testcase( op==TK_NOT );
62755      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62756      testcase( regFree1==0 );
62757      inReg = target;
62758      sqlite3VdbeAddOp2(v, op, r1, inReg);
62759      break;
62760    }
62761    case TK_ISNULL:
62762    case TK_NOTNULL: {
62763      int addr;
62764      assert( TK_ISNULL==OP_IsNull );
62765      assert( TK_NOTNULL==OP_NotNull );
62766      testcase( op==TK_ISNULL );
62767      testcase( op==TK_NOTNULL );
62768      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
62769      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
62770      testcase( regFree1==0 );
62771      addr = sqlite3VdbeAddOp1(v, op, r1);
62772      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
62773      sqlite3VdbeJumpHere(v, addr);
62774      break;
62775    }
62776    case TK_AGG_FUNCTION: {
62777      AggInfo *pInfo = pExpr->pAggInfo;
62778      if( pInfo==0 ){
62779        assert( !ExprHasProperty(pExpr, EP_IntValue) );
62780        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
62781      }else{
62782        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
62783      }
62784      break;
62785    }
62786    case TK_CONST_FUNC:
62787    case TK_FUNCTION: {
62788      ExprList *pFarg;       /* List of function arguments */
62789      int nFarg;             /* Number of function arguments */
62790      FuncDef *pDef;         /* The function definition object */
62791      int nId;               /* Length of the function name in bytes */
62792      const char *zId;       /* The function name */
62793      int constMask = 0;     /* Mask of function arguments that are constant */
62794      int i;                 /* Loop counter */
62795      u8 enc = ENC(db);      /* The text encoding used by this database */
62796      CollSeq *pColl = 0;    /* A collating sequence */
62797
62798      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
62799      testcase( op==TK_CONST_FUNC );
62800      testcase( op==TK_FUNCTION );
62801      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
62802        pFarg = 0;
62803      }else{
62804        pFarg = pExpr->x.pList;
62805      }
62806      nFarg = pFarg ? pFarg->nExpr : 0;
62807      assert( !ExprHasProperty(pExpr, EP_IntValue) );
62808      zId = pExpr->u.zToken;
62809      nId = sqlite3Strlen30(zId);
62810      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
62811      if( pDef==0 ){
62812        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
62813        break;
62814      }
62815
62816      /* Attempt a direct implementation of the built-in COALESCE() and
62817      ** IFNULL() functions.  This avoids unnecessary evalation of
62818      ** arguments past the first non-NULL argument.
62819      */
62820      if( pDef->flags & SQLITE_FUNC_COALESCE ){
62821        int endCoalesce = sqlite3VdbeMakeLabel(v);
62822        assert( nFarg>=2 );
62823        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
62824        for(i=1; i<nFarg; i++){
62825          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
62826          sqlite3ExprCacheRemove(pParse, target, 1);
62827          sqlite3ExprCachePush(pParse);
62828          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
62829          sqlite3ExprCachePop(pParse, 1);
62830        }
62831        sqlite3VdbeResolveLabel(v, endCoalesce);
62832        break;
62833      }
62834
62835
62836      if( pFarg ){
62837        r1 = sqlite3GetTempRange(pParse, nFarg);
62838        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
62839        sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
62840        sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
62841      }else{
62842        r1 = 0;
62843      }
62844#ifndef SQLITE_OMIT_VIRTUALTABLE
62845      /* Possibly overload the function if the first argument is
62846      ** a virtual table column.
62847      **
62848      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
62849      ** second argument, not the first, as the argument to test to
62850      ** see if it is a column in a virtual table.  This is done because
62851      ** the left operand of infix functions (the operand we want to
62852      ** control overloading) ends up as the second argument to the
62853      ** function.  The expression "A glob B" is equivalent to
62854      ** "glob(B,A).  We want to use the A in "A glob B" to test
62855      ** for function overloading.  But we use the B term in "glob(B,A)".
62856      */
62857      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
62858        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
62859      }else if( nFarg>0 ){
62860        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
62861      }
62862#endif
62863      for(i=0; i<nFarg; i++){
62864        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
62865          constMask |= (1<<i);
62866        }
62867        if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
62868          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
62869        }
62870      }
62871      if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
62872        if( !pColl ) pColl = db->pDfltColl;
62873        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
62874      }
62875      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
62876                        (char*)pDef, P4_FUNCDEF);
62877      sqlite3VdbeChangeP5(v, (u8)nFarg);
62878      if( nFarg ){
62879        sqlite3ReleaseTempRange(pParse, r1, nFarg);
62880      }
62881      break;
62882    }
62883#ifndef SQLITE_OMIT_SUBQUERY
62884    case TK_EXISTS:
62885    case TK_SELECT: {
62886      testcase( op==TK_EXISTS );
62887      testcase( op==TK_SELECT );
62888      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
62889      break;
62890    }
62891    case TK_IN: {
62892      int destIfFalse = sqlite3VdbeMakeLabel(v);
62893      int destIfNull = sqlite3VdbeMakeLabel(v);
62894      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
62895      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
62896      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
62897      sqlite3VdbeResolveLabel(v, destIfFalse);
62898      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
62899      sqlite3VdbeResolveLabel(v, destIfNull);
62900      break;
62901    }
62902#endif /* SQLITE_OMIT_SUBQUERY */
62903
62904
62905    /*
62906    **    x BETWEEN y AND z
62907    **
62908    ** This is equivalent to
62909    **
62910    **    x>=y AND x<=z
62911    **
62912    ** X is stored in pExpr->pLeft.
62913    ** Y is stored in pExpr->pList->a[0].pExpr.
62914    ** Z is stored in pExpr->pList->a[1].pExpr.
62915    */
62916    case TK_BETWEEN: {
62917      Expr *pLeft = pExpr->pLeft;
62918      struct ExprList_item *pLItem = pExpr->x.pList->a;
62919      Expr *pRight = pLItem->pExpr;
62920
62921      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
62922      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
62923      testcase( regFree1==0 );
62924      testcase( regFree2==0 );
62925      r3 = sqlite3GetTempReg(pParse);
62926      r4 = sqlite3GetTempReg(pParse);
62927      codeCompare(pParse, pLeft, pRight, OP_Ge,
62928                  r1, r2, r3, SQLITE_STOREP2);
62929      pLItem++;
62930      pRight = pLItem->pExpr;
62931      sqlite3ReleaseTempReg(pParse, regFree2);
62932      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
62933      testcase( regFree2==0 );
62934      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
62935      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
62936      sqlite3ReleaseTempReg(pParse, r3);
62937      sqlite3ReleaseTempReg(pParse, r4);
62938      break;
62939    }
62940    case TK_UPLUS: {
62941      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
62942      break;
62943    }
62944
62945    case TK_TRIGGER: {
62946      /* If the opcode is TK_TRIGGER, then the expression is a reference
62947      ** to a column in the new.* or old.* pseudo-tables available to
62948      ** trigger programs. In this case Expr.iTable is set to 1 for the
62949      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
62950      ** is set to the column of the pseudo-table to read, or to -1 to
62951      ** read the rowid field.
62952      **
62953      ** The expression is implemented using an OP_Param opcode. The p1
62954      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
62955      ** to reference another column of the old.* pseudo-table, where
62956      ** i is the index of the column. For a new.rowid reference, p1 is
62957      ** set to (n+1), where n is the number of columns in each pseudo-table.
62958      ** For a reference to any other column in the new.* pseudo-table, p1
62959      ** is set to (n+2+i), where n and i are as defined previously. For
62960      ** example, if the table on which triggers are being fired is
62961      ** declared as:
62962      **
62963      **   CREATE TABLE t1(a, b);
62964      **
62965      ** Then p1 is interpreted as follows:
62966      **
62967      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
62968      **   p1==1   ->    old.a         p1==4   ->    new.a
62969      **   p1==2   ->    old.b         p1==5   ->    new.b
62970      */
62971      Table *pTab = pExpr->pTab;
62972      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
62973
62974      assert( pExpr->iTable==0 || pExpr->iTable==1 );
62975      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
62976      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
62977      assert( p1>=0 && p1<(pTab->nCol*2+2) );
62978
62979      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
62980      VdbeComment((v, "%s.%s -> $%d",
62981        (pExpr->iTable ? "new" : "old"),
62982        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
62983        target
62984      ));
62985
62986      /* If the column has REAL affinity, it may currently be stored as an
62987      ** integer. Use OP_RealAffinity to make sure it is really real.  */
62988      if( pExpr->iColumn>=0
62989       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
62990      ){
62991        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
62992      }
62993      break;
62994    }
62995
62996
62997    /*
62998    ** Form A:
62999    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
63000    **
63001    ** Form B:
63002    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
63003    **
63004    ** Form A is can be transformed into the equivalent form B as follows:
63005    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
63006    **        WHEN x=eN THEN rN ELSE y END
63007    **
63008    ** X (if it exists) is in pExpr->pLeft.
63009    ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
63010    ** ELSE clause and no other term matches, then the result of the
63011    ** exprssion is NULL.
63012    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
63013    **
63014    ** The result of the expression is the Ri for the first matching Ei,
63015    ** or if there is no matching Ei, the ELSE term Y, or if there is
63016    ** no ELSE term, NULL.
63017    */
63018    default: assert( op==TK_CASE ); {
63019      int endLabel;                     /* GOTO label for end of CASE stmt */
63020      int nextCase;                     /* GOTO label for next WHEN clause */
63021      int nExpr;                        /* 2x number of WHEN terms */
63022      int i;                            /* Loop counter */
63023      ExprList *pEList;                 /* List of WHEN terms */
63024      struct ExprList_item *aListelem;  /* Array of WHEN terms */
63025      Expr opCompare;                   /* The X==Ei expression */
63026      Expr cacheX;                      /* Cached expression X */
63027      Expr *pX;                         /* The X expression */
63028      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
63029      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
63030
63031      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
63032      assert((pExpr->x.pList->nExpr % 2) == 0);
63033      assert(pExpr->x.pList->nExpr > 0);
63034      pEList = pExpr->x.pList;
63035      aListelem = pEList->a;
63036      nExpr = pEList->nExpr;
63037      endLabel = sqlite3VdbeMakeLabel(v);
63038      if( (pX = pExpr->pLeft)!=0 ){
63039        cacheX = *pX;
63040        testcase( pX->op==TK_COLUMN );
63041        testcase( pX->op==TK_REGISTER );
63042        cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
63043        testcase( regFree1==0 );
63044        cacheX.op = TK_REGISTER;
63045        opCompare.op = TK_EQ;
63046        opCompare.pLeft = &cacheX;
63047        pTest = &opCompare;
63048      }
63049      for(i=0; i<nExpr; i=i+2){
63050        sqlite3ExprCachePush(pParse);
63051        if( pX ){
63052          assert( pTest!=0 );
63053          opCompare.pRight = aListelem[i].pExpr;
63054        }else{
63055          pTest = aListelem[i].pExpr;
63056        }
63057        nextCase = sqlite3VdbeMakeLabel(v);
63058        testcase( pTest->op==TK_COLUMN );
63059        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
63060        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
63061        testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
63062        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
63063        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
63064        sqlite3ExprCachePop(pParse, 1);
63065        sqlite3VdbeResolveLabel(v, nextCase);
63066      }
63067      if( pExpr->pRight ){
63068        sqlite3ExprCachePush(pParse);
63069        sqlite3ExprCode(pParse, pExpr->pRight, target);
63070        sqlite3ExprCachePop(pParse, 1);
63071      }else{
63072        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
63073      }
63074      assert( db->mallocFailed || pParse->nErr>0
63075           || pParse->iCacheLevel==iCacheLevel );
63076      sqlite3VdbeResolveLabel(v, endLabel);
63077      break;
63078    }
63079#ifndef SQLITE_OMIT_TRIGGER
63080    case TK_RAISE: {
63081      assert( pExpr->affinity==OE_Rollback
63082           || pExpr->affinity==OE_Abort
63083           || pExpr->affinity==OE_Fail
63084           || pExpr->affinity==OE_Ignore
63085      );
63086      if( !pParse->pTriggerTab ){
63087        sqlite3ErrorMsg(pParse,
63088                       "RAISE() may only be used within a trigger-program");
63089        return 0;
63090      }
63091      if( pExpr->affinity==OE_Abort ){
63092        sqlite3MayAbort(pParse);
63093      }
63094      assert( !ExprHasProperty(pExpr, EP_IntValue) );
63095      if( pExpr->affinity==OE_Ignore ){
63096        sqlite3VdbeAddOp4(
63097            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
63098      }else{
63099        sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
63100      }
63101
63102      break;
63103    }
63104#endif
63105  }
63106  sqlite3ReleaseTempReg(pParse, regFree1);
63107  sqlite3ReleaseTempReg(pParse, regFree2);
63108  return inReg;
63109}
63110
63111/*
63112** Generate code to evaluate an expression and store the results
63113** into a register.  Return the register number where the results
63114** are stored.
63115**
63116** If the register is a temporary register that can be deallocated,
63117** then write its number into *pReg.  If the result register is not
63118** a temporary, then set *pReg to zero.
63119*/
63120SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
63121  int r1 = sqlite3GetTempReg(pParse);
63122  int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
63123  if( r2==r1 ){
63124    *pReg = r1;
63125  }else{
63126    sqlite3ReleaseTempReg(pParse, r1);
63127    *pReg = 0;
63128  }
63129  return r2;
63130}
63131
63132/*
63133** Generate code that will evaluate expression pExpr and store the
63134** results in register target.  The results are guaranteed to appear
63135** in register target.
63136*/
63137SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
63138  int inReg;
63139
63140  assert( target>0 && target<=pParse->nMem );
63141  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
63142  assert( pParse->pVdbe || pParse->db->mallocFailed );
63143  if( inReg!=target && pParse->pVdbe ){
63144    sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
63145  }
63146  return target;
63147}
63148
63149/*
63150** Generate code that evalutes the given expression and puts the result
63151** in register target.
63152**
63153** Also make a copy of the expression results into another "cache" register
63154** and modify the expression so that the next time it is evaluated,
63155** the result is a copy of the cache register.
63156**
63157** This routine is used for expressions that are used multiple
63158** times.  They are evaluated once and the results of the expression
63159** are reused.
63160*/
63161SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
63162  Vdbe *v = pParse->pVdbe;
63163  int inReg;
63164  inReg = sqlite3ExprCode(pParse, pExpr, target);
63165  assert( target>0 );
63166  /* This routine is called for terms to INSERT or UPDATE.  And the only
63167  ** other place where expressions can be converted into TK_REGISTER is
63168  ** in WHERE clause processing.  So as currently implemented, there is
63169  ** no way for a TK_REGISTER to exist here.  But it seems prudent to
63170  ** keep the ALWAYS() in case the conditions above change with future
63171  ** modifications or enhancements. */
63172  if( ALWAYS(pExpr->op!=TK_REGISTER) ){
63173    int iMem;
63174    iMem = ++pParse->nMem;
63175    sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
63176    pExpr->iTable = iMem;
63177    pExpr->op2 = pExpr->op;
63178    pExpr->op = TK_REGISTER;
63179  }
63180  return inReg;
63181}
63182
63183/*
63184** Return TRUE if pExpr is an constant expression that is appropriate
63185** for factoring out of a loop.  Appropriate expressions are:
63186**
63187**    *  Any expression that evaluates to two or more opcodes.
63188**
63189**    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
63190**       or OP_Variable that does not need to be placed in a
63191**       specific register.
63192**
63193** There is no point in factoring out single-instruction constant
63194** expressions that need to be placed in a particular register.
63195** We could factor them out, but then we would end up adding an
63196** OP_SCopy instruction to move the value into the correct register
63197** later.  We might as well just use the original instruction and
63198** avoid the OP_SCopy.
63199*/
63200static int isAppropriateForFactoring(Expr *p){
63201  if( !sqlite3ExprIsConstantNotJoin(p) ){
63202    return 0;  /* Only constant expressions are appropriate for factoring */
63203  }
63204  if( (p->flags & EP_FixedDest)==0 ){
63205    return 1;  /* Any constant without a fixed destination is appropriate */
63206  }
63207  while( p->op==TK_UPLUS ) p = p->pLeft;
63208  switch( p->op ){
63209#ifndef SQLITE_OMIT_BLOB_LITERAL
63210    case TK_BLOB:
63211#endif
63212    case TK_VARIABLE:
63213    case TK_INTEGER:
63214    case TK_FLOAT:
63215    case TK_NULL:
63216    case TK_STRING: {
63217      testcase( p->op==TK_BLOB );
63218      testcase( p->op==TK_VARIABLE );
63219      testcase( p->op==TK_INTEGER );
63220      testcase( p->op==TK_FLOAT );
63221      testcase( p->op==TK_NULL );
63222      testcase( p->op==TK_STRING );
63223      /* Single-instruction constants with a fixed destination are
63224      ** better done in-line.  If we factor them, they will just end
63225      ** up generating an OP_SCopy to move the value to the destination
63226      ** register. */
63227      return 0;
63228    }
63229    case TK_UMINUS: {
63230      if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
63231        return 0;
63232      }
63233      break;
63234    }
63235    default: {
63236      break;
63237    }
63238  }
63239  return 1;
63240}
63241
63242/*
63243** If pExpr is a constant expression that is appropriate for
63244** factoring out of a loop, then evaluate the expression
63245** into a register and convert the expression into a TK_REGISTER
63246** expression.
63247*/
63248static int evalConstExpr(Walker *pWalker, Expr *pExpr){
63249  Parse *pParse = pWalker->pParse;
63250  switch( pExpr->op ){
63251    case TK_IN:
63252    case TK_REGISTER: {
63253      return WRC_Prune;
63254    }
63255    case TK_FUNCTION:
63256    case TK_AGG_FUNCTION:
63257    case TK_CONST_FUNC: {
63258      /* The arguments to a function have a fixed destination.
63259      ** Mark them this way to avoid generated unneeded OP_SCopy
63260      ** instructions.
63261      */
63262      ExprList *pList = pExpr->x.pList;
63263      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63264      if( pList ){
63265        int i = pList->nExpr;
63266        struct ExprList_item *pItem = pList->a;
63267        for(; i>0; i--, pItem++){
63268          if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
63269        }
63270      }
63271      break;
63272    }
63273  }
63274  if( isAppropriateForFactoring(pExpr) ){
63275    int r1 = ++pParse->nMem;
63276    int r2;
63277    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
63278    if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
63279    pExpr->op2 = pExpr->op;
63280    pExpr->op = TK_REGISTER;
63281    pExpr->iTable = r2;
63282    return WRC_Prune;
63283  }
63284  return WRC_Continue;
63285}
63286
63287/*
63288** Preevaluate constant subexpressions within pExpr and store the
63289** results in registers.  Modify pExpr so that the constant subexpresions
63290** are TK_REGISTER opcodes that refer to the precomputed values.
63291*/
63292SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
63293  Walker w;
63294  w.xExprCallback = evalConstExpr;
63295  w.xSelectCallback = 0;
63296  w.pParse = pParse;
63297  sqlite3WalkExpr(&w, pExpr);
63298}
63299
63300
63301/*
63302** Generate code that pushes the value of every element of the given
63303** expression list into a sequence of registers beginning at target.
63304**
63305** Return the number of elements evaluated.
63306*/
63307SQLITE_PRIVATE int sqlite3ExprCodeExprList(
63308  Parse *pParse,     /* Parsing context */
63309  ExprList *pList,   /* The expression list to be coded */
63310  int target,        /* Where to write results */
63311  int doHardCopy     /* Make a hard copy of every element */
63312){
63313  struct ExprList_item *pItem;
63314  int i, n;
63315  assert( pList!=0 );
63316  assert( target>0 );
63317  n = pList->nExpr;
63318  for(pItem=pList->a, i=0; i<n; i++, pItem++){
63319    if( pItem->iAlias ){
63320      int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
63321      Vdbe *v = sqlite3GetVdbe(pParse);
63322      if( iReg!=target+i ){
63323        sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
63324      }
63325    }else{
63326      sqlite3ExprCode(pParse, pItem->pExpr, target+i);
63327    }
63328    if( doHardCopy && !pParse->db->mallocFailed ){
63329      sqlite3ExprHardCopy(pParse, target, n);
63330    }
63331  }
63332  return n;
63333}
63334
63335/*
63336** Generate code for a BETWEEN operator.
63337**
63338**    x BETWEEN y AND z
63339**
63340** The above is equivalent to
63341**
63342**    x>=y AND x<=z
63343**
63344** Code it as such, taking care to do the common subexpression
63345** elementation of x.
63346*/
63347static void exprCodeBetween(
63348  Parse *pParse,    /* Parsing and code generating context */
63349  Expr *pExpr,      /* The BETWEEN expression */
63350  int dest,         /* Jump here if the jump is taken */
63351  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
63352  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
63353){
63354  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
63355  Expr compLeft;    /* The  x>=y  term */
63356  Expr compRight;   /* The  x<=z  term */
63357  Expr exprX;       /* The  x  subexpression */
63358  int regFree1 = 0; /* Temporary use register */
63359
63360  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63361  exprX = *pExpr->pLeft;
63362  exprAnd.op = TK_AND;
63363  exprAnd.pLeft = &compLeft;
63364  exprAnd.pRight = &compRight;
63365  compLeft.op = TK_GE;
63366  compLeft.pLeft = &exprX;
63367  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
63368  compRight.op = TK_LE;
63369  compRight.pLeft = &exprX;
63370  compRight.pRight = pExpr->x.pList->a[1].pExpr;
63371  exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
63372  exprX.op = TK_REGISTER;
63373  if( jumpIfTrue ){
63374    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
63375  }else{
63376    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
63377  }
63378  sqlite3ReleaseTempReg(pParse, regFree1);
63379
63380  /* Ensure adequate test coverage */
63381  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
63382  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
63383  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
63384  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
63385  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
63386  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
63387  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
63388  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
63389}
63390
63391/*
63392** Generate code for a boolean expression such that a jump is made
63393** to the label "dest" if the expression is true but execution
63394** continues straight thru if the expression is false.
63395**
63396** If the expression evaluates to NULL (neither true nor false), then
63397** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
63398**
63399** This code depends on the fact that certain token values (ex: TK_EQ)
63400** are the same as opcode values (ex: OP_Eq) that implement the corresponding
63401** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
63402** the make process cause these values to align.  Assert()s in the code
63403** below verify that the numbers are aligned correctly.
63404*/
63405SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
63406  Vdbe *v = pParse->pVdbe;
63407  int op = 0;
63408  int regFree1 = 0;
63409  int regFree2 = 0;
63410  int r1, r2;
63411
63412  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
63413  if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
63414  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
63415  op = pExpr->op;
63416  switch( op ){
63417    case TK_AND: {
63418      int d2 = sqlite3VdbeMakeLabel(v);
63419      testcase( jumpIfNull==0 );
63420      sqlite3ExprCachePush(pParse);
63421      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
63422      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
63423      sqlite3VdbeResolveLabel(v, d2);
63424      sqlite3ExprCachePop(pParse, 1);
63425      break;
63426    }
63427    case TK_OR: {
63428      testcase( jumpIfNull==0 );
63429      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
63430      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
63431      break;
63432    }
63433    case TK_NOT: {
63434      testcase( jumpIfNull==0 );
63435      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
63436      break;
63437    }
63438    case TK_LT:
63439    case TK_LE:
63440    case TK_GT:
63441    case TK_GE:
63442    case TK_NE:
63443    case TK_EQ: {
63444      assert( TK_LT==OP_Lt );
63445      assert( TK_LE==OP_Le );
63446      assert( TK_GT==OP_Gt );
63447      assert( TK_GE==OP_Ge );
63448      assert( TK_EQ==OP_Eq );
63449      assert( TK_NE==OP_Ne );
63450      testcase( op==TK_LT );
63451      testcase( op==TK_LE );
63452      testcase( op==TK_GT );
63453      testcase( op==TK_GE );
63454      testcase( op==TK_EQ );
63455      testcase( op==TK_NE );
63456      testcase( jumpIfNull==0 );
63457      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63458      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63459      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63460                  r1, r2, dest, jumpIfNull);
63461      testcase( regFree1==0 );
63462      testcase( regFree2==0 );
63463      break;
63464    }
63465    case TK_IS:
63466    case TK_ISNOT: {
63467      testcase( op==TK_IS );
63468      testcase( op==TK_ISNOT );
63469      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63470      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63471      op = (op==TK_IS) ? TK_EQ : TK_NE;
63472      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63473                  r1, r2, dest, SQLITE_NULLEQ);
63474      testcase( regFree1==0 );
63475      testcase( regFree2==0 );
63476      break;
63477    }
63478    case TK_ISNULL:
63479    case TK_NOTNULL: {
63480      assert( TK_ISNULL==OP_IsNull );
63481      assert( TK_NOTNULL==OP_NotNull );
63482      testcase( op==TK_ISNULL );
63483      testcase( op==TK_NOTNULL );
63484      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63485      sqlite3VdbeAddOp2(v, op, r1, dest);
63486      testcase( regFree1==0 );
63487      break;
63488    }
63489    case TK_BETWEEN: {
63490      testcase( jumpIfNull==0 );
63491      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
63492      break;
63493    }
63494    case TK_IN: {
63495      int destIfFalse = sqlite3VdbeMakeLabel(v);
63496      int destIfNull = jumpIfNull ? dest : destIfFalse;
63497      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
63498      sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
63499      sqlite3VdbeResolveLabel(v, destIfFalse);
63500      break;
63501    }
63502    default: {
63503      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
63504      sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
63505      testcase( regFree1==0 );
63506      testcase( jumpIfNull==0 );
63507      break;
63508    }
63509  }
63510  sqlite3ReleaseTempReg(pParse, regFree1);
63511  sqlite3ReleaseTempReg(pParse, regFree2);
63512}
63513
63514/*
63515** Generate code for a boolean expression such that a jump is made
63516** to the label "dest" if the expression is false but execution
63517** continues straight thru if the expression is true.
63518**
63519** If the expression evaluates to NULL (neither true nor false) then
63520** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
63521** is 0.
63522*/
63523SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
63524  Vdbe *v = pParse->pVdbe;
63525  int op = 0;
63526  int regFree1 = 0;
63527  int regFree2 = 0;
63528  int r1, r2;
63529
63530  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
63531  if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
63532  if( pExpr==0 )    return;
63533
63534  /* The value of pExpr->op and op are related as follows:
63535  **
63536  **       pExpr->op            op
63537  **       ---------          ----------
63538  **       TK_ISNULL          OP_NotNull
63539  **       TK_NOTNULL         OP_IsNull
63540  **       TK_NE              OP_Eq
63541  **       TK_EQ              OP_Ne
63542  **       TK_GT              OP_Le
63543  **       TK_LE              OP_Gt
63544  **       TK_GE              OP_Lt
63545  **       TK_LT              OP_Ge
63546  **
63547  ** For other values of pExpr->op, op is undefined and unused.
63548  ** The value of TK_ and OP_ constants are arranged such that we
63549  ** can compute the mapping above using the following expression.
63550  ** Assert()s verify that the computation is correct.
63551  */
63552  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
63553
63554  /* Verify correct alignment of TK_ and OP_ constants
63555  */
63556  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
63557  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
63558  assert( pExpr->op!=TK_NE || op==OP_Eq );
63559  assert( pExpr->op!=TK_EQ || op==OP_Ne );
63560  assert( pExpr->op!=TK_LT || op==OP_Ge );
63561  assert( pExpr->op!=TK_LE || op==OP_Gt );
63562  assert( pExpr->op!=TK_GT || op==OP_Le );
63563  assert( pExpr->op!=TK_GE || op==OP_Lt );
63564
63565  switch( pExpr->op ){
63566    case TK_AND: {
63567      testcase( jumpIfNull==0 );
63568      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
63569      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
63570      break;
63571    }
63572    case TK_OR: {
63573      int d2 = sqlite3VdbeMakeLabel(v);
63574      testcase( jumpIfNull==0 );
63575      sqlite3ExprCachePush(pParse);
63576      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
63577      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
63578      sqlite3VdbeResolveLabel(v, d2);
63579      sqlite3ExprCachePop(pParse, 1);
63580      break;
63581    }
63582    case TK_NOT: {
63583      testcase( jumpIfNull==0 );
63584      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
63585      break;
63586    }
63587    case TK_LT:
63588    case TK_LE:
63589    case TK_GT:
63590    case TK_GE:
63591    case TK_NE:
63592    case TK_EQ: {
63593      testcase( op==TK_LT );
63594      testcase( op==TK_LE );
63595      testcase( op==TK_GT );
63596      testcase( op==TK_GE );
63597      testcase( op==TK_EQ );
63598      testcase( op==TK_NE );
63599      testcase( jumpIfNull==0 );
63600      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63601      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63602      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63603                  r1, r2, dest, jumpIfNull);
63604      testcase( regFree1==0 );
63605      testcase( regFree2==0 );
63606      break;
63607    }
63608    case TK_IS:
63609    case TK_ISNOT: {
63610      testcase( pExpr->op==TK_IS );
63611      testcase( pExpr->op==TK_ISNOT );
63612      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63613      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63614      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
63615      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63616                  r1, r2, dest, SQLITE_NULLEQ);
63617      testcase( regFree1==0 );
63618      testcase( regFree2==0 );
63619      break;
63620    }
63621    case TK_ISNULL:
63622    case TK_NOTNULL: {
63623      testcase( op==TK_ISNULL );
63624      testcase( op==TK_NOTNULL );
63625      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63626      sqlite3VdbeAddOp2(v, op, r1, dest);
63627      testcase( regFree1==0 );
63628      break;
63629    }
63630    case TK_BETWEEN: {
63631      testcase( jumpIfNull==0 );
63632      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
63633      break;
63634    }
63635    case TK_IN: {
63636      if( jumpIfNull ){
63637        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
63638      }else{
63639        int destIfNull = sqlite3VdbeMakeLabel(v);
63640        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
63641        sqlite3VdbeResolveLabel(v, destIfNull);
63642      }
63643      break;
63644    }
63645    default: {
63646      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
63647      sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
63648      testcase( regFree1==0 );
63649      testcase( jumpIfNull==0 );
63650      break;
63651    }
63652  }
63653  sqlite3ReleaseTempReg(pParse, regFree1);
63654  sqlite3ReleaseTempReg(pParse, regFree2);
63655}
63656
63657/*
63658** Do a deep comparison of two expression trees.  Return TRUE (non-zero)
63659** if they are identical and return FALSE if they differ in any way.
63660**
63661** Sometimes this routine will return FALSE even if the two expressions
63662** really are equivalent.  If we cannot prove that the expressions are
63663** identical, we return FALSE just to be safe.  So if this routine
63664** returns false, then you do not really know for certain if the two
63665** expressions are the same.  But if you get a TRUE return, then you
63666** can be sure the expressions are the same.  In the places where
63667** this routine is used, it does not hurt to get an extra FALSE - that
63668** just might result in some slightly slower code.  But returning
63669** an incorrect TRUE could lead to a malfunction.
63670*/
63671SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
63672  int i;
63673  if( pA==0||pB==0 ){
63674    return pB==pA;
63675  }
63676  assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
63677  assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
63678  if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
63679    return 0;
63680  }
63681  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
63682  if( pA->op!=pB->op ) return 0;
63683  if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
63684  if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
63685
63686  if( pA->x.pList && pB->x.pList ){
63687    if( pA->x.pList->nExpr!=pB->x.pList->nExpr ) return 0;
63688    for(i=0; i<pA->x.pList->nExpr; i++){
63689      Expr *pExprA = pA->x.pList->a[i].pExpr;
63690      Expr *pExprB = pB->x.pList->a[i].pExpr;
63691      if( !sqlite3ExprCompare(pExprA, pExprB) ) return 0;
63692    }
63693  }else if( pA->x.pList || pB->x.pList ){
63694    return 0;
63695  }
63696
63697  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
63698  if( ExprHasProperty(pA, EP_IntValue) ){
63699    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
63700      return 0;
63701    }
63702  }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
63703    if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 0;
63704    if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
63705      return 0;
63706    }
63707  }
63708  return 1;
63709}
63710
63711
63712/*
63713** Add a new element to the pAggInfo->aCol[] array.  Return the index of
63714** the new element.  Return a negative number if malloc fails.
63715*/
63716static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
63717  int i;
63718  pInfo->aCol = sqlite3ArrayAllocate(
63719       db,
63720       pInfo->aCol,
63721       sizeof(pInfo->aCol[0]),
63722       3,
63723       &pInfo->nColumn,
63724       &pInfo->nColumnAlloc,
63725       &i
63726  );
63727  return i;
63728}
63729
63730/*
63731** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
63732** the new element.  Return a negative number if malloc fails.
63733*/
63734static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
63735  int i;
63736  pInfo->aFunc = sqlite3ArrayAllocate(
63737       db,
63738       pInfo->aFunc,
63739       sizeof(pInfo->aFunc[0]),
63740       3,
63741       &pInfo->nFunc,
63742       &pInfo->nFuncAlloc,
63743       &i
63744  );
63745  return i;
63746}
63747
63748/*
63749** This is the xExprCallback for a tree walker.  It is used to
63750** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
63751** for additional information.
63752*/
63753static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
63754  int i;
63755  NameContext *pNC = pWalker->u.pNC;
63756  Parse *pParse = pNC->pParse;
63757  SrcList *pSrcList = pNC->pSrcList;
63758  AggInfo *pAggInfo = pNC->pAggInfo;
63759
63760  switch( pExpr->op ){
63761    case TK_AGG_COLUMN:
63762    case TK_COLUMN: {
63763      testcase( pExpr->op==TK_AGG_COLUMN );
63764      testcase( pExpr->op==TK_COLUMN );
63765      /* Check to see if the column is in one of the tables in the FROM
63766      ** clause of the aggregate query */
63767      if( ALWAYS(pSrcList!=0) ){
63768        struct SrcList_item *pItem = pSrcList->a;
63769        for(i=0; i<pSrcList->nSrc; i++, pItem++){
63770          struct AggInfo_col *pCol;
63771          assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
63772          if( pExpr->iTable==pItem->iCursor ){
63773            /* If we reach this point, it means that pExpr refers to a table
63774            ** that is in the FROM clause of the aggregate query.
63775            **
63776            ** Make an entry for the column in pAggInfo->aCol[] if there
63777            ** is not an entry there already.
63778            */
63779            int k;
63780            pCol = pAggInfo->aCol;
63781            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
63782              if( pCol->iTable==pExpr->iTable &&
63783                  pCol->iColumn==pExpr->iColumn ){
63784                break;
63785              }
63786            }
63787            if( (k>=pAggInfo->nColumn)
63788             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
63789            ){
63790              pCol = &pAggInfo->aCol[k];
63791              pCol->pTab = pExpr->pTab;
63792              pCol->iTable = pExpr->iTable;
63793              pCol->iColumn = pExpr->iColumn;
63794              pCol->iMem = ++pParse->nMem;
63795              pCol->iSorterColumn = -1;
63796              pCol->pExpr = pExpr;
63797              if( pAggInfo->pGroupBy ){
63798                int j, n;
63799                ExprList *pGB = pAggInfo->pGroupBy;
63800                struct ExprList_item *pTerm = pGB->a;
63801                n = pGB->nExpr;
63802                for(j=0; j<n; j++, pTerm++){
63803                  Expr *pE = pTerm->pExpr;
63804                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
63805                      pE->iColumn==pExpr->iColumn ){
63806                    pCol->iSorterColumn = j;
63807                    break;
63808                  }
63809                }
63810              }
63811              if( pCol->iSorterColumn<0 ){
63812                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
63813              }
63814            }
63815            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
63816            ** because it was there before or because we just created it).
63817            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
63818            ** pAggInfo->aCol[] entry.
63819            */
63820            ExprSetIrreducible(pExpr);
63821            pExpr->pAggInfo = pAggInfo;
63822            pExpr->op = TK_AGG_COLUMN;
63823            pExpr->iAgg = (i16)k;
63824            break;
63825          } /* endif pExpr->iTable==pItem->iCursor */
63826        } /* end loop over pSrcList */
63827      }
63828      return WRC_Prune;
63829    }
63830    case TK_AGG_FUNCTION: {
63831      /* The pNC->nDepth==0 test causes aggregate functions in subqueries
63832      ** to be ignored */
63833      if( pNC->nDepth==0 ){
63834        /* Check to see if pExpr is a duplicate of another aggregate
63835        ** function that is already in the pAggInfo structure
63836        */
63837        struct AggInfo_func *pItem = pAggInfo->aFunc;
63838        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
63839          if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
63840            break;
63841          }
63842        }
63843        if( i>=pAggInfo->nFunc ){
63844          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
63845          */
63846          u8 enc = ENC(pParse->db);
63847          i = addAggInfoFunc(pParse->db, pAggInfo);
63848          if( i>=0 ){
63849            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63850            pItem = &pAggInfo->aFunc[i];
63851            pItem->pExpr = pExpr;
63852            pItem->iMem = ++pParse->nMem;
63853            assert( !ExprHasProperty(pExpr, EP_IntValue) );
63854            pItem->pFunc = sqlite3FindFunction(pParse->db,
63855                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
63856                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
63857            if( pExpr->flags & EP_Distinct ){
63858              pItem->iDistinct = pParse->nTab++;
63859            }else{
63860              pItem->iDistinct = -1;
63861            }
63862          }
63863        }
63864        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
63865        */
63866        assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
63867        ExprSetIrreducible(pExpr);
63868        pExpr->iAgg = (i16)i;
63869        pExpr->pAggInfo = pAggInfo;
63870        return WRC_Prune;
63871      }
63872    }
63873  }
63874  return WRC_Continue;
63875}
63876static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
63877  NameContext *pNC = pWalker->u.pNC;
63878  if( pNC->nDepth==0 ){
63879    pNC->nDepth++;
63880    sqlite3WalkSelect(pWalker, pSelect);
63881    pNC->nDepth--;
63882    return WRC_Prune;
63883  }else{
63884    return WRC_Continue;
63885  }
63886}
63887
63888/*
63889** Analyze the given expression looking for aggregate functions and
63890** for variables that need to be added to the pParse->aAgg[] array.
63891** Make additional entries to the pParse->aAgg[] array as necessary.
63892**
63893** This routine should only be called after the expression has been
63894** analyzed by sqlite3ResolveExprNames().
63895*/
63896SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
63897  Walker w;
63898  w.xExprCallback = analyzeAggregate;
63899  w.xSelectCallback = analyzeAggregatesInSelect;
63900  w.u.pNC = pNC;
63901  assert( pNC->pSrcList!=0 );
63902  sqlite3WalkExpr(&w, pExpr);
63903}
63904
63905/*
63906** Call sqlite3ExprAnalyzeAggregates() for every expression in an
63907** expression list.  Return the number of errors.
63908**
63909** If an error is found, the analysis is cut short.
63910*/
63911SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
63912  struct ExprList_item *pItem;
63913  int i;
63914  if( pList ){
63915    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
63916      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
63917    }
63918  }
63919}
63920
63921/*
63922** Allocate a single new register for use to hold some intermediate result.
63923*/
63924SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
63925  if( pParse->nTempReg==0 ){
63926    return ++pParse->nMem;
63927  }
63928  return pParse->aTempReg[--pParse->nTempReg];
63929}
63930
63931/*
63932** Deallocate a register, making available for reuse for some other
63933** purpose.
63934**
63935** If a register is currently being used by the column cache, then
63936** the dallocation is deferred until the column cache line that uses
63937** the register becomes stale.
63938*/
63939SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
63940  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
63941    int i;
63942    struct yColCache *p;
63943    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
63944      if( p->iReg==iReg ){
63945        p->tempReg = 1;
63946        return;
63947      }
63948    }
63949    pParse->aTempReg[pParse->nTempReg++] = iReg;
63950  }
63951}
63952
63953/*
63954** Allocate or deallocate a block of nReg consecutive registers
63955*/
63956SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
63957  int i, n;
63958  i = pParse->iRangeReg;
63959  n = pParse->nRangeReg;
63960  if( nReg<=n ){
63961    assert( !usedAsColumnCache(pParse, i, i+n-1) );
63962    pParse->iRangeReg += nReg;
63963    pParse->nRangeReg -= nReg;
63964  }else{
63965    i = pParse->nMem+1;
63966    pParse->nMem += nReg;
63967  }
63968  return i;
63969}
63970SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
63971  sqlite3ExprCacheRemove(pParse, iReg, nReg);
63972  if( nReg>pParse->nRangeReg ){
63973    pParse->nRangeReg = nReg;
63974    pParse->iRangeReg = iReg;
63975  }
63976}
63977
63978/************** End of expr.c ************************************************/
63979/************** Begin file alter.c *******************************************/
63980/*
63981** 2005 February 15
63982**
63983** The author disclaims copyright to this source code.  In place of
63984** a legal notice, here is a blessing:
63985**
63986**    May you do good and not evil.
63987**    May you find forgiveness for yourself and forgive others.
63988**    May you share freely, never taking more than you give.
63989**
63990*************************************************************************
63991** This file contains C code routines that used to generate VDBE code
63992** that implements the ALTER TABLE command.
63993*/
63994
63995/*
63996** The code in this file only exists if we are not omitting the
63997** ALTER TABLE logic from the build.
63998*/
63999#ifndef SQLITE_OMIT_ALTERTABLE
64000
64001
64002/*
64003** This function is used by SQL generated to implement the
64004** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
64005** CREATE INDEX command. The second is a table name. The table name in
64006** the CREATE TABLE or CREATE INDEX statement is replaced with the third
64007** argument and the result returned. Examples:
64008**
64009** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
64010**     -> 'CREATE TABLE def(a, b, c)'
64011**
64012** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
64013**     -> 'CREATE INDEX i ON def(a, b, c)'
64014*/
64015static void renameTableFunc(
64016  sqlite3_context *context,
64017  int NotUsed,
64018  sqlite3_value **argv
64019){
64020  unsigned char const *zSql = sqlite3_value_text(argv[0]);
64021  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
64022
64023  int token;
64024  Token tname;
64025  unsigned char const *zCsr = zSql;
64026  int len = 0;
64027  char *zRet;
64028
64029  sqlite3 *db = sqlite3_context_db_handle(context);
64030
64031  UNUSED_PARAMETER(NotUsed);
64032
64033  /* The principle used to locate the table name in the CREATE TABLE
64034  ** statement is that the table name is the first non-space token that
64035  ** is immediately followed by a TK_LP or TK_USING token.
64036  */
64037  if( zSql ){
64038    do {
64039      if( !*zCsr ){
64040        /* Ran out of input before finding an opening bracket. Return NULL. */
64041        return;
64042      }
64043
64044      /* Store the token that zCsr points to in tname. */
64045      tname.z = (char*)zCsr;
64046      tname.n = len;
64047
64048      /* Advance zCsr to the next token. Store that token type in 'token',
64049      ** and its length in 'len' (to be used next iteration of this loop).
64050      */
64051      do {
64052        zCsr += len;
64053        len = sqlite3GetToken(zCsr, &token);
64054      } while( token==TK_SPACE );
64055      assert( len>0 );
64056    } while( token!=TK_LP && token!=TK_USING );
64057
64058    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
64059       zTableName, tname.z+tname.n);
64060    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
64061  }
64062}
64063
64064/*
64065** This C function implements an SQL user function that is used by SQL code
64066** generated by the ALTER TABLE ... RENAME command to modify the definition
64067** of any foreign key constraints that use the table being renamed as the
64068** parent table. It is passed three arguments:
64069**
64070**   1) The complete text of the CREATE TABLE statement being modified,
64071**   2) The old name of the table being renamed, and
64072**   3) The new name of the table being renamed.
64073**
64074** It returns the new CREATE TABLE statement. For example:
64075**
64076**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
64077**       -> 'CREATE TABLE t1(a REFERENCES t3)'
64078*/
64079#ifndef SQLITE_OMIT_FOREIGN_KEY
64080static void renameParentFunc(
64081  sqlite3_context *context,
64082  int NotUsed,
64083  sqlite3_value **argv
64084){
64085  sqlite3 *db = sqlite3_context_db_handle(context);
64086  char *zOutput = 0;
64087  char *zResult;
64088  unsigned char const *zInput = sqlite3_value_text(argv[0]);
64089  unsigned char const *zOld = sqlite3_value_text(argv[1]);
64090  unsigned char const *zNew = sqlite3_value_text(argv[2]);
64091
64092  unsigned const char *z;         /* Pointer to token */
64093  int n;                          /* Length of token z */
64094  int token;                      /* Type of token */
64095
64096  UNUSED_PARAMETER(NotUsed);
64097  for(z=zInput; *z; z=z+n){
64098    n = sqlite3GetToken(z, &token);
64099    if( token==TK_REFERENCES ){
64100      char *zParent;
64101      do {
64102        z += n;
64103        n = sqlite3GetToken(z, &token);
64104      }while( token==TK_SPACE );
64105
64106      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
64107      if( zParent==0 ) break;
64108      sqlite3Dequote(zParent);
64109      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
64110        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
64111            (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
64112        );
64113        sqlite3DbFree(db, zOutput);
64114        zOutput = zOut;
64115        zInput = &z[n];
64116      }
64117      sqlite3DbFree(db, zParent);
64118    }
64119  }
64120
64121  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
64122  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
64123  sqlite3DbFree(db, zOutput);
64124}
64125#endif
64126
64127#ifndef SQLITE_OMIT_TRIGGER
64128/* This function is used by SQL generated to implement the
64129** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
64130** statement. The second is a table name. The table name in the CREATE
64131** TRIGGER statement is replaced with the third argument and the result
64132** returned. This is analagous to renameTableFunc() above, except for CREATE
64133** TRIGGER, not CREATE INDEX and CREATE TABLE.
64134*/
64135static void renameTriggerFunc(
64136  sqlite3_context *context,
64137  int NotUsed,
64138  sqlite3_value **argv
64139){
64140  unsigned char const *zSql = sqlite3_value_text(argv[0]);
64141  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
64142
64143  int token;
64144  Token tname;
64145  int dist = 3;
64146  unsigned char const *zCsr = zSql;
64147  int len = 0;
64148  char *zRet;
64149  sqlite3 *db = sqlite3_context_db_handle(context);
64150
64151  UNUSED_PARAMETER(NotUsed);
64152
64153  /* The principle used to locate the table name in the CREATE TRIGGER
64154  ** statement is that the table name is the first token that is immediatedly
64155  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
64156  ** of TK_WHEN, TK_BEGIN or TK_FOR.
64157  */
64158  if( zSql ){
64159    do {
64160
64161      if( !*zCsr ){
64162        /* Ran out of input before finding the table name. Return NULL. */
64163        return;
64164      }
64165
64166      /* Store the token that zCsr points to in tname. */
64167      tname.z = (char*)zCsr;
64168      tname.n = len;
64169
64170      /* Advance zCsr to the next token. Store that token type in 'token',
64171      ** and its length in 'len' (to be used next iteration of this loop).
64172      */
64173      do {
64174        zCsr += len;
64175        len = sqlite3GetToken(zCsr, &token);
64176      }while( token==TK_SPACE );
64177      assert( len>0 );
64178
64179      /* Variable 'dist' stores the number of tokens read since the most
64180      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
64181      ** token is read and 'dist' equals 2, the condition stated above
64182      ** to be met.
64183      **
64184      ** Note that ON cannot be a database, table or column name, so
64185      ** there is no need to worry about syntax like
64186      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
64187      */
64188      dist++;
64189      if( token==TK_DOT || token==TK_ON ){
64190        dist = 0;
64191      }
64192    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
64193
64194    /* Variable tname now contains the token that is the old table-name
64195    ** in the CREATE TRIGGER statement.
64196    */
64197    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
64198       zTableName, tname.z+tname.n);
64199    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
64200  }
64201}
64202#endif   /* !SQLITE_OMIT_TRIGGER */
64203
64204/*
64205** Register built-in functions used to help implement ALTER TABLE
64206*/
64207SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
64208  sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
64209                         renameTableFunc, 0, 0);
64210#ifndef SQLITE_OMIT_TRIGGER
64211  sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
64212                         renameTriggerFunc, 0, 0);
64213#endif
64214#ifndef SQLITE_OMIT_FOREIGN_KEY
64215  sqlite3CreateFunc(db, "sqlite_rename_parent", 3, SQLITE_UTF8, 0,
64216                         renameParentFunc, 0, 0);
64217#endif
64218}
64219
64220/*
64221** This function is used to create the text of expressions of the form:
64222**
64223**   name=<constant1> OR name=<constant2> OR ...
64224**
64225** If argument zWhere is NULL, then a pointer string containing the text
64226** "name=<constant>" is returned, where <constant> is the quoted version
64227** of the string passed as argument zConstant. The returned buffer is
64228** allocated using sqlite3DbMalloc(). It is the responsibility of the
64229** caller to ensure that it is eventually freed.
64230**
64231** If argument zWhere is not NULL, then the string returned is
64232** "<where> OR name=<constant>", where <where> is the contents of zWhere.
64233** In this case zWhere is passed to sqlite3DbFree() before returning.
64234**
64235*/
64236static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
64237  char *zNew;
64238  if( !zWhere ){
64239    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
64240  }else{
64241    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
64242    sqlite3DbFree(db, zWhere);
64243  }
64244  return zNew;
64245}
64246
64247#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64248/*
64249** Generate the text of a WHERE expression which can be used to select all
64250** tables that have foreign key constraints that refer to table pTab (i.e.
64251** constraints for which pTab is the parent table) from the sqlite_master
64252** table.
64253*/
64254static char *whereForeignKeys(Parse *pParse, Table *pTab){
64255  FKey *p;
64256  char *zWhere = 0;
64257  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
64258    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
64259  }
64260  return zWhere;
64261}
64262#endif
64263
64264/*
64265** Generate the text of a WHERE expression which can be used to select all
64266** temporary triggers on table pTab from the sqlite_temp_master table. If
64267** table pTab has no temporary triggers, or is itself stored in the
64268** temporary database, NULL is returned.
64269*/
64270static char *whereTempTriggers(Parse *pParse, Table *pTab){
64271  Trigger *pTrig;
64272  char *zWhere = 0;
64273  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
64274
64275  /* If the table is not located in the temp-db (in which case NULL is
64276  ** returned, loop through the tables list of triggers. For each trigger
64277  ** that is not part of the temp-db schema, add a clause to the WHERE
64278  ** expression being built up in zWhere.
64279  */
64280  if( pTab->pSchema!=pTempSchema ){
64281    sqlite3 *db = pParse->db;
64282    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
64283      if( pTrig->pSchema==pTempSchema ){
64284        zWhere = whereOrName(db, zWhere, pTrig->zName);
64285      }
64286    }
64287  }
64288  return zWhere;
64289}
64290
64291/*
64292** Generate code to drop and reload the internal representation of table
64293** pTab from the database, including triggers and temporary triggers.
64294** Argument zName is the name of the table in the database schema at
64295** the time the generated code is executed. This can be different from
64296** pTab->zName if this function is being called to code part of an
64297** "ALTER TABLE RENAME TO" statement.
64298*/
64299static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
64300  Vdbe *v;
64301  char *zWhere;
64302  int iDb;                   /* Index of database containing pTab */
64303#ifndef SQLITE_OMIT_TRIGGER
64304  Trigger *pTrig;
64305#endif
64306
64307  v = sqlite3GetVdbe(pParse);
64308  if( NEVER(v==0) ) return;
64309  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
64310  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
64311  assert( iDb>=0 );
64312
64313#ifndef SQLITE_OMIT_TRIGGER
64314  /* Drop any table triggers from the internal schema. */
64315  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
64316    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
64317    assert( iTrigDb==iDb || iTrigDb==1 );
64318    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
64319  }
64320#endif
64321
64322  /* Drop the table and index from the internal schema.  */
64323  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
64324
64325  /* Reload the table, index and permanent trigger schemas. */
64326  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
64327  if( !zWhere ) return;
64328  sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
64329
64330#ifndef SQLITE_OMIT_TRIGGER
64331  /* Now, if the table is not stored in the temp database, reload any temp
64332  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
64333  */
64334  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
64335    sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
64336  }
64337#endif
64338}
64339
64340/*
64341** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
64342** command.
64343*/
64344SQLITE_PRIVATE void sqlite3AlterRenameTable(
64345  Parse *pParse,            /* Parser context. */
64346  SrcList *pSrc,            /* The table to rename. */
64347  Token *pName              /* The new table name. */
64348){
64349  int iDb;                  /* Database that contains the table */
64350  char *zDb;                /* Name of database iDb */
64351  Table *pTab;              /* Table being renamed */
64352  char *zName = 0;          /* NULL-terminated version of pName */
64353  sqlite3 *db = pParse->db; /* Database connection */
64354  int nTabName;             /* Number of UTF-8 characters in zTabName */
64355  const char *zTabName;     /* Original name of the table */
64356  Vdbe *v;
64357#ifndef SQLITE_OMIT_TRIGGER
64358  char *zWhere = 0;         /* Where clause to locate temp triggers */
64359#endif
64360  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
64361
64362  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
64363  assert( pSrc->nSrc==1 );
64364  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
64365
64366  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
64367  if( !pTab ) goto exit_rename_table;
64368  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
64369  zDb = db->aDb[iDb].zName;
64370
64371  /* Get a NULL terminated version of the new table name. */
64372  zName = sqlite3NameFromToken(db, pName);
64373  if( !zName ) goto exit_rename_table;
64374
64375  /* Check that a table or index named 'zName' does not already exist
64376  ** in database iDb. If so, this is an error.
64377  */
64378  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
64379    sqlite3ErrorMsg(pParse,
64380        "there is already another table or index with this name: %s", zName);
64381    goto exit_rename_table;
64382  }
64383
64384  /* Make sure it is not a system table being altered, or a reserved name
64385  ** that the table is being renamed to.
64386  */
64387  if( sqlite3Strlen30(pTab->zName)>6
64388   && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
64389  ){
64390    sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
64391    goto exit_rename_table;
64392  }
64393  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
64394    goto exit_rename_table;
64395  }
64396
64397#ifndef SQLITE_OMIT_VIEW
64398  if( pTab->pSelect ){
64399    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
64400    goto exit_rename_table;
64401  }
64402#endif
64403
64404#ifndef SQLITE_OMIT_AUTHORIZATION
64405  /* Invoke the authorization callback. */
64406  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
64407    goto exit_rename_table;
64408  }
64409#endif
64410
64411#ifndef SQLITE_OMIT_VIRTUALTABLE
64412  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
64413    goto exit_rename_table;
64414  }
64415  if( IsVirtual(pTab) ){
64416    pVTab = sqlite3GetVTable(db, pTab);
64417    if( pVTab->pVtab->pModule->xRename==0 ){
64418      pVTab = 0;
64419    }
64420  }
64421#endif
64422
64423  /* Begin a transaction and code the VerifyCookie for database iDb.
64424  ** Then modify the schema cookie (since the ALTER TABLE modifies the
64425  ** schema). Open a statement transaction if the table is a virtual
64426  ** table.
64427  */
64428  v = sqlite3GetVdbe(pParse);
64429  if( v==0 ){
64430    goto exit_rename_table;
64431  }
64432  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
64433  sqlite3ChangeCookie(pParse, iDb);
64434
64435  /* If this is a virtual table, invoke the xRename() function if
64436  ** one is defined. The xRename() callback will modify the names
64437  ** of any resources used by the v-table implementation (including other
64438  ** SQLite tables) that are identified by the name of the virtual table.
64439  */
64440#ifndef SQLITE_OMIT_VIRTUALTABLE
64441  if( pVTab ){
64442    int i = ++pParse->nMem;
64443    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
64444    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
64445    sqlite3MayAbort(pParse);
64446  }
64447#endif
64448
64449  /* figure out how many UTF-8 characters are in zName */
64450  zTabName = pTab->zName;
64451  nTabName = sqlite3Utf8CharLen(zTabName, -1);
64452
64453#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64454  if( db->flags&SQLITE_ForeignKeys ){
64455    /* If foreign-key support is enabled, rewrite the CREATE TABLE
64456    ** statements corresponding to all child tables of foreign key constraints
64457    ** for which the renamed table is the parent table.  */
64458    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
64459      sqlite3NestedParse(pParse,
64460          "UPDATE sqlite_master SET "
64461              "sql = sqlite_rename_parent(sql, %Q, %Q) "
64462              "WHERE %s;", zTabName, zName, zWhere);
64463      sqlite3DbFree(db, zWhere);
64464    }
64465  }
64466#endif
64467
64468  /* Modify the sqlite_master table to use the new table name. */
64469  sqlite3NestedParse(pParse,
64470      "UPDATE %Q.%s SET "
64471#ifdef SQLITE_OMIT_TRIGGER
64472          "sql = sqlite_rename_table(sql, %Q), "
64473#else
64474          "sql = CASE "
64475            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
64476            "ELSE sqlite_rename_table(sql, %Q) END, "
64477#endif
64478          "tbl_name = %Q, "
64479          "name = CASE "
64480            "WHEN type='table' THEN %Q "
64481            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
64482             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
64483            "ELSE name END "
64484      "WHERE tbl_name=%Q AND "
64485          "(type='table' OR type='index' OR type='trigger');",
64486      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
64487#ifndef SQLITE_OMIT_TRIGGER
64488      zName,
64489#endif
64490      zName, nTabName, zTabName
64491  );
64492
64493#ifndef SQLITE_OMIT_AUTOINCREMENT
64494  /* If the sqlite_sequence table exists in this database, then update
64495  ** it with the new table name.
64496  */
64497  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
64498    sqlite3NestedParse(pParse,
64499        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
64500        zDb, zName, pTab->zName);
64501  }
64502#endif
64503
64504#ifndef SQLITE_OMIT_TRIGGER
64505  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
64506  ** table. Don't do this if the table being ALTERed is itself located in
64507  ** the temp database.
64508  */
64509  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
64510    sqlite3NestedParse(pParse,
64511        "UPDATE sqlite_temp_master SET "
64512            "sql = sqlite_rename_trigger(sql, %Q), "
64513            "tbl_name = %Q "
64514            "WHERE %s;", zName, zName, zWhere);
64515    sqlite3DbFree(db, zWhere);
64516  }
64517#endif
64518
64519#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
64520  if( db->flags&SQLITE_ForeignKeys ){
64521    FKey *p;
64522    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
64523      Table *pFrom = p->pFrom;
64524      if( pFrom!=pTab ){
64525        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
64526      }
64527    }
64528  }
64529#endif
64530
64531  /* Drop and reload the internal table schema. */
64532  reloadTableSchema(pParse, pTab, zName);
64533
64534exit_rename_table:
64535  sqlite3SrcListDelete(db, pSrc);
64536  sqlite3DbFree(db, zName);
64537}
64538
64539
64540/*
64541** Generate code to make sure the file format number is at least minFormat.
64542** The generated code will increase the file format number if necessary.
64543*/
64544SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
64545  Vdbe *v;
64546  v = sqlite3GetVdbe(pParse);
64547  /* The VDBE should have been allocated before this routine is called.
64548  ** If that allocation failed, we would have quit before reaching this
64549  ** point */
64550  if( ALWAYS(v) ){
64551    int r1 = sqlite3GetTempReg(pParse);
64552    int r2 = sqlite3GetTempReg(pParse);
64553    int j1;
64554    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
64555    sqlite3VdbeUsesBtree(v, iDb);
64556    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
64557    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
64558    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
64559    sqlite3VdbeJumpHere(v, j1);
64560    sqlite3ReleaseTempReg(pParse, r1);
64561    sqlite3ReleaseTempReg(pParse, r2);
64562  }
64563}
64564
64565/*
64566** This function is called after an "ALTER TABLE ... ADD" statement
64567** has been parsed. Argument pColDef contains the text of the new
64568** column definition.
64569**
64570** The Table structure pParse->pNewTable was extended to include
64571** the new column during parsing.
64572*/
64573SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
64574  Table *pNew;              /* Copy of pParse->pNewTable */
64575  Table *pTab;              /* Table being altered */
64576  int iDb;                  /* Database number */
64577  const char *zDb;          /* Database name */
64578  const char *zTab;         /* Table name */
64579  char *zCol;               /* Null-terminated column definition */
64580  Column *pCol;             /* The new column */
64581  Expr *pDflt;              /* Default value for the new column */
64582  sqlite3 *db;              /* The database connection; */
64583
64584  db = pParse->db;
64585  if( pParse->nErr || db->mallocFailed ) return;
64586  pNew = pParse->pNewTable;
64587  assert( pNew );
64588
64589  assert( sqlite3BtreeHoldsAllMutexes(db) );
64590  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
64591  zDb = db->aDb[iDb].zName;
64592  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
64593  pCol = &pNew->aCol[pNew->nCol-1];
64594  pDflt = pCol->pDflt;
64595  pTab = sqlite3FindTable(db, zTab, zDb);
64596  assert( pTab );
64597
64598#ifndef SQLITE_OMIT_AUTHORIZATION
64599  /* Invoke the authorization callback. */
64600  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
64601    return;
64602  }
64603#endif
64604
64605  /* If the default value for the new column was specified with a
64606  ** literal NULL, then set pDflt to 0. This simplifies checking
64607  ** for an SQL NULL default below.
64608  */
64609  if( pDflt && pDflt->op==TK_NULL ){
64610    pDflt = 0;
64611  }
64612
64613  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
64614  ** If there is a NOT NULL constraint, then the default value for the
64615  ** column must not be NULL.
64616  */
64617  if( pCol->isPrimKey ){
64618    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
64619    return;
64620  }
64621  if( pNew->pIndex ){
64622    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
64623    return;
64624  }
64625  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
64626    sqlite3ErrorMsg(pParse,
64627        "Cannot add a REFERENCES column with non-NULL default value");
64628    return;
64629  }
64630  if( pCol->notNull && !pDflt ){
64631    sqlite3ErrorMsg(pParse,
64632        "Cannot add a NOT NULL column with default value NULL");
64633    return;
64634  }
64635
64636  /* Ensure the default expression is something that sqlite3ValueFromExpr()
64637  ** can handle (i.e. not CURRENT_TIME etc.)
64638  */
64639  if( pDflt ){
64640    sqlite3_value *pVal;
64641    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
64642      db->mallocFailed = 1;
64643      return;
64644    }
64645    if( !pVal ){
64646      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
64647      return;
64648    }
64649    sqlite3ValueFree(pVal);
64650  }
64651
64652  /* Modify the CREATE TABLE statement. */
64653  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
64654  if( zCol ){
64655    char *zEnd = &zCol[pColDef->n-1];
64656    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
64657      *zEnd-- = '\0';
64658    }
64659    sqlite3NestedParse(pParse,
64660        "UPDATE \"%w\".%s SET "
64661          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
64662        "WHERE type = 'table' AND name = %Q",
64663      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
64664      zTab
64665    );
64666    sqlite3DbFree(db, zCol);
64667  }
64668
64669  /* If the default value of the new column is NULL, then set the file
64670  ** format to 2. If the default value of the new column is not NULL,
64671  ** the file format becomes 3.
64672  */
64673  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
64674
64675  /* Reload the schema of the modified table. */
64676  reloadTableSchema(pParse, pTab, pTab->zName);
64677}
64678
64679/*
64680** This function is called by the parser after the table-name in
64681** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
64682** pSrc is the full-name of the table being altered.
64683**
64684** This routine makes a (partial) copy of the Table structure
64685** for the table being altered and sets Parse.pNewTable to point
64686** to it. Routines called by the parser as the column definition
64687** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
64688** the copy. The copy of the Table structure is deleted by tokenize.c
64689** after parsing is finished.
64690**
64691** Routine sqlite3AlterFinishAddColumn() will be called to complete
64692** coding the "ALTER TABLE ... ADD" statement.
64693*/
64694SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
64695  Table *pNew;
64696  Table *pTab;
64697  Vdbe *v;
64698  int iDb;
64699  int i;
64700  int nAlloc;
64701  sqlite3 *db = pParse->db;
64702
64703  /* Look up the table being altered. */
64704  assert( pParse->pNewTable==0 );
64705  assert( sqlite3BtreeHoldsAllMutexes(db) );
64706  if( db->mallocFailed ) goto exit_begin_add_column;
64707  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
64708  if( !pTab ) goto exit_begin_add_column;
64709
64710#ifndef SQLITE_OMIT_VIRTUALTABLE
64711  if( IsVirtual(pTab) ){
64712    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
64713    goto exit_begin_add_column;
64714  }
64715#endif
64716
64717  /* Make sure this is not an attempt to ALTER a view. */
64718  if( pTab->pSelect ){
64719    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
64720    goto exit_begin_add_column;
64721  }
64722
64723  assert( pTab->addColOffset>0 );
64724  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64725
64726  /* Put a copy of the Table struct in Parse.pNewTable for the
64727  ** sqlite3AddColumn() function and friends to modify.  But modify
64728  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
64729  ** prefix, we insure that the name will not collide with an existing
64730  ** table because user table are not allowed to have the "sqlite_"
64731  ** prefix on their name.
64732  */
64733  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
64734  if( !pNew ) goto exit_begin_add_column;
64735  pParse->pNewTable = pNew;
64736  pNew->nRef = 1;
64737  pNew->dbMem = pTab->dbMem;
64738  pNew->nCol = pTab->nCol;
64739  assert( pNew->nCol>0 );
64740  nAlloc = (((pNew->nCol-1)/8)*8)+8;
64741  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
64742  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
64743  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
64744  if( !pNew->aCol || !pNew->zName ){
64745    db->mallocFailed = 1;
64746    goto exit_begin_add_column;
64747  }
64748  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
64749  for(i=0; i<pNew->nCol; i++){
64750    Column *pCol = &pNew->aCol[i];
64751    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
64752    pCol->zColl = 0;
64753    pCol->zType = 0;
64754    pCol->pDflt = 0;
64755    pCol->zDflt = 0;
64756  }
64757  pNew->pSchema = db->aDb[iDb].pSchema;
64758  pNew->addColOffset = pTab->addColOffset;
64759  pNew->nRef = 1;
64760
64761  /* Begin a transaction and increment the schema cookie.  */
64762  sqlite3BeginWriteOperation(pParse, 0, iDb);
64763  v = sqlite3GetVdbe(pParse);
64764  if( !v ) goto exit_begin_add_column;
64765  sqlite3ChangeCookie(pParse, iDb);
64766
64767exit_begin_add_column:
64768  sqlite3SrcListDelete(db, pSrc);
64769  return;
64770}
64771#endif  /* SQLITE_ALTER_TABLE */
64772
64773/************** End of alter.c ***********************************************/
64774/************** Begin file analyze.c *****************************************/
64775/*
64776** 2005 July 8
64777**
64778** The author disclaims copyright to this source code.  In place of
64779** a legal notice, here is a blessing:
64780**
64781**    May you do good and not evil.
64782**    May you find forgiveness for yourself and forgive others.
64783**    May you share freely, never taking more than you give.
64784**
64785*************************************************************************
64786** This file contains code associated with the ANALYZE command.
64787*/
64788#ifndef SQLITE_OMIT_ANALYZE
64789
64790/*
64791** This routine generates code that opens the sqlite_stat1 table for
64792** writing with cursor iStatCur. If the library was built with the
64793** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
64794** opened for writing using cursor (iStatCur+1)
64795**
64796** If the sqlite_stat1 tables does not previously exist, it is created.
64797** Similarly, if the sqlite_stat2 table does not exist and the library
64798** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
64799**
64800** Argument zWhere may be a pointer to a buffer containing a table name,
64801** or it may be a NULL pointer. If it is not NULL, then all entries in
64802** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
64803** with the named table are deleted. If zWhere==0, then code is generated
64804** to delete all stat table entries.
64805*/
64806static void openStatTable(
64807  Parse *pParse,          /* Parsing context */
64808  int iDb,                /* The database we are looking in */
64809  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
64810  const char *zWhere      /* Delete entries associated with this table */
64811){
64812  static struct {
64813    const char *zName;
64814    const char *zCols;
64815  } aTable[] = {
64816    { "sqlite_stat1", "tbl,idx,stat" },
64817#ifdef SQLITE_ENABLE_STAT2
64818    { "sqlite_stat2", "tbl,idx,sampleno,sample" },
64819#endif
64820  };
64821
64822  int aRoot[] = {0, 0};
64823  u8 aCreateTbl[] = {0, 0};
64824
64825  int i;
64826  sqlite3 *db = pParse->db;
64827  Db *pDb;
64828  Vdbe *v = sqlite3GetVdbe(pParse);
64829  if( v==0 ) return;
64830  assert( sqlite3BtreeHoldsAllMutexes(db) );
64831  assert( sqlite3VdbeDb(v)==db );
64832  pDb = &db->aDb[iDb];
64833
64834  for(i=0; i<ArraySize(aTable); i++){
64835    const char *zTab = aTable[i].zName;
64836    Table *pStat;
64837    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
64838      /* The sqlite_stat[12] table does not exist. Create it. Note that a
64839      ** side-effect of the CREATE TABLE statement is to leave the rootpage
64840      ** of the new table in register pParse->regRoot. This is important
64841      ** because the OpenWrite opcode below will be needing it. */
64842      sqlite3NestedParse(pParse,
64843          "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
64844      );
64845      aRoot[i] = pParse->regRoot;
64846      aCreateTbl[i] = 1;
64847    }else{
64848      /* The table already exists. If zWhere is not NULL, delete all entries
64849      ** associated with the table zWhere. If zWhere is NULL, delete the
64850      ** entire contents of the table. */
64851      aRoot[i] = pStat->tnum;
64852      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
64853      if( zWhere ){
64854        sqlite3NestedParse(pParse,
64855           "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
64856        );
64857      }else{
64858        /* The sqlite_stat[12] table already exists.  Delete all rows. */
64859        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
64860      }
64861    }
64862  }
64863
64864  /* Open the sqlite_stat[12] tables for writing. */
64865  for(i=0; i<ArraySize(aTable); i++){
64866    sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
64867    sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
64868    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
64869  }
64870}
64871
64872/*
64873** Generate code to do an analysis of all indices associated with
64874** a single table.
64875*/
64876static void analyzeOneTable(
64877  Parse *pParse,   /* Parser context */
64878  Table *pTab,     /* Table whose indices are to be analyzed */
64879  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
64880  int iMem         /* Available memory locations begin here */
64881){
64882  sqlite3 *db = pParse->db;    /* Database handle */
64883  Index *pIdx;                 /* An index to being analyzed */
64884  int iIdxCur;                 /* Cursor open on index being analyzed */
64885  Vdbe *v;                     /* The virtual machine being built up */
64886  int i;                       /* Loop counter */
64887  int topOfLoop;               /* The top of the loop */
64888  int endOfLoop;               /* The end of the loop */
64889  int addr;                    /* The address of an instruction */
64890  int iDb;                     /* Index of database containing pTab */
64891  int regTabname = iMem++;     /* Register containing table name */
64892  int regIdxname = iMem++;     /* Register containing index name */
64893  int regSampleno = iMem++;    /* Register containing next sample number */
64894  int regCol = iMem++;         /* Content of a column analyzed table */
64895  int regRec = iMem++;         /* Register holding completed record */
64896  int regTemp = iMem++;        /* Temporary use register */
64897  int regRowid = iMem++;       /* Rowid for the inserted record */
64898
64899#ifdef SQLITE_ENABLE_STAT2
64900  int regTemp2 = iMem++;       /* Temporary use register */
64901  int regSamplerecno = iMem++; /* Index of next sample to record */
64902  int regRecno = iMem++;       /* Current sample index */
64903  int regLast = iMem++;        /* Index of last sample to record */
64904  int regFirst = iMem++;       /* Index of first sample to record */
64905#endif
64906
64907  v = sqlite3GetVdbe(pParse);
64908  if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
64909    /* Do no analysis for tables that have no indices */
64910    return;
64911  }
64912  assert( sqlite3BtreeHoldsAllMutexes(db) );
64913  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
64914  assert( iDb>=0 );
64915#ifndef SQLITE_OMIT_AUTHORIZATION
64916  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
64917      db->aDb[iDb].zName ) ){
64918    return;
64919  }
64920#endif
64921
64922  /* Establish a read-lock on the table at the shared-cache level. */
64923  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
64924
64925  iIdxCur = pParse->nTab++;
64926  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
64927    int nCol = pIdx->nColumn;
64928    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
64929
64930    if( iMem+1+(nCol*2)>pParse->nMem ){
64931      pParse->nMem = iMem+1+(nCol*2);
64932    }
64933
64934    /* Open a cursor to the index to be analyzed. */
64935    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
64936    sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
64937        (char *)pKey, P4_KEYINFO_HANDOFF);
64938    VdbeComment((v, "%s", pIdx->zName));
64939
64940    /* Populate the registers containing the table and index names. */
64941    if( pTab->pIndex==pIdx ){
64942      sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
64943    }
64944    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
64945
64946#ifdef SQLITE_ENABLE_STAT2
64947
64948    /* If this iteration of the loop is generating code to analyze the
64949    ** first index in the pTab->pIndex list, then register regLast has
64950    ** not been populated. In this case populate it now.  */
64951    if( pTab->pIndex==pIdx ){
64952      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
64953      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
64954      sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
64955
64956      sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
64957      sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
64958      addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
64959      sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
64960      sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
64961      sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
64962      sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
64963      sqlite3VdbeJumpHere(v, addr);
64964    }
64965
64966    /* Zero the regSampleno and regRecno registers. */
64967    sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
64968    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
64969    sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
64970#endif
64971
64972    /* The block of memory cells initialized here is used as follows.
64973    **
64974    **    iMem:
64975    **        The total number of rows in the table.
64976    **
64977    **    iMem+1 .. iMem+nCol:
64978    **        Number of distinct entries in index considering the
64979    **        left-most N columns only, where N is between 1 and nCol,
64980    **        inclusive.
64981    **
64982    **    iMem+nCol+1 .. Mem+2*nCol:
64983    **        Previous value of indexed columns, from left to right.
64984    **
64985    ** Cells iMem through iMem+nCol are initialized to 0. The others are
64986    ** initialized to contain an SQL NULL.
64987    */
64988    for(i=0; i<=nCol; i++){
64989      sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
64990    }
64991    for(i=0; i<nCol; i++){
64992      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
64993    }
64994
64995    /* Start the analysis loop. This loop runs through all the entries in
64996    ** the index b-tree.  */
64997    endOfLoop = sqlite3VdbeMakeLabel(v);
64998    sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
64999    topOfLoop = sqlite3VdbeCurrentAddr(v);
65000    sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
65001
65002    for(i=0; i<nCol; i++){
65003      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
65004#ifdef SQLITE_ENABLE_STAT2
65005      if( i==0 ){
65006        /* Check if the record that cursor iIdxCur points to contains a
65007        ** value that should be stored in the sqlite_stat2 table. If so,
65008        ** store it.  */
65009        int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
65010        assert( regTabname+1==regIdxname
65011             && regTabname+2==regSampleno
65012             && regTabname+3==regCol
65013        );
65014        sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
65015        sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
65016        sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
65017        sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
65018
65019        /* Calculate new values for regSamplerecno and regSampleno.
65020        **
65021        **   sampleno = sampleno + 1
65022        **   samplerecno = samplerecno+(remaining records)/(remaining samples)
65023        */
65024        sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
65025        sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
65026        sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
65027        sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
65028        sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
65029        sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
65030        sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
65031
65032        sqlite3VdbeJumpHere(v, ne);
65033        sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
65034      }
65035#endif
65036
65037      sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
65038      /**** TODO:  add collating sequence *****/
65039      sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
65040    }
65041    if( db->mallocFailed ){
65042      /* If a malloc failure has occurred, then the result of the expression
65043      ** passed as the second argument to the call to sqlite3VdbeJumpHere()
65044      ** below may be negative. Which causes an assert() to fail (or an
65045      ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
65046      return;
65047    }
65048    sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
65049    for(i=0; i<nCol; i++){
65050      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
65051      sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
65052      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
65053    }
65054
65055    /* End of the analysis loop. */
65056    sqlite3VdbeResolveLabel(v, endOfLoop);
65057    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
65058    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
65059
65060    /* Store the results in sqlite_stat1.
65061    **
65062    ** The result is a single row of the sqlite_stat1 table.  The first
65063    ** two columns are the names of the table and index.  The third column
65064    ** is a string composed of a list of integer statistics about the
65065    ** index.  The first integer in the list is the total number of entries
65066    ** in the index.  There is one additional integer in the list for each
65067    ** column of the table.  This additional integer is a guess of how many
65068    ** rows of the table the index will select.  If D is the count of distinct
65069    ** values and K is the total number of rows, then the integer is computed
65070    ** as:
65071    **
65072    **        I = (K+D-1)/D
65073    **
65074    ** If K==0 then no entry is made into the sqlite_stat1 table.
65075    ** If K>0 then it is always the case the D>0 so division by zero
65076    ** is never possible.
65077    */
65078    addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
65079    sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
65080    for(i=0; i<nCol; i++){
65081      sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
65082      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
65083      sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
65084      sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
65085      sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
65086      sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
65087      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
65088    }
65089    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
65090    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
65091    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
65092    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
65093    sqlite3VdbeJumpHere(v, addr);
65094  }
65095}
65096
65097/*
65098** Generate code that will cause the most recent index analysis to
65099** be laoded into internal hash tables where is can be used.
65100*/
65101static void loadAnalysis(Parse *pParse, int iDb){
65102  Vdbe *v = sqlite3GetVdbe(pParse);
65103  if( v ){
65104    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
65105  }
65106}
65107
65108/*
65109** Generate code that will do an analysis of an entire database
65110*/
65111static void analyzeDatabase(Parse *pParse, int iDb){
65112  sqlite3 *db = pParse->db;
65113  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
65114  HashElem *k;
65115  int iStatCur;
65116  int iMem;
65117
65118  sqlite3BeginWriteOperation(pParse, 0, iDb);
65119  iStatCur = pParse->nTab;
65120  pParse->nTab += 2;
65121  openStatTable(pParse, iDb, iStatCur, 0);
65122  iMem = pParse->nMem+1;
65123  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
65124    Table *pTab = (Table*)sqliteHashData(k);
65125    analyzeOneTable(pParse, pTab, iStatCur, iMem);
65126  }
65127  loadAnalysis(pParse, iDb);
65128}
65129
65130/*
65131** Generate code that will do an analysis of a single table in
65132** a database.
65133*/
65134static void analyzeTable(Parse *pParse, Table *pTab){
65135  int iDb;
65136  int iStatCur;
65137
65138  assert( pTab!=0 );
65139  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
65140  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
65141  sqlite3BeginWriteOperation(pParse, 0, iDb);
65142  iStatCur = pParse->nTab;
65143  pParse->nTab += 2;
65144  openStatTable(pParse, iDb, iStatCur, pTab->zName);
65145  analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
65146  loadAnalysis(pParse, iDb);
65147}
65148
65149/*
65150** Generate code for the ANALYZE command.  The parser calls this routine
65151** when it recognizes an ANALYZE command.
65152**
65153**        ANALYZE                            -- 1
65154**        ANALYZE  <database>                -- 2
65155**        ANALYZE  ?<database>.?<tablename>  -- 3
65156**
65157** Form 1 causes all indices in all attached databases to be analyzed.
65158** Form 2 analyzes all indices the single database named.
65159** Form 3 analyzes all indices associated with the named table.
65160*/
65161SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
65162  sqlite3 *db = pParse->db;
65163  int iDb;
65164  int i;
65165  char *z, *zDb;
65166  Table *pTab;
65167  Token *pTableName;
65168
65169  /* Read the database schema. If an error occurs, leave an error message
65170  ** and code in pParse and return NULL. */
65171  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
65172  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
65173    return;
65174  }
65175
65176  assert( pName2!=0 || pName1==0 );
65177  if( pName1==0 ){
65178    /* Form 1:  Analyze everything */
65179    for(i=0; i<db->nDb; i++){
65180      if( i==1 ) continue;  /* Do not analyze the TEMP database */
65181      analyzeDatabase(pParse, i);
65182    }
65183  }else if( pName2->n==0 ){
65184    /* Form 2:  Analyze the database or table named */
65185    iDb = sqlite3FindDb(db, pName1);
65186    if( iDb>=0 ){
65187      analyzeDatabase(pParse, iDb);
65188    }else{
65189      z = sqlite3NameFromToken(db, pName1);
65190      if( z ){
65191        pTab = sqlite3LocateTable(pParse, 0, z, 0);
65192        sqlite3DbFree(db, z);
65193        if( pTab ){
65194          analyzeTable(pParse, pTab);
65195        }
65196      }
65197    }
65198  }else{
65199    /* Form 3: Analyze the fully qualified table name */
65200    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
65201    if( iDb>=0 ){
65202      zDb = db->aDb[iDb].zName;
65203      z = sqlite3NameFromToken(db, pTableName);
65204      if( z ){
65205        pTab = sqlite3LocateTable(pParse, 0, z, zDb);
65206        sqlite3DbFree(db, z);
65207        if( pTab ){
65208          analyzeTable(pParse, pTab);
65209        }
65210      }
65211    }
65212  }
65213}
65214
65215/*
65216** Used to pass information from the analyzer reader through to the
65217** callback routine.
65218*/
65219typedef struct analysisInfo analysisInfo;
65220struct analysisInfo {
65221  sqlite3 *db;
65222  const char *zDatabase;
65223};
65224
65225/*
65226** This callback is invoked once for each index when reading the
65227** sqlite_stat1 table.
65228**
65229**     argv[0] = name of the index
65230**     argv[1] = results of analysis - on integer for each column
65231*/
65232static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
65233  analysisInfo *pInfo = (analysisInfo*)pData;
65234  Index *pIndex;
65235  int i, c;
65236  unsigned int v;
65237  const char *z;
65238
65239  assert( argc==2 );
65240  UNUSED_PARAMETER2(NotUsed, argc);
65241
65242  if( argv==0 || argv[0]==0 || argv[1]==0 ){
65243    return 0;
65244  }
65245  pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
65246  if( pIndex==0 ){
65247    return 0;
65248  }
65249  z = argv[1];
65250  for(i=0; *z && i<=pIndex->nColumn; i++){
65251    v = 0;
65252    while( (c=z[0])>='0' && c<='9' ){
65253      v = v*10 + c - '0';
65254      z++;
65255    }
65256    pIndex->aiRowEst[i] = v;
65257    if( *z==' ' ) z++;
65258  }
65259  return 0;
65260}
65261
65262/*
65263** If the Index.aSample variable is not NULL, delete the aSample[] array
65264** and its contents.
65265*/
65266SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index *pIdx){
65267#ifdef SQLITE_ENABLE_STAT2
65268  if( pIdx->aSample ){
65269    int j;
65270    sqlite3 *dbMem = pIdx->pTable->dbMem;
65271    for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
65272      IndexSample *p = &pIdx->aSample[j];
65273      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
65274        sqlite3DbFree(pIdx->pTable->dbMem, p->u.z);
65275      }
65276    }
65277    sqlite3DbFree(dbMem, pIdx->aSample);
65278    pIdx->aSample = 0;
65279  }
65280#else
65281  UNUSED_PARAMETER(pIdx);
65282#endif
65283}
65284
65285/*
65286** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
65287** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
65288** arrays. The contents of sqlite_stat2 are used to populate the
65289** Index.aSample[] arrays.
65290**
65291** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
65292** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
65293** during compilation and the sqlite_stat2 table is present, no data is
65294** read from it.
65295**
65296** If SQLITE_ENABLE_STAT2 was defined during compilation and the
65297** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
65298** returned. However, in this case, data is read from the sqlite_stat1
65299** table (if it is present) before returning.
65300**
65301** If an OOM error occurs, this function always sets db->mallocFailed.
65302** This means if the caller does not care about other errors, the return
65303** code may be ignored.
65304*/
65305SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
65306  analysisInfo sInfo;
65307  HashElem *i;
65308  char *zSql;
65309  int rc;
65310
65311  assert( iDb>=0 && iDb<db->nDb );
65312  assert( db->aDb[iDb].pBt!=0 );
65313  assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
65314
65315  /* Clear any prior statistics */
65316  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
65317    Index *pIdx = sqliteHashData(i);
65318    sqlite3DefaultRowEst(pIdx);
65319    sqlite3DeleteIndexSamples(pIdx);
65320  }
65321
65322  /* Check to make sure the sqlite_stat1 table exists */
65323  sInfo.db = db;
65324  sInfo.zDatabase = db->aDb[iDb].zName;
65325  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
65326    return SQLITE_ERROR;
65327  }
65328
65329  /* Load new statistics out of the sqlite_stat1 table */
65330  zSql = sqlite3MPrintf(db,
65331      "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
65332  if( zSql==0 ){
65333    rc = SQLITE_NOMEM;
65334  }else{
65335    (void)sqlite3SafetyOff(db);
65336    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
65337    (void)sqlite3SafetyOn(db);
65338    sqlite3DbFree(db, zSql);
65339  }
65340
65341
65342  /* Load the statistics from the sqlite_stat2 table. */
65343#ifdef SQLITE_ENABLE_STAT2
65344  if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
65345    rc = SQLITE_ERROR;
65346  }
65347  if( rc==SQLITE_OK ){
65348    sqlite3_stmt *pStmt = 0;
65349
65350    zSql = sqlite3MPrintf(db,
65351        "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
65352    if( !zSql ){
65353      rc = SQLITE_NOMEM;
65354    }else{
65355      (void)sqlite3SafetyOff(db);
65356      rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
65357      (void)sqlite3SafetyOn(db);
65358      sqlite3DbFree(db, zSql);
65359    }
65360
65361    if( rc==SQLITE_OK ){
65362      (void)sqlite3SafetyOff(db);
65363      while( sqlite3_step(pStmt)==SQLITE_ROW ){
65364        char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
65365        Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
65366        if( pIdx ){
65367          int iSample = sqlite3_column_int(pStmt, 1);
65368          sqlite3 *dbMem = pIdx->pTable->dbMem;
65369          assert( dbMem==db || dbMem==0 );
65370          if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
65371            int eType = sqlite3_column_type(pStmt, 2);
65372
65373            if( pIdx->aSample==0 ){
65374              static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
65375              pIdx->aSample = (IndexSample *)sqlite3DbMallocZero(dbMem, sz);
65376              if( pIdx->aSample==0 ){
65377                db->mallocFailed = 1;
65378                break;
65379              }
65380            }
65381
65382            assert( pIdx->aSample );
65383            {
65384              IndexSample *pSample = &pIdx->aSample[iSample];
65385              pSample->eType = (u8)eType;
65386              if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
65387                pSample->u.r = sqlite3_column_double(pStmt, 2);
65388              }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
65389                const char *z = (const char *)(
65390                    (eType==SQLITE_BLOB) ?
65391                    sqlite3_column_blob(pStmt, 2):
65392                    sqlite3_column_text(pStmt, 2)
65393                );
65394                int n = sqlite3_column_bytes(pStmt, 2);
65395                if( n>24 ){
65396                  n = 24;
65397                }
65398                pSample->nByte = (u8)n;
65399                pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
65400                if( pSample->u.z ){
65401                  memcpy(pSample->u.z, z, n);
65402                }else{
65403                  db->mallocFailed = 1;
65404                  break;
65405                }
65406              }
65407            }
65408          }
65409        }
65410      }
65411      rc = sqlite3_finalize(pStmt);
65412      (void)sqlite3SafetyOn(db);
65413    }
65414  }
65415#endif
65416
65417  if( rc==SQLITE_NOMEM ){
65418    db->mallocFailed = 1;
65419  }
65420  return rc;
65421}
65422
65423
65424#endif /* SQLITE_OMIT_ANALYZE */
65425
65426/************** End of analyze.c *********************************************/
65427/************** Begin file attach.c ******************************************/
65428/*
65429** 2003 April 6
65430**
65431** The author disclaims copyright to this source code.  In place of
65432** a legal notice, here is a blessing:
65433**
65434**    May you do good and not evil.
65435**    May you find forgiveness for yourself and forgive others.
65436**    May you share freely, never taking more than you give.
65437**
65438*************************************************************************
65439** This file contains code used to implement the ATTACH and DETACH commands.
65440*/
65441
65442#ifndef SQLITE_OMIT_ATTACH
65443/*
65444** Resolve an expression that was part of an ATTACH or DETACH statement. This
65445** is slightly different from resolving a normal SQL expression, because simple
65446** identifiers are treated as strings, not possible column names or aliases.
65447**
65448** i.e. if the parser sees:
65449**
65450**     ATTACH DATABASE abc AS def
65451**
65452** it treats the two expressions as literal strings 'abc' and 'def' instead of
65453** looking for columns of the same name.
65454**
65455** This only applies to the root node of pExpr, so the statement:
65456**
65457**     ATTACH DATABASE abc||def AS 'db2'
65458**
65459** will fail because neither abc or def can be resolved.
65460*/
65461static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
65462{
65463  int rc = SQLITE_OK;
65464  if( pExpr ){
65465    if( pExpr->op!=TK_ID ){
65466      rc = sqlite3ResolveExprNames(pName, pExpr);
65467      if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
65468        sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
65469        return SQLITE_ERROR;
65470      }
65471    }else{
65472      pExpr->op = TK_STRING;
65473    }
65474  }
65475  return rc;
65476}
65477
65478/*
65479** An SQL user-function registered to do the work of an ATTACH statement. The
65480** three arguments to the function come directly from an attach statement:
65481**
65482**     ATTACH DATABASE x AS y KEY z
65483**
65484**     SELECT sqlite_attach(x, y, z)
65485**
65486** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
65487** third argument.
65488*/
65489static void attachFunc(
65490  sqlite3_context *context,
65491  int NotUsed,
65492  sqlite3_value **argv
65493){
65494  int i;
65495  int rc = 0;
65496  sqlite3 *db = sqlite3_context_db_handle(context);
65497  const char *zName;
65498  const char *zFile;
65499  Db *aNew;
65500  char *zErrDyn = 0;
65501
65502  UNUSED_PARAMETER(NotUsed);
65503
65504  zFile = (const char *)sqlite3_value_text(argv[0]);
65505  zName = (const char *)sqlite3_value_text(argv[1]);
65506  if( zFile==0 ) zFile = "";
65507  if( zName==0 ) zName = "";
65508
65509  /* Check for the following errors:
65510  **
65511  **     * Too many attached databases,
65512  **     * Transaction currently open
65513  **     * Specified database name already being used.
65514  */
65515  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
65516    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
65517      db->aLimit[SQLITE_LIMIT_ATTACHED]
65518    );
65519    goto attach_error;
65520  }
65521  if( !db->autoCommit ){
65522    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
65523    goto attach_error;
65524  }
65525  for(i=0; i<db->nDb; i++){
65526    char *z = db->aDb[i].zName;
65527    assert( z && zName );
65528    if( sqlite3StrICmp(z, zName)==0 ){
65529      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
65530      goto attach_error;
65531    }
65532  }
65533
65534  /* Allocate the new entry in the db->aDb[] array and initialise the schema
65535  ** hash tables.
65536  */
65537  if( db->aDb==db->aDbStatic ){
65538    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
65539    if( aNew==0 ) return;
65540    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
65541  }else{
65542    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
65543    if( aNew==0 ) return;
65544  }
65545  db->aDb = aNew;
65546  aNew = &db->aDb[db->nDb];
65547  memset(aNew, 0, sizeof(*aNew));
65548
65549  /* Open the database file. If the btree is successfully opened, use
65550  ** it to obtain the database schema. At this point the schema may
65551  ** or may not be initialised.
65552  */
65553  rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
65554                           db->openFlags | SQLITE_OPEN_MAIN_DB,
65555                           &aNew->pBt);
65556  db->nDb++;
65557  if( rc==SQLITE_CONSTRAINT ){
65558    rc = SQLITE_ERROR;
65559    zErrDyn = sqlite3MPrintf(db, "database is already attached");
65560  }else if( rc==SQLITE_OK ){
65561    Pager *pPager;
65562    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
65563    if( !aNew->pSchema ){
65564      rc = SQLITE_NOMEM;
65565    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
65566      zErrDyn = sqlite3MPrintf(db,
65567        "attached databases must use the same text encoding as main database");
65568      rc = SQLITE_ERROR;
65569    }
65570    pPager = sqlite3BtreePager(aNew->pBt);
65571    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
65572    sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
65573  }
65574  aNew->zName = sqlite3DbStrDup(db, zName);
65575  aNew->safety_level = 3;
65576
65577#if SQLITE_HAS_CODEC
65578  if( rc==SQLITE_OK ){
65579    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
65580    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
65581    int nKey;
65582    char *zKey;
65583    int t = sqlite3_value_type(argv[2]);
65584    switch( t ){
65585      case SQLITE_INTEGER:
65586      case SQLITE_FLOAT:
65587        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
65588        rc = SQLITE_ERROR;
65589        break;
65590
65591      case SQLITE_TEXT:
65592      case SQLITE_BLOB:
65593        nKey = sqlite3_value_bytes(argv[2]);
65594        zKey = (char *)sqlite3_value_blob(argv[2]);
65595        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
65596        break;
65597
65598      case SQLITE_NULL:
65599        /* No key specified.  Use the key from the main database */
65600        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
65601        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
65602        break;
65603    }
65604  }
65605#endif
65606
65607  /* If the file was opened successfully, read the schema for the new database.
65608  ** If this fails, or if opening the file failed, then close the file and
65609  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
65610  ** we found it.
65611  */
65612  if( rc==SQLITE_OK ){
65613    (void)sqlite3SafetyOn(db);
65614    sqlite3BtreeEnterAll(db);
65615    rc = sqlite3Init(db, &zErrDyn);
65616    sqlite3BtreeLeaveAll(db);
65617    (void)sqlite3SafetyOff(db);
65618  }
65619  if( rc ){
65620    int iDb = db->nDb - 1;
65621    assert( iDb>=2 );
65622    if( db->aDb[iDb].pBt ){
65623      sqlite3BtreeClose(db->aDb[iDb].pBt);
65624      db->aDb[iDb].pBt = 0;
65625      db->aDb[iDb].pSchema = 0;
65626    }
65627    sqlite3ResetInternalSchema(db, 0);
65628    db->nDb = iDb;
65629    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
65630      db->mallocFailed = 1;
65631      sqlite3DbFree(db, zErrDyn);
65632      zErrDyn = sqlite3MPrintf(db, "out of memory");
65633    }else if( zErrDyn==0 ){
65634      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
65635    }
65636    goto attach_error;
65637  }
65638
65639  return;
65640
65641attach_error:
65642  /* Return an error if we get here */
65643  if( zErrDyn ){
65644    sqlite3_result_error(context, zErrDyn, -1);
65645    sqlite3DbFree(db, zErrDyn);
65646  }
65647  if( rc ) sqlite3_result_error_code(context, rc);
65648}
65649
65650/*
65651** An SQL user-function registered to do the work of an DETACH statement. The
65652** three arguments to the function come directly from a detach statement:
65653**
65654**     DETACH DATABASE x
65655**
65656**     SELECT sqlite_detach(x)
65657*/
65658static void detachFunc(
65659  sqlite3_context *context,
65660  int NotUsed,
65661  sqlite3_value **argv
65662){
65663  const char *zName = (const char *)sqlite3_value_text(argv[0]);
65664  sqlite3 *db = sqlite3_context_db_handle(context);
65665  int i;
65666  Db *pDb = 0;
65667  char zErr[128];
65668
65669  UNUSED_PARAMETER(NotUsed);
65670
65671  if( zName==0 ) zName = "";
65672  for(i=0; i<db->nDb; i++){
65673    pDb = &db->aDb[i];
65674    if( pDb->pBt==0 ) continue;
65675    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
65676  }
65677
65678  if( i>=db->nDb ){
65679    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
65680    goto detach_error;
65681  }
65682  if( i<2 ){
65683    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
65684    goto detach_error;
65685  }
65686  if( !db->autoCommit ){
65687    sqlite3_snprintf(sizeof(zErr), zErr,
65688                     "cannot DETACH database within transaction");
65689    goto detach_error;
65690  }
65691  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
65692    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
65693    goto detach_error;
65694  }
65695
65696  sqlite3BtreeClose(pDb->pBt);
65697  pDb->pBt = 0;
65698  pDb->pSchema = 0;
65699  sqlite3ResetInternalSchema(db, 0);
65700  return;
65701
65702detach_error:
65703  sqlite3_result_error(context, zErr, -1);
65704}
65705
65706/*
65707** This procedure generates VDBE code for a single invocation of either the
65708** sqlite_detach() or sqlite_attach() SQL user functions.
65709*/
65710static void codeAttach(
65711  Parse *pParse,       /* The parser context */
65712  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
65713  FuncDef *pFunc,      /* FuncDef wrapper for detachFunc() or attachFunc() */
65714  Expr *pAuthArg,      /* Expression to pass to authorization callback */
65715  Expr *pFilename,     /* Name of database file */
65716  Expr *pDbname,       /* Name of the database to use internally */
65717  Expr *pKey           /* Database key for encryption extension */
65718){
65719  int rc;
65720  NameContext sName;
65721  Vdbe *v;
65722  sqlite3* db = pParse->db;
65723  int regArgs;
65724
65725  memset(&sName, 0, sizeof(NameContext));
65726  sName.pParse = pParse;
65727
65728  if(
65729      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
65730      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
65731      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
65732  ){
65733    pParse->nErr++;
65734    goto attach_end;
65735  }
65736
65737#ifndef SQLITE_OMIT_AUTHORIZATION
65738  if( pAuthArg ){
65739    char *zAuthArg = pAuthArg->u.zToken;
65740    if( NEVER(zAuthArg==0) ){
65741      goto attach_end;
65742    }
65743    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
65744    if(rc!=SQLITE_OK ){
65745      goto attach_end;
65746    }
65747  }
65748#endif /* SQLITE_OMIT_AUTHORIZATION */
65749
65750
65751  v = sqlite3GetVdbe(pParse);
65752  regArgs = sqlite3GetTempRange(pParse, 4);
65753  sqlite3ExprCode(pParse, pFilename, regArgs);
65754  sqlite3ExprCode(pParse, pDbname, regArgs+1);
65755  sqlite3ExprCode(pParse, pKey, regArgs+2);
65756
65757  assert( v || db->mallocFailed );
65758  if( v ){
65759    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
65760    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
65761    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
65762    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
65763
65764    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
65765    ** statement only). For DETACH, set it to false (expire all existing
65766    ** statements).
65767    */
65768    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
65769  }
65770
65771attach_end:
65772  sqlite3ExprDelete(db, pFilename);
65773  sqlite3ExprDelete(db, pDbname);
65774  sqlite3ExprDelete(db, pKey);
65775}
65776
65777/*
65778** Called by the parser to compile a DETACH statement.
65779**
65780**     DETACH pDbname
65781*/
65782SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
65783  static FuncDef detach_func = {
65784    1,                /* nArg */
65785    SQLITE_UTF8,      /* iPrefEnc */
65786    0,                /* flags */
65787    0,                /* pUserData */
65788    0,                /* pNext */
65789    detachFunc,       /* xFunc */
65790    0,                /* xStep */
65791    0,                /* xFinalize */
65792    "sqlite_detach",  /* zName */
65793    0                 /* pHash */
65794  };
65795  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
65796}
65797
65798/*
65799** Called by the parser to compile an ATTACH statement.
65800**
65801**     ATTACH p AS pDbname KEY pKey
65802*/
65803SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
65804  static FuncDef attach_func = {
65805    3,                /* nArg */
65806    SQLITE_UTF8,      /* iPrefEnc */
65807    0,                /* flags */
65808    0,                /* pUserData */
65809    0,                /* pNext */
65810    attachFunc,       /* xFunc */
65811    0,                /* xStep */
65812    0,                /* xFinalize */
65813    "sqlite_attach",  /* zName */
65814    0                 /* pHash */
65815  };
65816  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
65817}
65818#endif /* SQLITE_OMIT_ATTACH */
65819
65820/*
65821** Initialize a DbFixer structure.  This routine must be called prior
65822** to passing the structure to one of the sqliteFixAAAA() routines below.
65823**
65824** The return value indicates whether or not fixation is required.  TRUE
65825** means we do need to fix the database references, FALSE means we do not.
65826*/
65827SQLITE_PRIVATE int sqlite3FixInit(
65828  DbFixer *pFix,      /* The fixer to be initialized */
65829  Parse *pParse,      /* Error messages will be written here */
65830  int iDb,            /* This is the database that must be used */
65831  const char *zType,  /* "view", "trigger", or "index" */
65832  const Token *pName  /* Name of the view, trigger, or index */
65833){
65834  sqlite3 *db;
65835
65836  if( NEVER(iDb<0) || iDb==1 ) return 0;
65837  db = pParse->db;
65838  assert( db->nDb>iDb );
65839  pFix->pParse = pParse;
65840  pFix->zDb = db->aDb[iDb].zName;
65841  pFix->zType = zType;
65842  pFix->pName = pName;
65843  return 1;
65844}
65845
65846/*
65847** The following set of routines walk through the parse tree and assign
65848** a specific database to all table references where the database name
65849** was left unspecified in the original SQL statement.  The pFix structure
65850** must have been initialized by a prior call to sqlite3FixInit().
65851**
65852** These routines are used to make sure that an index, trigger, or
65853** view in one database does not refer to objects in a different database.
65854** (Exception: indices, triggers, and views in the TEMP database are
65855** allowed to refer to anything.)  If a reference is explicitly made
65856** to an object in a different database, an error message is added to
65857** pParse->zErrMsg and these routines return non-zero.  If everything
65858** checks out, these routines return 0.
65859*/
65860SQLITE_PRIVATE int sqlite3FixSrcList(
65861  DbFixer *pFix,       /* Context of the fixation */
65862  SrcList *pList       /* The Source list to check and modify */
65863){
65864  int i;
65865  const char *zDb;
65866  struct SrcList_item *pItem;
65867
65868  if( NEVER(pList==0) ) return 0;
65869  zDb = pFix->zDb;
65870  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
65871    if( pItem->zDatabase==0 ){
65872      pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
65873    }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
65874      sqlite3ErrorMsg(pFix->pParse,
65875         "%s %T cannot reference objects in database %s",
65876         pFix->zType, pFix->pName, pItem->zDatabase);
65877      return 1;
65878    }
65879#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
65880    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
65881    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
65882#endif
65883  }
65884  return 0;
65885}
65886#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
65887SQLITE_PRIVATE int sqlite3FixSelect(
65888  DbFixer *pFix,       /* Context of the fixation */
65889  Select *pSelect      /* The SELECT statement to be fixed to one database */
65890){
65891  while( pSelect ){
65892    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
65893      return 1;
65894    }
65895    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
65896      return 1;
65897    }
65898    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
65899      return 1;
65900    }
65901    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
65902      return 1;
65903    }
65904    pSelect = pSelect->pPrior;
65905  }
65906  return 0;
65907}
65908SQLITE_PRIVATE int sqlite3FixExpr(
65909  DbFixer *pFix,     /* Context of the fixation */
65910  Expr *pExpr        /* The expression to be fixed to one database */
65911){
65912  while( pExpr ){
65913    if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
65914    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
65915      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
65916    }else{
65917      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
65918    }
65919    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
65920      return 1;
65921    }
65922    pExpr = pExpr->pLeft;
65923  }
65924  return 0;
65925}
65926SQLITE_PRIVATE int sqlite3FixExprList(
65927  DbFixer *pFix,     /* Context of the fixation */
65928  ExprList *pList    /* The expression to be fixed to one database */
65929){
65930  int i;
65931  struct ExprList_item *pItem;
65932  if( pList==0 ) return 0;
65933  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
65934    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
65935      return 1;
65936    }
65937  }
65938  return 0;
65939}
65940#endif
65941
65942#ifndef SQLITE_OMIT_TRIGGER
65943SQLITE_PRIVATE int sqlite3FixTriggerStep(
65944  DbFixer *pFix,     /* Context of the fixation */
65945  TriggerStep *pStep /* The trigger step be fixed to one database */
65946){
65947  while( pStep ){
65948    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
65949      return 1;
65950    }
65951    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
65952      return 1;
65953    }
65954    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
65955      return 1;
65956    }
65957    pStep = pStep->pNext;
65958  }
65959  return 0;
65960}
65961#endif
65962
65963/************** End of attach.c **********************************************/
65964/************** Begin file auth.c ********************************************/
65965/*
65966** 2003 January 11
65967**
65968** The author disclaims copyright to this source code.  In place of
65969** a legal notice, here is a blessing:
65970**
65971**    May you do good and not evil.
65972**    May you find forgiveness for yourself and forgive others.
65973**    May you share freely, never taking more than you give.
65974**
65975*************************************************************************
65976** This file contains code used to implement the sqlite3_set_authorizer()
65977** API.  This facility is an optional feature of the library.  Embedded
65978** systems that do not need this facility may omit it by recompiling
65979** the library with -DSQLITE_OMIT_AUTHORIZATION=1
65980*/
65981
65982/*
65983** All of the code in this file may be omitted by defining a single
65984** macro.
65985*/
65986#ifndef SQLITE_OMIT_AUTHORIZATION
65987
65988/*
65989** Set or clear the access authorization function.
65990**
65991** The access authorization function is be called during the compilation
65992** phase to verify that the user has read and/or write access permission on
65993** various fields of the database.  The first argument to the auth function
65994** is a copy of the 3rd argument to this routine.  The second argument
65995** to the auth function is one of these constants:
65996**
65997**       SQLITE_CREATE_INDEX
65998**       SQLITE_CREATE_TABLE
65999**       SQLITE_CREATE_TEMP_INDEX
66000**       SQLITE_CREATE_TEMP_TABLE
66001**       SQLITE_CREATE_TEMP_TRIGGER
66002**       SQLITE_CREATE_TEMP_VIEW
66003**       SQLITE_CREATE_TRIGGER
66004**       SQLITE_CREATE_VIEW
66005**       SQLITE_DELETE
66006**       SQLITE_DROP_INDEX
66007**       SQLITE_DROP_TABLE
66008**       SQLITE_DROP_TEMP_INDEX
66009**       SQLITE_DROP_TEMP_TABLE
66010**       SQLITE_DROP_TEMP_TRIGGER
66011**       SQLITE_DROP_TEMP_VIEW
66012**       SQLITE_DROP_TRIGGER
66013**       SQLITE_DROP_VIEW
66014**       SQLITE_INSERT
66015**       SQLITE_PRAGMA
66016**       SQLITE_READ
66017**       SQLITE_SELECT
66018**       SQLITE_TRANSACTION
66019**       SQLITE_UPDATE
66020**
66021** The third and fourth arguments to the auth function are the name of
66022** the table and the column that are being accessed.  The auth function
66023** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
66024** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
66025** means that the SQL statement will never-run - the sqlite3_exec() call
66026** will return with an error.  SQLITE_IGNORE means that the SQL statement
66027** should run but attempts to read the specified column will return NULL
66028** and attempts to write the column will be ignored.
66029**
66030** Setting the auth function to NULL disables this hook.  The default
66031** setting of the auth function is NULL.
66032*/
66033SQLITE_API int sqlite3_set_authorizer(
66034  sqlite3 *db,
66035  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
66036  void *pArg
66037){
66038  sqlite3_mutex_enter(db->mutex);
66039  db->xAuth = xAuth;
66040  db->pAuthArg = pArg;
66041  sqlite3ExpirePreparedStatements(db);
66042  sqlite3_mutex_leave(db->mutex);
66043  return SQLITE_OK;
66044}
66045
66046/*
66047** Write an error message into pParse->zErrMsg that explains that the
66048** user-supplied authorization function returned an illegal value.
66049*/
66050static void sqliteAuthBadReturnCode(Parse *pParse){
66051  sqlite3ErrorMsg(pParse, "authorizer malfunction");
66052  pParse->rc = SQLITE_ERROR;
66053}
66054
66055/*
66056** Invoke the authorization callback for permission to read column zCol from
66057** table zTab in database zDb. This function assumes that an authorization
66058** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
66059**
66060** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
66061** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
66062** is treated as SQLITE_DENY. In this case an error is left in pParse.
66063*/
66064SQLITE_PRIVATE int sqlite3AuthReadCol(
66065  Parse *pParse,                  /* The parser context */
66066  const char *zTab,               /* Table name */
66067  const char *zCol,               /* Column name */
66068  int iDb                         /* Index of containing database. */
66069){
66070  sqlite3 *db = pParse->db;       /* Database handle */
66071  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
66072  int rc;                         /* Auth callback return code */
66073
66074  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
66075  if( rc==SQLITE_DENY ){
66076    if( db->nDb>2 || iDb!=0 ){
66077      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
66078    }else{
66079      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
66080    }
66081    pParse->rc = SQLITE_AUTH;
66082  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
66083    sqliteAuthBadReturnCode(pParse);
66084  }
66085  return rc;
66086}
66087
66088/*
66089** The pExpr should be a TK_COLUMN expression.  The table referred to
66090** is in pTabList or else it is the NEW or OLD table of a trigger.
66091** Check to see if it is OK to read this particular column.
66092**
66093** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
66094** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
66095** then generate an error.
66096*/
66097SQLITE_PRIVATE void sqlite3AuthRead(
66098  Parse *pParse,        /* The parser context */
66099  Expr *pExpr,          /* The expression to check authorization on */
66100  Schema *pSchema,      /* The schema of the expression */
66101  SrcList *pTabList     /* All table that pExpr might refer to */
66102){
66103  sqlite3 *db = pParse->db;
66104  Table *pTab = 0;      /* The table being read */
66105  const char *zCol;     /* Name of the column of the table */
66106  int iSrc;             /* Index in pTabList->a[] of table being read */
66107  int iDb;              /* The index of the database the expression refers to */
66108  int iCol;             /* Index of column in table */
66109
66110  if( db->xAuth==0 ) return;
66111  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
66112  if( iDb<0 ){
66113    /* An attempt to read a column out of a subquery or other
66114    ** temporary table. */
66115    return;
66116  }
66117
66118  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
66119  if( pExpr->op==TK_TRIGGER ){
66120    pTab = pParse->pTriggerTab;
66121  }else{
66122    assert( pTabList );
66123    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
66124      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
66125        pTab = pTabList->a[iSrc].pTab;
66126        break;
66127      }
66128    }
66129  }
66130  iCol = pExpr->iColumn;
66131  if( NEVER(pTab==0) ) return;
66132
66133  if( iCol>=0 ){
66134    assert( iCol<pTab->nCol );
66135    zCol = pTab->aCol[iCol].zName;
66136  }else if( pTab->iPKey>=0 ){
66137    assert( pTab->iPKey<pTab->nCol );
66138    zCol = pTab->aCol[pTab->iPKey].zName;
66139  }else{
66140    zCol = "ROWID";
66141  }
66142  assert( iDb>=0 && iDb<db->nDb );
66143  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
66144    pExpr->op = TK_NULL;
66145  }
66146}
66147
66148/*
66149** Do an authorization check using the code and arguments given.  Return
66150** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
66151** is returned, then the error count and error message in pParse are
66152** modified appropriately.
66153*/
66154SQLITE_PRIVATE int sqlite3AuthCheck(
66155  Parse *pParse,
66156  int code,
66157  const char *zArg1,
66158  const char *zArg2,
66159  const char *zArg3
66160){
66161  sqlite3 *db = pParse->db;
66162  int rc;
66163
66164  /* Don't do any authorization checks if the database is initialising
66165  ** or if the parser is being invoked from within sqlite3_declare_vtab.
66166  */
66167  if( db->init.busy || IN_DECLARE_VTAB ){
66168    return SQLITE_OK;
66169  }
66170
66171  if( db->xAuth==0 ){
66172    return SQLITE_OK;
66173  }
66174  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
66175  if( rc==SQLITE_DENY ){
66176    sqlite3ErrorMsg(pParse, "not authorized");
66177    pParse->rc = SQLITE_AUTH;
66178  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
66179    rc = SQLITE_DENY;
66180    sqliteAuthBadReturnCode(pParse);
66181  }
66182  return rc;
66183}
66184
66185/*
66186** Push an authorization context.  After this routine is called, the
66187** zArg3 argument to authorization callbacks will be zContext until
66188** popped.  Or if pParse==0, this routine is a no-op.
66189*/
66190SQLITE_PRIVATE void sqlite3AuthContextPush(
66191  Parse *pParse,
66192  AuthContext *pContext,
66193  const char *zContext
66194){
66195  assert( pParse );
66196  pContext->pParse = pParse;
66197  pContext->zAuthContext = pParse->zAuthContext;
66198  pParse->zAuthContext = zContext;
66199}
66200
66201/*
66202** Pop an authorization context that was previously pushed
66203** by sqlite3AuthContextPush
66204*/
66205SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
66206  if( pContext->pParse ){
66207    pContext->pParse->zAuthContext = pContext->zAuthContext;
66208    pContext->pParse = 0;
66209  }
66210}
66211
66212#endif /* SQLITE_OMIT_AUTHORIZATION */
66213
66214/************** End of auth.c ************************************************/
66215/************** Begin file build.c *******************************************/
66216/*
66217** 2001 September 15
66218**
66219** The author disclaims copyright to this source code.  In place of
66220** a legal notice, here is a blessing:
66221**
66222**    May you do good and not evil.
66223**    May you find forgiveness for yourself and forgive others.
66224**    May you share freely, never taking more than you give.
66225**
66226*************************************************************************
66227** This file contains C code routines that are called by the SQLite parser
66228** when syntax rules are reduced.  The routines in this file handle the
66229** following kinds of SQL syntax:
66230**
66231**     CREATE TABLE
66232**     DROP TABLE
66233**     CREATE INDEX
66234**     DROP INDEX
66235**     creating ID lists
66236**     BEGIN TRANSACTION
66237**     COMMIT
66238**     ROLLBACK
66239*/
66240
66241/*
66242** This routine is called when a new SQL statement is beginning to
66243** be parsed.  Initialize the pParse structure as needed.
66244*/
66245SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
66246  pParse->explain = (u8)explainFlag;
66247  pParse->nVar = 0;
66248}
66249
66250#ifndef SQLITE_OMIT_SHARED_CACHE
66251/*
66252** The TableLock structure is only used by the sqlite3TableLock() and
66253** codeTableLocks() functions.
66254*/
66255struct TableLock {
66256  int iDb;             /* The database containing the table to be locked */
66257  int iTab;            /* The root page of the table to be locked */
66258  u8 isWriteLock;      /* True for write lock.  False for a read lock */
66259  const char *zName;   /* Name of the table */
66260};
66261
66262/*
66263** Record the fact that we want to lock a table at run-time.
66264**
66265** The table to be locked has root page iTab and is found in database iDb.
66266** A read or a write lock can be taken depending on isWritelock.
66267**
66268** This routine just records the fact that the lock is desired.  The
66269** code to make the lock occur is generated by a later call to
66270** codeTableLocks() which occurs during sqlite3FinishCoding().
66271*/
66272SQLITE_PRIVATE void sqlite3TableLock(
66273  Parse *pParse,     /* Parsing context */
66274  int iDb,           /* Index of the database containing the table to lock */
66275  int iTab,          /* Root page number of the table to be locked */
66276  u8 isWriteLock,    /* True for a write lock */
66277  const char *zName  /* Name of the table to be locked */
66278){
66279  Parse *pToplevel = sqlite3ParseToplevel(pParse);
66280  int i;
66281  int nBytes;
66282  TableLock *p;
66283  assert( iDb>=0 );
66284
66285  for(i=0; i<pToplevel->nTableLock; i++){
66286    p = &pToplevel->aTableLock[i];
66287    if( p->iDb==iDb && p->iTab==iTab ){
66288      p->isWriteLock = (p->isWriteLock || isWriteLock);
66289      return;
66290    }
66291  }
66292
66293  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
66294  pToplevel->aTableLock =
66295      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
66296  if( pToplevel->aTableLock ){
66297    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
66298    p->iDb = iDb;
66299    p->iTab = iTab;
66300    p->isWriteLock = isWriteLock;
66301    p->zName = zName;
66302  }else{
66303    pToplevel->nTableLock = 0;
66304    pToplevel->db->mallocFailed = 1;
66305  }
66306}
66307
66308/*
66309** Code an OP_TableLock instruction for each table locked by the
66310** statement (configured by calls to sqlite3TableLock()).
66311*/
66312static void codeTableLocks(Parse *pParse){
66313  int i;
66314  Vdbe *pVdbe;
66315
66316  pVdbe = sqlite3GetVdbe(pParse);
66317  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
66318
66319  for(i=0; i<pParse->nTableLock; i++){
66320    TableLock *p = &pParse->aTableLock[i];
66321    int p1 = p->iDb;
66322    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
66323                      p->zName, P4_STATIC);
66324  }
66325}
66326#else
66327  #define codeTableLocks(x)
66328#endif
66329
66330/*
66331** This routine is called after a single SQL statement has been
66332** parsed and a VDBE program to execute that statement has been
66333** prepared.  This routine puts the finishing touches on the
66334** VDBE program and resets the pParse structure for the next
66335** parse.
66336**
66337** Note that if an error occurred, it might be the case that
66338** no VDBE code was generated.
66339*/
66340SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
66341  sqlite3 *db;
66342  Vdbe *v;
66343
66344  db = pParse->db;
66345  if( db->mallocFailed ) return;
66346  if( pParse->nested ) return;
66347  if( pParse->nErr ) return;
66348
66349  /* Begin by generating some termination code at the end of the
66350  ** vdbe program
66351  */
66352  v = sqlite3GetVdbe(pParse);
66353  assert( !pParse->isMultiWrite
66354       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
66355  if( v ){
66356    sqlite3VdbeAddOp0(v, OP_Halt);
66357
66358    /* The cookie mask contains one bit for each database file open.
66359    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
66360    ** set for each database that is used.  Generate code to start a
66361    ** transaction on each used database and to verify the schema cookie
66362    ** on each used database.
66363    */
66364    if( pParse->cookieGoto>0 ){
66365      u32 mask;
66366      int iDb;
66367      sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
66368      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
66369        if( (mask & pParse->cookieMask)==0 ) continue;
66370        sqlite3VdbeUsesBtree(v, iDb);
66371        sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
66372        if( db->init.busy==0 ){
66373          sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
66374        }
66375      }
66376#ifndef SQLITE_OMIT_VIRTUALTABLE
66377      {
66378        int i;
66379        for(i=0; i<pParse->nVtabLock; i++){
66380          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
66381          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
66382        }
66383        pParse->nVtabLock = 0;
66384      }
66385#endif
66386
66387      /* Once all the cookies have been verified and transactions opened,
66388      ** obtain the required table-locks. This is a no-op unless the
66389      ** shared-cache feature is enabled.
66390      */
66391      codeTableLocks(pParse);
66392
66393      /* Initialize any AUTOINCREMENT data structures required.
66394      */
66395      sqlite3AutoincrementBegin(pParse);
66396
66397      /* Finally, jump back to the beginning of the executable code. */
66398      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
66399    }
66400  }
66401
66402
66403  /* Get the VDBE program ready for execution
66404  */
66405  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
66406#ifdef SQLITE_DEBUG
66407    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
66408    sqlite3VdbeTrace(v, trace);
66409#endif
66410    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
66411    /* A minimum of one cursor is required if autoincrement is used
66412    *  See ticket [a696379c1f08866] */
66413    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
66414    sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
66415                         pParse->nTab, pParse->nMaxArg, pParse->explain,
66416                         pParse->isMultiWrite && pParse->mayAbort);
66417    pParse->rc = SQLITE_DONE;
66418    pParse->colNamesSet = 0;
66419  }else if( pParse->rc==SQLITE_OK ){
66420    pParse->rc = SQLITE_ERROR;
66421  }
66422  pParse->nTab = 0;
66423  pParse->nMem = 0;
66424  pParse->nSet = 0;
66425  pParse->nVar = 0;
66426  pParse->cookieMask = 0;
66427  pParse->cookieGoto = 0;
66428}
66429
66430/*
66431** Run the parser and code generator recursively in order to generate
66432** code for the SQL statement given onto the end of the pParse context
66433** currently under construction.  When the parser is run recursively
66434** this way, the final OP_Halt is not appended and other initialization
66435** and finalization steps are omitted because those are handling by the
66436** outermost parser.
66437**
66438** Not everything is nestable.  This facility is designed to permit
66439** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
66440** care if you decide to try to use this routine for some other purposes.
66441*/
66442SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
66443  va_list ap;
66444  char *zSql;
66445  char *zErrMsg = 0;
66446  sqlite3 *db = pParse->db;
66447# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
66448  char saveBuf[SAVE_SZ];
66449
66450  if( pParse->nErr ) return;
66451  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
66452  va_start(ap, zFormat);
66453  zSql = sqlite3VMPrintf(db, zFormat, ap);
66454  va_end(ap);
66455  if( zSql==0 ){
66456    return;   /* A malloc must have failed */
66457  }
66458  pParse->nested++;
66459  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
66460  memset(&pParse->nVar, 0, SAVE_SZ);
66461  sqlite3RunParser(pParse, zSql, &zErrMsg);
66462  sqlite3DbFree(db, zErrMsg);
66463  sqlite3DbFree(db, zSql);
66464  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
66465  pParse->nested--;
66466}
66467
66468/*
66469** Locate the in-memory structure that describes a particular database
66470** table given the name of that table and (optionally) the name of the
66471** database containing the table.  Return NULL if not found.
66472**
66473** If zDatabase is 0, all databases are searched for the table and the
66474** first matching table is returned.  (No checking for duplicate table
66475** names is done.)  The search order is TEMP first, then MAIN, then any
66476** auxiliary databases added using the ATTACH command.
66477**
66478** See also sqlite3LocateTable().
66479*/
66480SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
66481  Table *p = 0;
66482  int i;
66483  int nName;
66484  assert( zName!=0 );
66485  nName = sqlite3Strlen30(zName);
66486  for(i=OMIT_TEMPDB; i<db->nDb; i++){
66487    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
66488    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
66489    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
66490    if( p ) break;
66491  }
66492  return p;
66493}
66494
66495/*
66496** Locate the in-memory structure that describes a particular database
66497** table given the name of that table and (optionally) the name of the
66498** database containing the table.  Return NULL if not found.  Also leave an
66499** error message in pParse->zErrMsg.
66500**
66501** The difference between this routine and sqlite3FindTable() is that this
66502** routine leaves an error message in pParse->zErrMsg where
66503** sqlite3FindTable() does not.
66504*/
66505SQLITE_PRIVATE Table *sqlite3LocateTable(
66506  Parse *pParse,         /* context in which to report errors */
66507  int isView,            /* True if looking for a VIEW rather than a TABLE */
66508  const char *zName,     /* Name of the table we are looking for */
66509  const char *zDbase     /* Name of the database.  Might be NULL */
66510){
66511  Table *p;
66512
66513  /* Read the database schema. If an error occurs, leave an error message
66514  ** and code in pParse and return NULL. */
66515  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
66516    return 0;
66517  }
66518
66519  p = sqlite3FindTable(pParse->db, zName, zDbase);
66520  if( p==0 ){
66521    const char *zMsg = isView ? "no such view" : "no such table";
66522    if( zDbase ){
66523      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
66524    }else{
66525      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
66526    }
66527    pParse->checkSchema = 1;
66528  }
66529  return p;
66530}
66531
66532/*
66533** Locate the in-memory structure that describes
66534** a particular index given the name of that index
66535** and the name of the database that contains the index.
66536** Return NULL if not found.
66537**
66538** If zDatabase is 0, all databases are searched for the
66539** table and the first matching index is returned.  (No checking
66540** for duplicate index names is done.)  The search order is
66541** TEMP first, then MAIN, then any auxiliary databases added
66542** using the ATTACH command.
66543*/
66544SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
66545  Index *p = 0;
66546  int i;
66547  int nName = sqlite3Strlen30(zName);
66548  for(i=OMIT_TEMPDB; i<db->nDb; i++){
66549    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
66550    Schema *pSchema = db->aDb[j].pSchema;
66551    assert( pSchema );
66552    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
66553    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
66554    if( p ) break;
66555  }
66556  return p;
66557}
66558
66559/*
66560** Reclaim the memory used by an index
66561*/
66562static void freeIndex(Index *p){
66563  sqlite3 *db = p->pTable->dbMem;
66564#ifndef SQLITE_OMIT_ANALYZE
66565  sqlite3DeleteIndexSamples(p);
66566#endif
66567  sqlite3DbFree(db, p->zColAff);
66568  sqlite3DbFree(db, p);
66569}
66570
66571/*
66572** Remove the given index from the index hash table, and free
66573** its memory structures.
66574**
66575** The index is removed from the database hash tables but
66576** it is not unlinked from the Table that it indexes.
66577** Unlinking from the Table must be done by the calling function.
66578*/
66579static void sqlite3DeleteIndex(Index *p){
66580  Index *pOld;
66581  const char *zName = p->zName;
66582
66583  pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
66584                           sqlite3Strlen30(zName), 0);
66585  assert( pOld==0 || pOld==p );
66586  freeIndex(p);
66587}
66588
66589/*
66590** For the index called zIdxName which is found in the database iDb,
66591** unlike that index from its Table then remove the index from
66592** the index hash table and free all memory structures associated
66593** with the index.
66594*/
66595SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
66596  Index *pIndex;
66597  int len;
66598  Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
66599
66600  len = sqlite3Strlen30(zIdxName);
66601  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
66602  if( pIndex ){
66603    if( pIndex->pTable->pIndex==pIndex ){
66604      pIndex->pTable->pIndex = pIndex->pNext;
66605    }else{
66606      Index *p;
66607      /* Justification of ALWAYS();  The index must be on the list of
66608      ** indices. */
66609      p = pIndex->pTable->pIndex;
66610      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
66611      if( ALWAYS(p && p->pNext==pIndex) ){
66612        p->pNext = pIndex->pNext;
66613      }
66614    }
66615    freeIndex(pIndex);
66616  }
66617  db->flags |= SQLITE_InternChanges;
66618}
66619
66620/*
66621** Erase all schema information from the in-memory hash tables of
66622** a single database.  This routine is called to reclaim memory
66623** before the database closes.  It is also called during a rollback
66624** if there were schema changes during the transaction or if a
66625** schema-cookie mismatch occurs.
66626**
66627** If iDb==0 then reset the internal schema tables for all database
66628** files.  If iDb>=1 then reset the internal schema for only the
66629** single file indicated.
66630*/
66631SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
66632  int i, j;
66633  assert( iDb>=0 && iDb<db->nDb );
66634
66635  if( iDb==0 ){
66636    sqlite3BtreeEnterAll(db);
66637  }
66638  for(i=iDb; i<db->nDb; i++){
66639    Db *pDb = &db->aDb[i];
66640    if( pDb->pSchema ){
66641      assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
66642      sqlite3SchemaFree(pDb->pSchema);
66643    }
66644    if( iDb>0 ) return;
66645  }
66646  assert( iDb==0 );
66647  db->flags &= ~SQLITE_InternChanges;
66648  sqlite3VtabUnlockList(db);
66649  sqlite3BtreeLeaveAll(db);
66650
66651  /* If one or more of the auxiliary database files has been closed,
66652  ** then remove them from the auxiliary database list.  We take the
66653  ** opportunity to do this here since we have just deleted all of the
66654  ** schema hash tables and therefore do not have to make any changes
66655  ** to any of those tables.
66656  */
66657  for(i=j=2; i<db->nDb; i++){
66658    struct Db *pDb = &db->aDb[i];
66659    if( pDb->pBt==0 ){
66660      sqlite3DbFree(db, pDb->zName);
66661      pDb->zName = 0;
66662      continue;
66663    }
66664    if( j<i ){
66665      db->aDb[j] = db->aDb[i];
66666    }
66667    j++;
66668  }
66669  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
66670  db->nDb = j;
66671  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
66672    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
66673    sqlite3DbFree(db, db->aDb);
66674    db->aDb = db->aDbStatic;
66675  }
66676}
66677
66678/*
66679** This routine is called when a commit occurs.
66680*/
66681SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
66682  db->flags &= ~SQLITE_InternChanges;
66683}
66684
66685/*
66686** Clear the column names from a table or view.
66687*/
66688static void sqliteResetColumnNames(Table *pTable){
66689  int i;
66690  Column *pCol;
66691  sqlite3 *db = pTable->dbMem;
66692  testcase( db==0 );
66693  assert( pTable!=0 );
66694  if( (pCol = pTable->aCol)!=0 ){
66695    for(i=0; i<pTable->nCol; i++, pCol++){
66696      sqlite3DbFree(db, pCol->zName);
66697      sqlite3ExprDelete(db, pCol->pDflt);
66698      sqlite3DbFree(db, pCol->zDflt);
66699      sqlite3DbFree(db, pCol->zType);
66700      sqlite3DbFree(db, pCol->zColl);
66701    }
66702    sqlite3DbFree(db, pTable->aCol);
66703  }
66704  pTable->aCol = 0;
66705  pTable->nCol = 0;
66706}
66707
66708/*
66709** Remove the memory data structures associated with the given
66710** Table.  No changes are made to disk by this routine.
66711**
66712** This routine just deletes the data structure.  It does not unlink
66713** the table data structure from the hash table.  But it does destroy
66714** memory structures of the indices and foreign keys associated with
66715** the table.
66716*/
66717SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
66718  Index *pIndex, *pNext;
66719  sqlite3 *db;
66720
66721  if( pTable==0 ) return;
66722  db = pTable->dbMem;
66723  testcase( db==0 );
66724
66725  /* Do not delete the table until the reference count reaches zero. */
66726  pTable->nRef--;
66727  if( pTable->nRef>0 ){
66728    return;
66729  }
66730  assert( pTable->nRef==0 );
66731
66732  /* Delete all indices associated with this table
66733  */
66734  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
66735    pNext = pIndex->pNext;
66736    assert( pIndex->pSchema==pTable->pSchema );
66737    sqlite3DeleteIndex(pIndex);
66738  }
66739
66740  /* Delete any foreign keys attached to this table. */
66741  sqlite3FkDelete(pTable);
66742
66743  /* Delete the Table structure itself.
66744  */
66745  sqliteResetColumnNames(pTable);
66746  sqlite3DbFree(db, pTable->zName);
66747  sqlite3DbFree(db, pTable->zColAff);
66748  sqlite3SelectDelete(db, pTable->pSelect);
66749#ifndef SQLITE_OMIT_CHECK
66750  sqlite3ExprDelete(db, pTable->pCheck);
66751#endif
66752  sqlite3VtabClear(pTable);
66753  sqlite3DbFree(db, pTable);
66754}
66755
66756/*
66757** Unlink the given table from the hash tables and the delete the
66758** table structure with all its indices and foreign keys.
66759*/
66760SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
66761  Table *p;
66762  Db *pDb;
66763
66764  assert( db!=0 );
66765  assert( iDb>=0 && iDb<db->nDb );
66766  assert( zTabName );
66767  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
66768  pDb = &db->aDb[iDb];
66769  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
66770                        sqlite3Strlen30(zTabName),0);
66771  sqlite3DeleteTable(p);
66772  db->flags |= SQLITE_InternChanges;
66773}
66774
66775/*
66776** Given a token, return a string that consists of the text of that
66777** token.  Space to hold the returned string
66778** is obtained from sqliteMalloc() and must be freed by the calling
66779** function.
66780**
66781** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
66782** surround the body of the token are removed.
66783**
66784** Tokens are often just pointers into the original SQL text and so
66785** are not \000 terminated and are not persistent.  The returned string
66786** is \000 terminated and is persistent.
66787*/
66788SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
66789  char *zName;
66790  if( pName ){
66791    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
66792    sqlite3Dequote(zName);
66793  }else{
66794    zName = 0;
66795  }
66796  return zName;
66797}
66798
66799/*
66800** Open the sqlite_master table stored in database number iDb for
66801** writing. The table is opened using cursor 0.
66802*/
66803SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
66804  Vdbe *v = sqlite3GetVdbe(p);
66805  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
66806  sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
66807  sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
66808  if( p->nTab==0 ){
66809    p->nTab = 1;
66810  }
66811}
66812
66813/*
66814** Parameter zName points to a nul-terminated buffer containing the name
66815** of a database ("main", "temp" or the name of an attached db). This
66816** function returns the index of the named database in db->aDb[], or
66817** -1 if the named db cannot be found.
66818*/
66819SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
66820  int i = -1;         /* Database number */
66821  if( zName ){
66822    Db *pDb;
66823    int n = sqlite3Strlen30(zName);
66824    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
66825      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
66826          0==sqlite3StrICmp(pDb->zName, zName) ){
66827        break;
66828      }
66829    }
66830  }
66831  return i;
66832}
66833
66834/*
66835** The token *pName contains the name of a database (either "main" or
66836** "temp" or the name of an attached db). This routine returns the
66837** index of the named database in db->aDb[], or -1 if the named db
66838** does not exist.
66839*/
66840SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
66841  int i;                               /* Database number */
66842  char *zName;                         /* Name we are searching for */
66843  zName = sqlite3NameFromToken(db, pName);
66844  i = sqlite3FindDbName(db, zName);
66845  sqlite3DbFree(db, zName);
66846  return i;
66847}
66848
66849/* The table or view or trigger name is passed to this routine via tokens
66850** pName1 and pName2. If the table name was fully qualified, for example:
66851**
66852** CREATE TABLE xxx.yyy (...);
66853**
66854** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
66855** the table name is not fully qualified, i.e.:
66856**
66857** CREATE TABLE yyy(...);
66858**
66859** Then pName1 is set to "yyy" and pName2 is "".
66860**
66861** This routine sets the *ppUnqual pointer to point at the token (pName1 or
66862** pName2) that stores the unqualified table name.  The index of the
66863** database "xxx" is returned.
66864*/
66865SQLITE_PRIVATE int sqlite3TwoPartName(
66866  Parse *pParse,      /* Parsing and code generating context */
66867  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
66868  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
66869  Token **pUnqual     /* Write the unqualified object name here */
66870){
66871  int iDb;                    /* Database holding the object */
66872  sqlite3 *db = pParse->db;
66873
66874  if( ALWAYS(pName2!=0) && pName2->n>0 ){
66875    if( db->init.busy ) {
66876      sqlite3ErrorMsg(pParse, "corrupt database");
66877      pParse->nErr++;
66878      return -1;
66879    }
66880    *pUnqual = pName2;
66881    iDb = sqlite3FindDb(db, pName1);
66882    if( iDb<0 ){
66883      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
66884      pParse->nErr++;
66885      return -1;
66886    }
66887  }else{
66888    assert( db->init.iDb==0 || db->init.busy );
66889    iDb = db->init.iDb;
66890    *pUnqual = pName1;
66891  }
66892  return iDb;
66893}
66894
66895/*
66896** This routine is used to check if the UTF-8 string zName is a legal
66897** unqualified name for a new schema object (table, index, view or
66898** trigger). All names are legal except those that begin with the string
66899** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
66900** is reserved for internal use.
66901*/
66902SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
66903  if( !pParse->db->init.busy && pParse->nested==0
66904          && (pParse->db->flags & SQLITE_WriteSchema)==0
66905          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
66906    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
66907    return SQLITE_ERROR;
66908  }
66909  return SQLITE_OK;
66910}
66911
66912/*
66913** Begin constructing a new table representation in memory.  This is
66914** the first of several action routines that get called in response
66915** to a CREATE TABLE statement.  In particular, this routine is called
66916** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
66917** flag is true if the table should be stored in the auxiliary database
66918** file instead of in the main database file.  This is normally the case
66919** when the "TEMP" or "TEMPORARY" keyword occurs in between
66920** CREATE and TABLE.
66921**
66922** The new table record is initialized and put in pParse->pNewTable.
66923** As more of the CREATE TABLE statement is parsed, additional action
66924** routines will be called to add more information to this record.
66925** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
66926** is called to complete the construction of the new table record.
66927*/
66928SQLITE_PRIVATE void sqlite3StartTable(
66929  Parse *pParse,   /* Parser context */
66930  Token *pName1,   /* First part of the name of the table or view */
66931  Token *pName2,   /* Second part of the name of the table or view */
66932  int isTemp,      /* True if this is a TEMP table */
66933  int isView,      /* True if this is a VIEW */
66934  int isVirtual,   /* True if this is a VIRTUAL table */
66935  int noErr        /* Do nothing if table already exists */
66936){
66937  Table *pTable;
66938  char *zName = 0; /* The name of the new table */
66939  sqlite3 *db = pParse->db;
66940  Vdbe *v;
66941  int iDb;         /* Database number to create the table in */
66942  Token *pName;    /* Unqualified name of the table to create */
66943
66944  /* The table or view name to create is passed to this routine via tokens
66945  ** pName1 and pName2. If the table name was fully qualified, for example:
66946  **
66947  ** CREATE TABLE xxx.yyy (...);
66948  **
66949  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
66950  ** the table name is not fully qualified, i.e.:
66951  **
66952  ** CREATE TABLE yyy(...);
66953  **
66954  ** Then pName1 is set to "yyy" and pName2 is "".
66955  **
66956  ** The call below sets the pName pointer to point at the token (pName1 or
66957  ** pName2) that stores the unqualified table name. The variable iDb is
66958  ** set to the index of the database that the table or view is to be
66959  ** created in.
66960  */
66961  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
66962  if( iDb<0 ) return;
66963  if( !OMIT_TEMPDB && isTemp && iDb>1 ){
66964    /* If creating a temp table, the name may not be qualified */
66965    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
66966    return;
66967  }
66968  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
66969
66970  pParse->sNameToken = *pName;
66971  zName = sqlite3NameFromToken(db, pName);
66972  if( zName==0 ) return;
66973  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
66974    goto begin_table_error;
66975  }
66976  if( db->init.iDb==1 ) isTemp = 1;
66977#ifndef SQLITE_OMIT_AUTHORIZATION
66978  assert( (isTemp & 1)==isTemp );
66979  {
66980    int code;
66981    char *zDb = db->aDb[iDb].zName;
66982    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
66983      goto begin_table_error;
66984    }
66985    if( isView ){
66986      if( !OMIT_TEMPDB && isTemp ){
66987        code = SQLITE_CREATE_TEMP_VIEW;
66988      }else{
66989        code = SQLITE_CREATE_VIEW;
66990      }
66991    }else{
66992      if( !OMIT_TEMPDB && isTemp ){
66993        code = SQLITE_CREATE_TEMP_TABLE;
66994      }else{
66995        code = SQLITE_CREATE_TABLE;
66996      }
66997    }
66998    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
66999      goto begin_table_error;
67000    }
67001  }
67002#endif
67003
67004  /* Make sure the new table name does not collide with an existing
67005  ** index or table name in the same database.  Issue an error message if
67006  ** it does. The exception is if the statement being parsed was passed
67007  ** to an sqlite3_declare_vtab() call. In that case only the column names
67008  ** and types will be used, so there is no need to test for namespace
67009  ** collisions.
67010  */
67011  if( !IN_DECLARE_VTAB ){
67012    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
67013      goto begin_table_error;
67014    }
67015    pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
67016    if( pTable ){
67017      if( !noErr ){
67018        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
67019      }
67020      goto begin_table_error;
67021    }
67022    if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
67023      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
67024      goto begin_table_error;
67025    }
67026  }
67027
67028  pTable = sqlite3DbMallocZero(db, sizeof(Table));
67029  if( pTable==0 ){
67030    db->mallocFailed = 1;
67031    pParse->rc = SQLITE_NOMEM;
67032    pParse->nErr++;
67033    goto begin_table_error;
67034  }
67035  pTable->zName = zName;
67036  pTable->iPKey = -1;
67037  pTable->pSchema = db->aDb[iDb].pSchema;
67038  pTable->nRef = 1;
67039  pTable->dbMem = 0;
67040  assert( pParse->pNewTable==0 );
67041  pParse->pNewTable = pTable;
67042
67043  /* If this is the magic sqlite_sequence table used by autoincrement,
67044  ** then record a pointer to this table in the main database structure
67045  ** so that INSERT can find the table easily.
67046  */
67047#ifndef SQLITE_OMIT_AUTOINCREMENT
67048  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
67049    pTable->pSchema->pSeqTab = pTable;
67050  }
67051#endif
67052
67053  /* Begin generating the code that will insert the table record into
67054  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
67055  ** and allocate the record number for the table entry now.  Before any
67056  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
67057  ** indices to be created and the table record must come before the
67058  ** indices.  Hence, the record number for the table must be allocated
67059  ** now.
67060  */
67061  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
67062    int j1;
67063    int fileFormat;
67064    int reg1, reg2, reg3;
67065    sqlite3BeginWriteOperation(pParse, 0, iDb);
67066
67067#ifndef SQLITE_OMIT_VIRTUALTABLE
67068    if( isVirtual ){
67069      sqlite3VdbeAddOp0(v, OP_VBegin);
67070    }
67071#endif
67072
67073    /* If the file format and encoding in the database have not been set,
67074    ** set them now.
67075    */
67076    reg1 = pParse->regRowid = ++pParse->nMem;
67077    reg2 = pParse->regRoot = ++pParse->nMem;
67078    reg3 = ++pParse->nMem;
67079    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
67080    sqlite3VdbeUsesBtree(v, iDb);
67081    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
67082    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
67083                  1 : SQLITE_MAX_FILE_FORMAT;
67084    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
67085    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
67086    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
67087    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
67088    sqlite3VdbeJumpHere(v, j1);
67089
67090    /* This just creates a place-holder record in the sqlite_master table.
67091    ** The record created does not contain anything yet.  It will be replaced
67092    ** by the real entry in code generated at sqlite3EndTable().
67093    **
67094    ** The rowid for the new entry is left in register pParse->regRowid.
67095    ** The root page number of the new table is left in reg pParse->regRoot.
67096    ** The rowid and root page number values are needed by the code that
67097    ** sqlite3EndTable will generate.
67098    */
67099#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
67100    if( isView || isVirtual ){
67101      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
67102    }else
67103#endif
67104    {
67105      sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
67106    }
67107    sqlite3OpenMasterTable(pParse, iDb);
67108    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
67109    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
67110    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
67111    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
67112    sqlite3VdbeAddOp0(v, OP_Close);
67113  }
67114
67115  /* Normal (non-error) return. */
67116  return;
67117
67118  /* If an error occurs, we jump here */
67119begin_table_error:
67120  sqlite3DbFree(db, zName);
67121  return;
67122}
67123
67124/*
67125** This macro is used to compare two strings in a case-insensitive manner.
67126** It is slightly faster than calling sqlite3StrICmp() directly, but
67127** produces larger code.
67128**
67129** WARNING: This macro is not compatible with the strcmp() family. It
67130** returns true if the two strings are equal, otherwise false.
67131*/
67132#define STRICMP(x, y) (\
67133sqlite3UpperToLower[*(unsigned char *)(x)]==   \
67134sqlite3UpperToLower[*(unsigned char *)(y)]     \
67135&& sqlite3StrICmp((x)+1,(y)+1)==0 )
67136
67137/*
67138** Add a new column to the table currently being constructed.
67139**
67140** The parser calls this routine once for each column declaration
67141** in a CREATE TABLE statement.  sqlite3StartTable() gets called
67142** first to get things going.  Then this routine is called for each
67143** column.
67144*/
67145SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
67146  Table *p;
67147  int i;
67148  char *z;
67149  Column *pCol;
67150  sqlite3 *db = pParse->db;
67151  if( (p = pParse->pNewTable)==0 ) return;
67152#if SQLITE_MAX_COLUMN
67153  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
67154    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
67155    return;
67156  }
67157#endif
67158  z = sqlite3NameFromToken(db, pName);
67159  if( z==0 ) return;
67160  for(i=0; i<p->nCol; i++){
67161    if( STRICMP(z, p->aCol[i].zName) ){
67162      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
67163      sqlite3DbFree(db, z);
67164      return;
67165    }
67166  }
67167  if( (p->nCol & 0x7)==0 ){
67168    Column *aNew;
67169    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
67170    if( aNew==0 ){
67171      sqlite3DbFree(db, z);
67172      return;
67173    }
67174    p->aCol = aNew;
67175  }
67176  pCol = &p->aCol[p->nCol];
67177  memset(pCol, 0, sizeof(p->aCol[0]));
67178  pCol->zName = z;
67179
67180  /* If there is no type specified, columns have the default affinity
67181  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
67182  ** be called next to set pCol->affinity correctly.
67183  */
67184  pCol->affinity = SQLITE_AFF_NONE;
67185  p->nCol++;
67186}
67187
67188/*
67189** This routine is called by the parser while in the middle of
67190** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
67191** been seen on a column.  This routine sets the notNull flag on
67192** the column currently under construction.
67193*/
67194SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
67195  Table *p;
67196  p = pParse->pNewTable;
67197  if( p==0 || NEVER(p->nCol<1) ) return;
67198  p->aCol[p->nCol-1].notNull = (u8)onError;
67199}
67200
67201/*
67202** Scan the column type name zType (length nType) and return the
67203** associated affinity type.
67204**
67205** This routine does a case-independent search of zType for the
67206** substrings in the following table. If one of the substrings is
67207** found, the corresponding affinity is returned. If zType contains
67208** more than one of the substrings, entries toward the top of
67209** the table take priority. For example, if zType is 'BLOBINT',
67210** SQLITE_AFF_INTEGER is returned.
67211**
67212** Substring     | Affinity
67213** --------------------------------
67214** 'INT'         | SQLITE_AFF_INTEGER
67215** 'CHAR'        | SQLITE_AFF_TEXT
67216** 'CLOB'        | SQLITE_AFF_TEXT
67217** 'TEXT'        | SQLITE_AFF_TEXT
67218** 'BLOB'        | SQLITE_AFF_NONE
67219** 'REAL'        | SQLITE_AFF_REAL
67220** 'FLOA'        | SQLITE_AFF_REAL
67221** 'DOUB'        | SQLITE_AFF_REAL
67222**
67223** If none of the substrings in the above table are found,
67224** SQLITE_AFF_NUMERIC is returned.
67225*/
67226SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
67227  u32 h = 0;
67228  char aff = SQLITE_AFF_NUMERIC;
67229
67230  if( zIn ) while( zIn[0] ){
67231    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
67232    zIn++;
67233    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
67234      aff = SQLITE_AFF_TEXT;
67235    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
67236      aff = SQLITE_AFF_TEXT;
67237    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
67238      aff = SQLITE_AFF_TEXT;
67239    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
67240        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
67241      aff = SQLITE_AFF_NONE;
67242#ifndef SQLITE_OMIT_FLOATING_POINT
67243    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
67244        && aff==SQLITE_AFF_NUMERIC ){
67245      aff = SQLITE_AFF_REAL;
67246    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
67247        && aff==SQLITE_AFF_NUMERIC ){
67248      aff = SQLITE_AFF_REAL;
67249    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
67250        && aff==SQLITE_AFF_NUMERIC ){
67251      aff = SQLITE_AFF_REAL;
67252#endif
67253    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
67254      aff = SQLITE_AFF_INTEGER;
67255      break;
67256    }
67257  }
67258
67259  return aff;
67260}
67261
67262/*
67263** This routine is called by the parser while in the middle of
67264** parsing a CREATE TABLE statement.  The pFirst token is the first
67265** token in the sequence of tokens that describe the type of the
67266** column currently under construction.   pLast is the last token
67267** in the sequence.  Use this information to construct a string
67268** that contains the typename of the column and store that string
67269** in zType.
67270*/
67271SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
67272  Table *p;
67273  Column *pCol;
67274
67275  p = pParse->pNewTable;
67276  if( p==0 || NEVER(p->nCol<1) ) return;
67277  pCol = &p->aCol[p->nCol-1];
67278  assert( pCol->zType==0 );
67279  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
67280  pCol->affinity = sqlite3AffinityType(pCol->zType);
67281}
67282
67283/*
67284** The expression is the default value for the most recently added column
67285** of the table currently under construction.
67286**
67287** Default value expressions must be constant.  Raise an exception if this
67288** is not the case.
67289**
67290** This routine is called by the parser while in the middle of
67291** parsing a CREATE TABLE statement.
67292*/
67293SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
67294  Table *p;
67295  Column *pCol;
67296  sqlite3 *db = pParse->db;
67297  p = pParse->pNewTable;
67298  if( p!=0 ){
67299    pCol = &(p->aCol[p->nCol-1]);
67300    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
67301      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
67302          pCol->zName);
67303    }else{
67304      /* A copy of pExpr is used instead of the original, as pExpr contains
67305      ** tokens that point to volatile memory. The 'span' of the expression
67306      ** is required by pragma table_info.
67307      */
67308      sqlite3ExprDelete(db, pCol->pDflt);
67309      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
67310      sqlite3DbFree(db, pCol->zDflt);
67311      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
67312                                     (int)(pSpan->zEnd - pSpan->zStart));
67313    }
67314  }
67315  sqlite3ExprDelete(db, pSpan->pExpr);
67316}
67317
67318/*
67319** Designate the PRIMARY KEY for the table.  pList is a list of names
67320** of columns that form the primary key.  If pList is NULL, then the
67321** most recently added column of the table is the primary key.
67322**
67323** A table can have at most one primary key.  If the table already has
67324** a primary key (and this is the second primary key) then create an
67325** error.
67326**
67327** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
67328** then we will try to use that column as the rowid.  Set the Table.iPKey
67329** field of the table under construction to be the index of the
67330** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
67331** no INTEGER PRIMARY KEY.
67332**
67333** If the key is not an INTEGER PRIMARY KEY, then create a unique
67334** index for the key.  No index is created for INTEGER PRIMARY KEYs.
67335*/
67336SQLITE_PRIVATE void sqlite3AddPrimaryKey(
67337  Parse *pParse,    /* Parsing context */
67338  ExprList *pList,  /* List of field names to be indexed */
67339  int onError,      /* What to do with a uniqueness conflict */
67340  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
67341  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
67342){
67343  Table *pTab = pParse->pNewTable;
67344  char *zType = 0;
67345  int iCol = -1, i;
67346  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
67347  if( pTab->tabFlags & TF_HasPrimaryKey ){
67348    sqlite3ErrorMsg(pParse,
67349      "table \"%s\" has more than one primary key", pTab->zName);
67350    goto primary_key_exit;
67351  }
67352  pTab->tabFlags |= TF_HasPrimaryKey;
67353  if( pList==0 ){
67354    iCol = pTab->nCol - 1;
67355    pTab->aCol[iCol].isPrimKey = 1;
67356  }else{
67357    for(i=0; i<pList->nExpr; i++){
67358      for(iCol=0; iCol<pTab->nCol; iCol++){
67359        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
67360          break;
67361        }
67362      }
67363      if( iCol<pTab->nCol ){
67364        pTab->aCol[iCol].isPrimKey = 1;
67365      }
67366    }
67367    if( pList->nExpr>1 ) iCol = -1;
67368  }
67369  if( iCol>=0 && iCol<pTab->nCol ){
67370    zType = pTab->aCol[iCol].zType;
67371  }
67372  if( zType && sqlite3StrICmp(zType, "INTEGER")==0
67373        && sortOrder==SQLITE_SO_ASC ){
67374    pTab->iPKey = iCol;
67375    pTab->keyConf = (u8)onError;
67376    assert( autoInc==0 || autoInc==1 );
67377    pTab->tabFlags |= autoInc*TF_Autoincrement;
67378  }else if( autoInc ){
67379#ifndef SQLITE_OMIT_AUTOINCREMENT
67380    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
67381       "INTEGER PRIMARY KEY");
67382#endif
67383  }else{
67384    Index *p;
67385    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
67386    if( p ){
67387      p->autoIndex = 2;
67388    }
67389    pList = 0;
67390  }
67391
67392primary_key_exit:
67393  sqlite3ExprListDelete(pParse->db, pList);
67394  return;
67395}
67396
67397/*
67398** Add a new CHECK constraint to the table currently under construction.
67399*/
67400SQLITE_PRIVATE void sqlite3AddCheckConstraint(
67401  Parse *pParse,    /* Parsing context */
67402  Expr *pCheckExpr  /* The check expression */
67403){
67404  sqlite3 *db = pParse->db;
67405#ifndef SQLITE_OMIT_CHECK
67406  Table *pTab = pParse->pNewTable;
67407  if( pTab && !IN_DECLARE_VTAB ){
67408    pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
67409  }else
67410#endif
67411  {
67412    sqlite3ExprDelete(db, pCheckExpr);
67413  }
67414}
67415
67416/*
67417** Set the collation function of the most recently parsed table column
67418** to the CollSeq given.
67419*/
67420SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
67421  Table *p;
67422  int i;
67423  char *zColl;              /* Dequoted name of collation sequence */
67424  sqlite3 *db;
67425
67426  if( (p = pParse->pNewTable)==0 ) return;
67427  i = p->nCol-1;
67428  db = pParse->db;
67429  zColl = sqlite3NameFromToken(db, pToken);
67430  if( !zColl ) return;
67431
67432  if( sqlite3LocateCollSeq(pParse, zColl) ){
67433    Index *pIdx;
67434    p->aCol[i].zColl = zColl;
67435
67436    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
67437    ** then an index may have been created on this column before the
67438    ** collation type was added. Correct this if it is the case.
67439    */
67440    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
67441      assert( pIdx->nColumn==1 );
67442      if( pIdx->aiColumn[0]==i ){
67443        pIdx->azColl[0] = p->aCol[i].zColl;
67444      }
67445    }
67446  }else{
67447    sqlite3DbFree(db, zColl);
67448  }
67449}
67450
67451/*
67452** This function returns the collation sequence for database native text
67453** encoding identified by the string zName, length nName.
67454**
67455** If the requested collation sequence is not available, or not available
67456** in the database native encoding, the collation factory is invoked to
67457** request it. If the collation factory does not supply such a sequence,
67458** and the sequence is available in another text encoding, then that is
67459** returned instead.
67460**
67461** If no versions of the requested collations sequence are available, or
67462** another error occurs, NULL is returned and an error message written into
67463** pParse.
67464**
67465** This routine is a wrapper around sqlite3FindCollSeq().  This routine
67466** invokes the collation factory if the named collation cannot be found
67467** and generates an error message.
67468**
67469** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
67470*/
67471SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
67472  sqlite3 *db = pParse->db;
67473  u8 enc = ENC(db);
67474  u8 initbusy = db->init.busy;
67475  CollSeq *pColl;
67476
67477  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
67478  if( !initbusy && (!pColl || !pColl->xCmp) ){
67479    pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
67480    if( !pColl ){
67481      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
67482    }
67483  }
67484
67485  return pColl;
67486}
67487
67488
67489/*
67490** Generate code that will increment the schema cookie.
67491**
67492** The schema cookie is used to determine when the schema for the
67493** database changes.  After each schema change, the cookie value
67494** changes.  When a process first reads the schema it records the
67495** cookie.  Thereafter, whenever it goes to access the database,
67496** it checks the cookie to make sure the schema has not changed
67497** since it was last read.
67498**
67499** This plan is not completely bullet-proof.  It is possible for
67500** the schema to change multiple times and for the cookie to be
67501** set back to prior value.  But schema changes are infrequent
67502** and the probability of hitting the same cookie value is only
67503** 1 chance in 2^32.  So we're safe enough.
67504*/
67505SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
67506  int r1 = sqlite3GetTempReg(pParse);
67507  sqlite3 *db = pParse->db;
67508  Vdbe *v = pParse->pVdbe;
67509  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
67510  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
67511  sqlite3ReleaseTempReg(pParse, r1);
67512}
67513
67514/*
67515** Measure the number of characters needed to output the given
67516** identifier.  The number returned includes any quotes used
67517** but does not include the null terminator.
67518**
67519** The estimate is conservative.  It might be larger that what is
67520** really needed.
67521*/
67522static int identLength(const char *z){
67523  int n;
67524  for(n=0; *z; n++, z++){
67525    if( *z=='"' ){ n++; }
67526  }
67527  return n + 2;
67528}
67529
67530/*
67531** The first parameter is a pointer to an output buffer. The second
67532** parameter is a pointer to an integer that contains the offset at
67533** which to write into the output buffer. This function copies the
67534** nul-terminated string pointed to by the third parameter, zSignedIdent,
67535** to the specified offset in the buffer and updates *pIdx to refer
67536** to the first byte after the last byte written before returning.
67537**
67538** If the string zSignedIdent consists entirely of alpha-numeric
67539** characters, does not begin with a digit and is not an SQL keyword,
67540** then it is copied to the output buffer exactly as it is. Otherwise,
67541** it is quoted using double-quotes.
67542*/
67543static void identPut(char *z, int *pIdx, char *zSignedIdent){
67544  unsigned char *zIdent = (unsigned char*)zSignedIdent;
67545  int i, j, needQuote;
67546  i = *pIdx;
67547
67548  for(j=0; zIdent[j]; j++){
67549    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
67550  }
67551  needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
67552  if( !needQuote ){
67553    needQuote = zIdent[j];
67554  }
67555
67556  if( needQuote ) z[i++] = '"';
67557  for(j=0; zIdent[j]; j++){
67558    z[i++] = zIdent[j];
67559    if( zIdent[j]=='"' ) z[i++] = '"';
67560  }
67561  if( needQuote ) z[i++] = '"';
67562  z[i] = 0;
67563  *pIdx = i;
67564}
67565
67566/*
67567** Generate a CREATE TABLE statement appropriate for the given
67568** table.  Memory to hold the text of the statement is obtained
67569** from sqliteMalloc() and must be freed by the calling function.
67570*/
67571static char *createTableStmt(sqlite3 *db, Table *p){
67572  int i, k, n;
67573  char *zStmt;
67574  char *zSep, *zSep2, *zEnd;
67575  Column *pCol;
67576  n = 0;
67577  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
67578    n += identLength(pCol->zName) + 5;
67579  }
67580  n += identLength(p->zName);
67581  if( n<50 ){
67582    zSep = "";
67583    zSep2 = ",";
67584    zEnd = ")";
67585  }else{
67586    zSep = "\n  ";
67587    zSep2 = ",\n  ";
67588    zEnd = "\n)";
67589  }
67590  n += 35 + 6*p->nCol;
67591  zStmt = sqlite3Malloc( n );
67592  if( zStmt==0 ){
67593    db->mallocFailed = 1;
67594    return 0;
67595  }
67596  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
67597  k = sqlite3Strlen30(zStmt);
67598  identPut(zStmt, &k, p->zName);
67599  zStmt[k++] = '(';
67600  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
67601    static const char * const azType[] = {
67602        /* SQLITE_AFF_TEXT    */ " TEXT",
67603        /* SQLITE_AFF_NONE    */ "",
67604        /* SQLITE_AFF_NUMERIC */ " NUM",
67605        /* SQLITE_AFF_INTEGER */ " INT",
67606        /* SQLITE_AFF_REAL    */ " REAL"
67607    };
67608    int len;
67609    const char *zType;
67610
67611    sqlite3_snprintf(n-k, &zStmt[k], zSep);
67612    k += sqlite3Strlen30(&zStmt[k]);
67613    zSep = zSep2;
67614    identPut(zStmt, &k, pCol->zName);
67615    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
67616    assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
67617    testcase( pCol->affinity==SQLITE_AFF_TEXT );
67618    testcase( pCol->affinity==SQLITE_AFF_NONE );
67619    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
67620    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
67621    testcase( pCol->affinity==SQLITE_AFF_REAL );
67622
67623    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
67624    len = sqlite3Strlen30(zType);
67625    assert( pCol->affinity==SQLITE_AFF_NONE
67626            || pCol->affinity==sqlite3AffinityType(zType) );
67627    memcpy(&zStmt[k], zType, len);
67628    k += len;
67629    assert( k<=n );
67630  }
67631  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
67632  return zStmt;
67633}
67634
67635/*
67636** This routine is called to report the final ")" that terminates
67637** a CREATE TABLE statement.
67638**
67639** The table structure that other action routines have been building
67640** is added to the internal hash tables, assuming no errors have
67641** occurred.
67642**
67643** An entry for the table is made in the master table on disk, unless
67644** this is a temporary table or db->init.busy==1.  When db->init.busy==1
67645** it means we are reading the sqlite_master table because we just
67646** connected to the database or because the sqlite_master table has
67647** recently changed, so the entry for this table already exists in
67648** the sqlite_master table.  We do not want to create it again.
67649**
67650** If the pSelect argument is not NULL, it means that this routine
67651** was called to create a table generated from a
67652** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
67653** the new table will match the result set of the SELECT.
67654*/
67655SQLITE_PRIVATE void sqlite3EndTable(
67656  Parse *pParse,          /* Parse context */
67657  Token *pCons,           /* The ',' token after the last column defn. */
67658  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
67659  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
67660){
67661  Table *p;
67662  sqlite3 *db = pParse->db;
67663  int iDb;
67664
67665  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
67666    return;
67667  }
67668  p = pParse->pNewTable;
67669  if( p==0 ) return;
67670
67671  assert( !db->init.busy || !pSelect );
67672
67673  iDb = sqlite3SchemaToIndex(db, p->pSchema);
67674
67675#ifndef SQLITE_OMIT_CHECK
67676  /* Resolve names in all CHECK constraint expressions.
67677  */
67678  if( p->pCheck ){
67679    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
67680    NameContext sNC;                /* Name context for pParse->pNewTable */
67681
67682    memset(&sNC, 0, sizeof(sNC));
67683    memset(&sSrc, 0, sizeof(sSrc));
67684    sSrc.nSrc = 1;
67685    sSrc.a[0].zName = p->zName;
67686    sSrc.a[0].pTab = p;
67687    sSrc.a[0].iCursor = -1;
67688    sNC.pParse = pParse;
67689    sNC.pSrcList = &sSrc;
67690    sNC.isCheck = 1;
67691    if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
67692      return;
67693    }
67694  }
67695#endif /* !defined(SQLITE_OMIT_CHECK) */
67696
67697  /* If the db->init.busy is 1 it means we are reading the SQL off the
67698  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
67699  ** So do not write to the disk again.  Extract the root page number
67700  ** for the table from the db->init.newTnum field.  (The page number
67701  ** should have been put there by the sqliteOpenCb routine.)
67702  */
67703  if( db->init.busy ){
67704    p->tnum = db->init.newTnum;
67705  }
67706
67707  /* If not initializing, then create a record for the new table
67708  ** in the SQLITE_MASTER table of the database.
67709  **
67710  ** If this is a TEMPORARY table, write the entry into the auxiliary
67711  ** file instead of into the main database file.
67712  */
67713  if( !db->init.busy ){
67714    int n;
67715    Vdbe *v;
67716    char *zType;    /* "view" or "table" */
67717    char *zType2;   /* "VIEW" or "TABLE" */
67718    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
67719
67720    v = sqlite3GetVdbe(pParse);
67721    if( NEVER(v==0) ) return;
67722
67723    sqlite3VdbeAddOp1(v, OP_Close, 0);
67724
67725    /*
67726    ** Initialize zType for the new view or table.
67727    */
67728    if( p->pSelect==0 ){
67729      /* A regular table */
67730      zType = "table";
67731      zType2 = "TABLE";
67732#ifndef SQLITE_OMIT_VIEW
67733    }else{
67734      /* A view */
67735      zType = "view";
67736      zType2 = "VIEW";
67737#endif
67738    }
67739
67740    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
67741    ** statement to populate the new table. The root-page number for the
67742    ** new table is in register pParse->regRoot.
67743    **
67744    ** Once the SELECT has been coded by sqlite3Select(), it is in a
67745    ** suitable state to query for the column names and types to be used
67746    ** by the new table.
67747    **
67748    ** A shared-cache write-lock is not required to write to the new table,
67749    ** as a schema-lock must have already been obtained to create it. Since
67750    ** a schema-lock excludes all other database users, the write-lock would
67751    ** be redundant.
67752    */
67753    if( pSelect ){
67754      SelectDest dest;
67755      Table *pSelTab;
67756
67757      assert(pParse->nTab==1);
67758      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
67759      sqlite3VdbeChangeP5(v, 1);
67760      pParse->nTab = 2;
67761      sqlite3SelectDestInit(&dest, SRT_Table, 1);
67762      sqlite3Select(pParse, pSelect, &dest);
67763      sqlite3VdbeAddOp1(v, OP_Close, 1);
67764      if( pParse->nErr==0 ){
67765        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
67766        if( pSelTab==0 ) return;
67767        assert( p->aCol==0 );
67768        p->nCol = pSelTab->nCol;
67769        p->aCol = pSelTab->aCol;
67770        pSelTab->nCol = 0;
67771        pSelTab->aCol = 0;
67772        sqlite3DeleteTable(pSelTab);
67773      }
67774    }
67775
67776    /* Compute the complete text of the CREATE statement */
67777    if( pSelect ){
67778      zStmt = createTableStmt(db, p);
67779    }else{
67780      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
67781      zStmt = sqlite3MPrintf(db,
67782          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
67783      );
67784    }
67785
67786    /* A slot for the record has already been allocated in the
67787    ** SQLITE_MASTER table.  We just need to update that slot with all
67788    ** the information we've collected.
67789    */
67790    sqlite3NestedParse(pParse,
67791      "UPDATE %Q.%s "
67792         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
67793       "WHERE rowid=#%d",
67794      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
67795      zType,
67796      p->zName,
67797      p->zName,
67798      pParse->regRoot,
67799      zStmt,
67800      pParse->regRowid
67801    );
67802    sqlite3DbFree(db, zStmt);
67803    sqlite3ChangeCookie(pParse, iDb);
67804
67805#ifndef SQLITE_OMIT_AUTOINCREMENT
67806    /* Check to see if we need to create an sqlite_sequence table for
67807    ** keeping track of autoincrement keys.
67808    */
67809    if( p->tabFlags & TF_Autoincrement ){
67810      Db *pDb = &db->aDb[iDb];
67811      if( pDb->pSchema->pSeqTab==0 ){
67812        sqlite3NestedParse(pParse,
67813          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
67814          pDb->zName
67815        );
67816      }
67817    }
67818#endif
67819
67820    /* Reparse everything to update our internal data structures */
67821    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
67822        sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
67823  }
67824
67825
67826  /* Add the table to the in-memory representation of the database.
67827  */
67828  if( db->init.busy ){
67829    Table *pOld;
67830    Schema *pSchema = p->pSchema;
67831    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
67832                             sqlite3Strlen30(p->zName),p);
67833    if( pOld ){
67834      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
67835      db->mallocFailed = 1;
67836      return;
67837    }
67838    pParse->pNewTable = 0;
67839    db->nTable++;
67840    db->flags |= SQLITE_InternChanges;
67841
67842#ifndef SQLITE_OMIT_ALTERTABLE
67843    if( !p->pSelect ){
67844      const char *zName = (const char *)pParse->sNameToken.z;
67845      int nName;
67846      assert( !pSelect && pCons && pEnd );
67847      if( pCons->z==0 ){
67848        pCons = pEnd;
67849      }
67850      nName = (int)((const char *)pCons->z - zName);
67851      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
67852    }
67853#endif
67854  }
67855}
67856
67857#ifndef SQLITE_OMIT_VIEW
67858/*
67859** The parser calls this routine in order to create a new VIEW
67860*/
67861SQLITE_PRIVATE void sqlite3CreateView(
67862  Parse *pParse,     /* The parsing context */
67863  Token *pBegin,     /* The CREATE token that begins the statement */
67864  Token *pName1,     /* The token that holds the name of the view */
67865  Token *pName2,     /* The token that holds the name of the view */
67866  Select *pSelect,   /* A SELECT statement that will become the new view */
67867  int isTemp,        /* TRUE for a TEMPORARY view */
67868  int noErr          /* Suppress error messages if VIEW already exists */
67869){
67870  Table *p;
67871  int n;
67872  const char *z;
67873  Token sEnd;
67874  DbFixer sFix;
67875  Token *pName;
67876  int iDb;
67877  sqlite3 *db = pParse->db;
67878
67879  if( pParse->nVar>0 ){
67880    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
67881    sqlite3SelectDelete(db, pSelect);
67882    return;
67883  }
67884  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
67885  p = pParse->pNewTable;
67886  if( p==0 ){
67887    sqlite3SelectDelete(db, pSelect);
67888    return;
67889  }
67890  assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
67891                             ** there could not have been an error */
67892  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
67893  iDb = sqlite3SchemaToIndex(db, p->pSchema);
67894  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
67895    && sqlite3FixSelect(&sFix, pSelect)
67896  ){
67897    sqlite3SelectDelete(db, pSelect);
67898    return;
67899  }
67900
67901  /* Make a copy of the entire SELECT statement that defines the view.
67902  ** This will force all the Expr.token.z values to be dynamically
67903  ** allocated rather than point to the input string - which means that
67904  ** they will persist after the current sqlite3_exec() call returns.
67905  */
67906  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
67907  sqlite3SelectDelete(db, pSelect);
67908  if( db->mallocFailed ){
67909    return;
67910  }
67911  if( !db->init.busy ){
67912    sqlite3ViewGetColumnNames(pParse, p);
67913  }
67914
67915  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
67916  ** the end.
67917  */
67918  sEnd = pParse->sLastToken;
67919  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
67920    sEnd.z += sEnd.n;
67921  }
67922  sEnd.n = 0;
67923  n = (int)(sEnd.z - pBegin->z);
67924  z = pBegin->z;
67925  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
67926  sEnd.z = &z[n-1];
67927  sEnd.n = 1;
67928
67929  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
67930  sqlite3EndTable(pParse, 0, &sEnd, 0);
67931  return;
67932}
67933#endif /* SQLITE_OMIT_VIEW */
67934
67935#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
67936/*
67937** The Table structure pTable is really a VIEW.  Fill in the names of
67938** the columns of the view in the pTable structure.  Return the number
67939** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
67940*/
67941SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
67942  Table *pSelTab;   /* A fake table from which we get the result set */
67943  Select *pSel;     /* Copy of the SELECT that implements the view */
67944  int nErr = 0;     /* Number of errors encountered */
67945  int n;            /* Temporarily holds the number of cursors assigned */
67946  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
67947  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
67948
67949  assert( pTable );
67950
67951#ifndef SQLITE_OMIT_VIRTUALTABLE
67952  if( sqlite3VtabCallConnect(pParse, pTable) ){
67953    return SQLITE_ERROR;
67954  }
67955  if( IsVirtual(pTable) ) return 0;
67956#endif
67957
67958#ifndef SQLITE_OMIT_VIEW
67959  /* A positive nCol means the columns names for this view are
67960  ** already known.
67961  */
67962  if( pTable->nCol>0 ) return 0;
67963
67964  /* A negative nCol is a special marker meaning that we are currently
67965  ** trying to compute the column names.  If we enter this routine with
67966  ** a negative nCol, it means two or more views form a loop, like this:
67967  **
67968  **     CREATE VIEW one AS SELECT * FROM two;
67969  **     CREATE VIEW two AS SELECT * FROM one;
67970  **
67971  ** Actually, the error above is now caught prior to reaching this point.
67972  ** But the following test is still important as it does come up
67973  ** in the following:
67974  **
67975  **     CREATE TABLE main.ex1(a);
67976  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
67977  **     SELECT * FROM temp.ex1;
67978  */
67979  if( pTable->nCol<0 ){
67980    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
67981    return 1;
67982  }
67983  assert( pTable->nCol>=0 );
67984
67985  /* If we get this far, it means we need to compute the table names.
67986  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
67987  ** "*" elements in the results set of the view and will assign cursors
67988  ** to the elements of the FROM clause.  But we do not want these changes
67989  ** to be permanent.  So the computation is done on a copy of the SELECT
67990  ** statement that defines the view.
67991  */
67992  assert( pTable->pSelect );
67993  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
67994  if( pSel ){
67995    u8 enableLookaside = db->lookaside.bEnabled;
67996    n = pParse->nTab;
67997    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
67998    pTable->nCol = -1;
67999    db->lookaside.bEnabled = 0;
68000#ifndef SQLITE_OMIT_AUTHORIZATION
68001    xAuth = db->xAuth;
68002    db->xAuth = 0;
68003    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
68004    db->xAuth = xAuth;
68005#else
68006    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
68007#endif
68008    db->lookaside.bEnabled = enableLookaside;
68009    pParse->nTab = n;
68010    if( pSelTab ){
68011      assert( pTable->aCol==0 );
68012      pTable->nCol = pSelTab->nCol;
68013      pTable->aCol = pSelTab->aCol;
68014      pSelTab->nCol = 0;
68015      pSelTab->aCol = 0;
68016      sqlite3DeleteTable(pSelTab);
68017      pTable->pSchema->flags |= DB_UnresetViews;
68018    }else{
68019      pTable->nCol = 0;
68020      nErr++;
68021    }
68022    sqlite3SelectDelete(db, pSel);
68023  } else {
68024    nErr++;
68025  }
68026#endif /* SQLITE_OMIT_VIEW */
68027  return nErr;
68028}
68029#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
68030
68031#ifndef SQLITE_OMIT_VIEW
68032/*
68033** Clear the column names from every VIEW in database idx.
68034*/
68035static void sqliteViewResetAll(sqlite3 *db, int idx){
68036  HashElem *i;
68037  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
68038  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
68039    Table *pTab = sqliteHashData(i);
68040    if( pTab->pSelect ){
68041      sqliteResetColumnNames(pTab);
68042    }
68043  }
68044  DbClearProperty(db, idx, DB_UnresetViews);
68045}
68046#else
68047# define sqliteViewResetAll(A,B)
68048#endif /* SQLITE_OMIT_VIEW */
68049
68050/*
68051** This function is called by the VDBE to adjust the internal schema
68052** used by SQLite when the btree layer moves a table root page. The
68053** root-page of a table or index in database iDb has changed from iFrom
68054** to iTo.
68055**
68056** Ticket #1728:  The symbol table might still contain information
68057** on tables and/or indices that are the process of being deleted.
68058** If you are unlucky, one of those deleted indices or tables might
68059** have the same rootpage number as the real table or index that is
68060** being moved.  So we cannot stop searching after the first match
68061** because the first match might be for one of the deleted indices
68062** or tables and not the table/index that is actually being moved.
68063** We must continue looping until all tables and indices with
68064** rootpage==iFrom have been converted to have a rootpage of iTo
68065** in order to be certain that we got the right one.
68066*/
68067#ifndef SQLITE_OMIT_AUTOVACUUM
68068SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
68069  HashElem *pElem;
68070  Hash *pHash;
68071
68072  pHash = &pDb->pSchema->tblHash;
68073  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
68074    Table *pTab = sqliteHashData(pElem);
68075    if( pTab->tnum==iFrom ){
68076      pTab->tnum = iTo;
68077    }
68078  }
68079  pHash = &pDb->pSchema->idxHash;
68080  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
68081    Index *pIdx = sqliteHashData(pElem);
68082    if( pIdx->tnum==iFrom ){
68083      pIdx->tnum = iTo;
68084    }
68085  }
68086}
68087#endif
68088
68089/*
68090** Write code to erase the table with root-page iTable from database iDb.
68091** Also write code to modify the sqlite_master table and internal schema
68092** if a root-page of another table is moved by the btree-layer whilst
68093** erasing iTable (this can happen with an auto-vacuum database).
68094*/
68095static void destroyRootPage(Parse *pParse, int iTable, int iDb){
68096  Vdbe *v = sqlite3GetVdbe(pParse);
68097  int r1 = sqlite3GetTempReg(pParse);
68098  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
68099  sqlite3MayAbort(pParse);
68100#ifndef SQLITE_OMIT_AUTOVACUUM
68101  /* OP_Destroy stores an in integer r1. If this integer
68102  ** is non-zero, then it is the root page number of a table moved to
68103  ** location iTable. The following code modifies the sqlite_master table to
68104  ** reflect this.
68105  **
68106  ** The "#NNN" in the SQL is a special constant that means whatever value
68107  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
68108  ** token for additional information.
68109  */
68110  sqlite3NestedParse(pParse,
68111     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
68112     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
68113#endif
68114  sqlite3ReleaseTempReg(pParse, r1);
68115}
68116
68117/*
68118** Write VDBE code to erase table pTab and all associated indices on disk.
68119** Code to update the sqlite_master tables and internal schema definitions
68120** in case a root-page belonging to another table is moved by the btree layer
68121** is also added (this can happen with an auto-vacuum database).
68122*/
68123static void destroyTable(Parse *pParse, Table *pTab){
68124#ifdef SQLITE_OMIT_AUTOVACUUM
68125  Index *pIdx;
68126  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
68127  destroyRootPage(pParse, pTab->tnum, iDb);
68128  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68129    destroyRootPage(pParse, pIdx->tnum, iDb);
68130  }
68131#else
68132  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
68133  ** is not defined), then it is important to call OP_Destroy on the
68134  ** table and index root-pages in order, starting with the numerically
68135  ** largest root-page number. This guarantees that none of the root-pages
68136  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
68137  ** following were coded:
68138  **
68139  ** OP_Destroy 4 0
68140  ** ...
68141  ** OP_Destroy 5 0
68142  **
68143  ** and root page 5 happened to be the largest root-page number in the
68144  ** database, then root page 5 would be moved to page 4 by the
68145  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
68146  ** a free-list page.
68147  */
68148  int iTab = pTab->tnum;
68149  int iDestroyed = 0;
68150
68151  while( 1 ){
68152    Index *pIdx;
68153    int iLargest = 0;
68154
68155    if( iDestroyed==0 || iTab<iDestroyed ){
68156      iLargest = iTab;
68157    }
68158    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68159      int iIdx = pIdx->tnum;
68160      assert( pIdx->pSchema==pTab->pSchema );
68161      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
68162        iLargest = iIdx;
68163      }
68164    }
68165    if( iLargest==0 ){
68166      return;
68167    }else{
68168      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
68169      destroyRootPage(pParse, iLargest, iDb);
68170      iDestroyed = iLargest;
68171    }
68172  }
68173#endif
68174}
68175
68176/*
68177** This routine is called to do the work of a DROP TABLE statement.
68178** pName is the name of the table to be dropped.
68179*/
68180SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
68181  Table *pTab;
68182  Vdbe *v;
68183  sqlite3 *db = pParse->db;
68184  int iDb;
68185
68186  if( db->mallocFailed ){
68187    goto exit_drop_table;
68188  }
68189  assert( pParse->nErr==0 );
68190  assert( pName->nSrc==1 );
68191  pTab = sqlite3LocateTable(pParse, isView,
68192                            pName->a[0].zName, pName->a[0].zDatabase);
68193
68194  if( pTab==0 ){
68195    if( noErr ){
68196      sqlite3ErrorClear(pParse);
68197    }
68198    goto exit_drop_table;
68199  }
68200  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68201  assert( iDb>=0 && iDb<db->nDb );
68202
68203  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
68204  ** it is initialized.
68205  */
68206  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
68207    goto exit_drop_table;
68208  }
68209#ifndef SQLITE_OMIT_AUTHORIZATION
68210  {
68211    int code;
68212    const char *zTab = SCHEMA_TABLE(iDb);
68213    const char *zDb = db->aDb[iDb].zName;
68214    const char *zArg2 = 0;
68215    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
68216      goto exit_drop_table;
68217    }
68218    if( isView ){
68219      if( !OMIT_TEMPDB && iDb==1 ){
68220        code = SQLITE_DROP_TEMP_VIEW;
68221      }else{
68222        code = SQLITE_DROP_VIEW;
68223      }
68224#ifndef SQLITE_OMIT_VIRTUALTABLE
68225    }else if( IsVirtual(pTab) ){
68226      code = SQLITE_DROP_VTABLE;
68227      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
68228#endif
68229    }else{
68230      if( !OMIT_TEMPDB && iDb==1 ){
68231        code = SQLITE_DROP_TEMP_TABLE;
68232      }else{
68233        code = SQLITE_DROP_TABLE;
68234      }
68235    }
68236    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
68237      goto exit_drop_table;
68238    }
68239    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
68240      goto exit_drop_table;
68241    }
68242  }
68243#endif
68244  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
68245    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
68246    goto exit_drop_table;
68247  }
68248
68249#ifndef SQLITE_OMIT_VIEW
68250  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
68251  ** on a table.
68252  */
68253  if( isView && pTab->pSelect==0 ){
68254    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
68255    goto exit_drop_table;
68256  }
68257  if( !isView && pTab->pSelect ){
68258    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
68259    goto exit_drop_table;
68260  }
68261#endif
68262
68263  /* Generate code to remove the table from the master table
68264  ** on disk.
68265  */
68266  v = sqlite3GetVdbe(pParse);
68267  if( v ){
68268    Trigger *pTrigger;
68269    Db *pDb = &db->aDb[iDb];
68270    sqlite3BeginWriteOperation(pParse, 1, iDb);
68271
68272#ifndef SQLITE_OMIT_VIRTUALTABLE
68273    if( IsVirtual(pTab) ){
68274      sqlite3VdbeAddOp0(v, OP_VBegin);
68275    }
68276#endif
68277    sqlite3FkDropTable(pParse, pName, pTab);
68278
68279    /* Drop all triggers associated with the table being dropped. Code
68280    ** is generated to remove entries from sqlite_master and/or
68281    ** sqlite_temp_master if required.
68282    */
68283    pTrigger = sqlite3TriggerList(pParse, pTab);
68284    while( pTrigger ){
68285      assert( pTrigger->pSchema==pTab->pSchema ||
68286          pTrigger->pSchema==db->aDb[1].pSchema );
68287      sqlite3DropTriggerPtr(pParse, pTrigger);
68288      pTrigger = pTrigger->pNext;
68289    }
68290
68291#ifndef SQLITE_OMIT_AUTOINCREMENT
68292    /* Remove any entries of the sqlite_sequence table associated with
68293    ** the table being dropped. This is done before the table is dropped
68294    ** at the btree level, in case the sqlite_sequence table needs to
68295    ** move as a result of the drop (can happen in auto-vacuum mode).
68296    */
68297    if( pTab->tabFlags & TF_Autoincrement ){
68298      sqlite3NestedParse(pParse,
68299        "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
68300        pDb->zName, pTab->zName
68301      );
68302    }
68303#endif
68304
68305    /* Drop all SQLITE_MASTER table and index entries that refer to the
68306    ** table. The program name loops through the master table and deletes
68307    ** every row that refers to a table of the same name as the one being
68308    ** dropped. Triggers are handled seperately because a trigger can be
68309    ** created in the temp database that refers to a table in another
68310    ** database.
68311    */
68312    sqlite3NestedParse(pParse,
68313        "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
68314        pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
68315
68316    /* Drop any statistics from the sqlite_stat1 table, if it exists */
68317    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
68318      sqlite3NestedParse(pParse,
68319        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
68320      );
68321    }
68322
68323    if( !isView && !IsVirtual(pTab) ){
68324      destroyTable(pParse, pTab);
68325    }
68326
68327    /* Remove the table entry from SQLite's internal schema and modify
68328    ** the schema cookie.
68329    */
68330    if( IsVirtual(pTab) ){
68331      sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
68332    }
68333    sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
68334    sqlite3ChangeCookie(pParse, iDb);
68335  }
68336  sqliteViewResetAll(db, iDb);
68337
68338exit_drop_table:
68339  sqlite3SrcListDelete(db, pName);
68340}
68341
68342/*
68343** This routine is called to create a new foreign key on the table
68344** currently under construction.  pFromCol determines which columns
68345** in the current table point to the foreign key.  If pFromCol==0 then
68346** connect the key to the last column inserted.  pTo is the name of
68347** the table referred to.  pToCol is a list of tables in the other
68348** pTo table that the foreign key points to.  flags contains all
68349** information about the conflict resolution algorithms specified
68350** in the ON DELETE, ON UPDATE and ON INSERT clauses.
68351**
68352** An FKey structure is created and added to the table currently
68353** under construction in the pParse->pNewTable field.
68354**
68355** The foreign key is set for IMMEDIATE processing.  A subsequent call
68356** to sqlite3DeferForeignKey() might change this to DEFERRED.
68357*/
68358SQLITE_PRIVATE void sqlite3CreateForeignKey(
68359  Parse *pParse,       /* Parsing context */
68360  ExprList *pFromCol,  /* Columns in this table that point to other table */
68361  Token *pTo,          /* Name of the other table */
68362  ExprList *pToCol,    /* Columns in the other table */
68363  int flags            /* Conflict resolution algorithms. */
68364){
68365  sqlite3 *db = pParse->db;
68366#ifndef SQLITE_OMIT_FOREIGN_KEY
68367  FKey *pFKey = 0;
68368  FKey *pNextTo;
68369  Table *p = pParse->pNewTable;
68370  int nByte;
68371  int i;
68372  int nCol;
68373  char *z;
68374
68375  assert( pTo!=0 );
68376  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
68377  if( pFromCol==0 ){
68378    int iCol = p->nCol-1;
68379    if( NEVER(iCol<0) ) goto fk_end;
68380    if( pToCol && pToCol->nExpr!=1 ){
68381      sqlite3ErrorMsg(pParse, "foreign key on %s"
68382         " should reference only one column of table %T",
68383         p->aCol[iCol].zName, pTo);
68384      goto fk_end;
68385    }
68386    nCol = 1;
68387  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
68388    sqlite3ErrorMsg(pParse,
68389        "number of columns in foreign key does not match the number of "
68390        "columns in the referenced table");
68391    goto fk_end;
68392  }else{
68393    nCol = pFromCol->nExpr;
68394  }
68395  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
68396  if( pToCol ){
68397    for(i=0; i<pToCol->nExpr; i++){
68398      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
68399    }
68400  }
68401  pFKey = sqlite3DbMallocZero(db, nByte );
68402  if( pFKey==0 ){
68403    goto fk_end;
68404  }
68405  pFKey->pFrom = p;
68406  pFKey->pNextFrom = p->pFKey;
68407  z = (char*)&pFKey->aCol[nCol];
68408  pFKey->zTo = z;
68409  memcpy(z, pTo->z, pTo->n);
68410  z[pTo->n] = 0;
68411  sqlite3Dequote(z);
68412  z += pTo->n+1;
68413  pFKey->nCol = nCol;
68414  if( pFromCol==0 ){
68415    pFKey->aCol[0].iFrom = p->nCol-1;
68416  }else{
68417    for(i=0; i<nCol; i++){
68418      int j;
68419      for(j=0; j<p->nCol; j++){
68420        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
68421          pFKey->aCol[i].iFrom = j;
68422          break;
68423        }
68424      }
68425      if( j>=p->nCol ){
68426        sqlite3ErrorMsg(pParse,
68427          "unknown column \"%s\" in foreign key definition",
68428          pFromCol->a[i].zName);
68429        goto fk_end;
68430      }
68431    }
68432  }
68433  if( pToCol ){
68434    for(i=0; i<nCol; i++){
68435      int n = sqlite3Strlen30(pToCol->a[i].zName);
68436      pFKey->aCol[i].zCol = z;
68437      memcpy(z, pToCol->a[i].zName, n);
68438      z[n] = 0;
68439      z += n+1;
68440    }
68441  }
68442  pFKey->isDeferred = 0;
68443  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
68444  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
68445
68446  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
68447      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
68448  );
68449  if( pNextTo==pFKey ){
68450    db->mallocFailed = 1;
68451    goto fk_end;
68452  }
68453  if( pNextTo ){
68454    assert( pNextTo->pPrevTo==0 );
68455    pFKey->pNextTo = pNextTo;
68456    pNextTo->pPrevTo = pFKey;
68457  }
68458
68459  /* Link the foreign key to the table as the last step.
68460  */
68461  p->pFKey = pFKey;
68462  pFKey = 0;
68463
68464fk_end:
68465  sqlite3DbFree(db, pFKey);
68466#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
68467  sqlite3ExprListDelete(db, pFromCol);
68468  sqlite3ExprListDelete(db, pToCol);
68469}
68470
68471/*
68472** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
68473** clause is seen as part of a foreign key definition.  The isDeferred
68474** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
68475** The behavior of the most recently created foreign key is adjusted
68476** accordingly.
68477*/
68478SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
68479#ifndef SQLITE_OMIT_FOREIGN_KEY
68480  Table *pTab;
68481  FKey *pFKey;
68482  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
68483  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
68484  pFKey->isDeferred = (u8)isDeferred;
68485#endif
68486}
68487
68488/*
68489** Generate code that will erase and refill index *pIdx.  This is
68490** used to initialize a newly created index or to recompute the
68491** content of an index in response to a REINDEX command.
68492**
68493** if memRootPage is not negative, it means that the index is newly
68494** created.  The register specified by memRootPage contains the
68495** root page number of the index.  If memRootPage is negative, then
68496** the index already exists and must be cleared before being refilled and
68497** the root page number of the index is taken from pIndex->tnum.
68498*/
68499static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
68500  Table *pTab = pIndex->pTable;  /* The table that is indexed */
68501  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
68502  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
68503  int addr1;                     /* Address of top of loop */
68504  int tnum;                      /* Root page of index */
68505  Vdbe *v;                       /* Generate code into this virtual machine */
68506  KeyInfo *pKey;                 /* KeyInfo for index */
68507  int regIdxKey;                 /* Registers containing the index key */
68508  int regRecord;                 /* Register holding assemblied index record */
68509  sqlite3 *db = pParse->db;      /* The database connection */
68510  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
68511
68512#ifndef SQLITE_OMIT_AUTHORIZATION
68513  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
68514      db->aDb[iDb].zName ) ){
68515    return;
68516  }
68517#endif
68518
68519  /* Require a write-lock on the table to perform this operation */
68520  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
68521
68522  v = sqlite3GetVdbe(pParse);
68523  if( v==0 ) return;
68524  if( memRootPage>=0 ){
68525    tnum = memRootPage;
68526  }else{
68527    tnum = pIndex->tnum;
68528    sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
68529  }
68530  pKey = sqlite3IndexKeyinfo(pParse, pIndex);
68531  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
68532                    (char *)pKey, P4_KEYINFO_HANDOFF);
68533  if( memRootPage>=0 ){
68534    sqlite3VdbeChangeP5(v, 1);
68535  }
68536  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
68537  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
68538  regRecord = sqlite3GetTempReg(pParse);
68539  regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
68540  if( pIndex->onError!=OE_None ){
68541    const int regRowid = regIdxKey + pIndex->nColumn;
68542    const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
68543    void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
68544
68545    /* The registers accessed by the OP_IsUnique opcode were allocated
68546    ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
68547    ** call above. Just before that function was freed they were released
68548    ** (made available to the compiler for reuse) using
68549    ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
68550    ** opcode use the values stored within seems dangerous. However, since
68551    ** we can be sure that no other temp registers have been allocated
68552    ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
68553    */
68554    sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
68555    sqlite3HaltConstraint(
68556        pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
68557  }
68558  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
68559  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
68560  sqlite3ReleaseTempReg(pParse, regRecord);
68561  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
68562  sqlite3VdbeJumpHere(v, addr1);
68563  sqlite3VdbeAddOp1(v, OP_Close, iTab);
68564  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
68565}
68566
68567/*
68568** Create a new index for an SQL table.  pName1.pName2 is the name of the index
68569** and pTblList is the name of the table that is to be indexed.  Both will
68570** be NULL for a primary key or an index that is created to satisfy a
68571** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
68572** as the table to be indexed.  pParse->pNewTable is a table that is
68573** currently being constructed by a CREATE TABLE statement.
68574**
68575** pList is a list of columns to be indexed.  pList will be NULL if this
68576** is a primary key or unique-constraint on the most recent column added
68577** to the table currently under construction.
68578**
68579** If the index is created successfully, return a pointer to the new Index
68580** structure. This is used by sqlite3AddPrimaryKey() to mark the index
68581** as the tables primary key (Index.autoIndex==2).
68582*/
68583SQLITE_PRIVATE Index *sqlite3CreateIndex(
68584  Parse *pParse,     /* All information about this parse */
68585  Token *pName1,     /* First part of index name. May be NULL */
68586  Token *pName2,     /* Second part of index name. May be NULL */
68587  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
68588  ExprList *pList,   /* A list of columns to be indexed */
68589  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
68590  Token *pStart,     /* The CREATE token that begins this statement */
68591  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
68592  int sortOrder,     /* Sort order of primary key when pList==NULL */
68593  int ifNotExist     /* Omit error if index already exists */
68594){
68595  Index *pRet = 0;     /* Pointer to return */
68596  Table *pTab = 0;     /* Table to be indexed */
68597  Index *pIndex = 0;   /* The index to be created */
68598  char *zName = 0;     /* Name of the index */
68599  int nName;           /* Number of characters in zName */
68600  int i, j;
68601  Token nullId;        /* Fake token for an empty ID list */
68602  DbFixer sFix;        /* For assigning database names to pTable */
68603  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
68604  sqlite3 *db = pParse->db;
68605  Db *pDb;             /* The specific table containing the indexed database */
68606  int iDb;             /* Index of the database that is being written */
68607  Token *pName = 0;    /* Unqualified name of the index to create */
68608  struct ExprList_item *pListItem; /* For looping over pList */
68609  int nCol;
68610  int nExtra = 0;
68611  char *zExtra;
68612
68613  assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
68614  assert( pParse->nErr==0 );      /* Never called with prior errors */
68615  if( db->mallocFailed || IN_DECLARE_VTAB ){
68616    goto exit_create_index;
68617  }
68618  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
68619    goto exit_create_index;
68620  }
68621
68622  /*
68623  ** Find the table that is to be indexed.  Return early if not found.
68624  */
68625  if( pTblName!=0 ){
68626
68627    /* Use the two-part index name to determine the database
68628    ** to search for the table. 'Fix' the table name to this db
68629    ** before looking up the table.
68630    */
68631    assert( pName1 && pName2 );
68632    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
68633    if( iDb<0 ) goto exit_create_index;
68634
68635#ifndef SQLITE_OMIT_TEMPDB
68636    /* If the index name was unqualified, check if the the table
68637    ** is a temp table. If so, set the database to 1. Do not do this
68638    ** if initialising a database schema.
68639    */
68640    if( !db->init.busy ){
68641      pTab = sqlite3SrcListLookup(pParse, pTblName);
68642      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
68643        iDb = 1;
68644      }
68645    }
68646#endif
68647
68648    if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
68649        sqlite3FixSrcList(&sFix, pTblName)
68650    ){
68651      /* Because the parser constructs pTblName from a single identifier,
68652      ** sqlite3FixSrcList can never fail. */
68653      assert(0);
68654    }
68655    pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
68656        pTblName->a[0].zDatabase);
68657    if( !pTab || db->mallocFailed ) goto exit_create_index;
68658    assert( db->aDb[iDb].pSchema==pTab->pSchema );
68659  }else{
68660    assert( pName==0 );
68661    pTab = pParse->pNewTable;
68662    if( !pTab ) goto exit_create_index;
68663    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
68664  }
68665  pDb = &db->aDb[iDb];
68666
68667  assert( pTab!=0 );
68668  assert( pParse->nErr==0 );
68669  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
68670       && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
68671    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
68672    goto exit_create_index;
68673  }
68674#ifndef SQLITE_OMIT_VIEW
68675  if( pTab->pSelect ){
68676    sqlite3ErrorMsg(pParse, "views may not be indexed");
68677    goto exit_create_index;
68678  }
68679#endif
68680#ifndef SQLITE_OMIT_VIRTUALTABLE
68681  if( IsVirtual(pTab) ){
68682    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
68683    goto exit_create_index;
68684  }
68685#endif
68686
68687  /*
68688  ** Find the name of the index.  Make sure there is not already another
68689  ** index or table with the same name.
68690  **
68691  ** Exception:  If we are reading the names of permanent indices from the
68692  ** sqlite_master table (because some other process changed the schema) and
68693  ** one of the index names collides with the name of a temporary table or
68694  ** index, then we will continue to process this index.
68695  **
68696  ** If pName==0 it means that we are
68697  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
68698  ** own name.
68699  */
68700  if( pName ){
68701    zName = sqlite3NameFromToken(db, pName);
68702    if( zName==0 ) goto exit_create_index;
68703    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
68704      goto exit_create_index;
68705    }
68706    if( !db->init.busy ){
68707      if( sqlite3FindTable(db, zName, 0)!=0 ){
68708        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
68709        goto exit_create_index;
68710      }
68711    }
68712    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
68713      if( !ifNotExist ){
68714        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
68715      }
68716      goto exit_create_index;
68717    }
68718  }else{
68719    int n;
68720    Index *pLoop;
68721    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
68722    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
68723    if( zName==0 ){
68724      goto exit_create_index;
68725    }
68726  }
68727
68728  /* Check for authorization to create an index.
68729  */
68730#ifndef SQLITE_OMIT_AUTHORIZATION
68731  {
68732    const char *zDb = pDb->zName;
68733    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
68734      goto exit_create_index;
68735    }
68736    i = SQLITE_CREATE_INDEX;
68737    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
68738    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
68739      goto exit_create_index;
68740    }
68741  }
68742#endif
68743
68744  /* If pList==0, it means this routine was called to make a primary
68745  ** key out of the last column added to the table under construction.
68746  ** So create a fake list to simulate this.
68747  */
68748  if( pList==0 ){
68749    nullId.z = pTab->aCol[pTab->nCol-1].zName;
68750    nullId.n = sqlite3Strlen30((char*)nullId.z);
68751    pList = sqlite3ExprListAppend(pParse, 0, 0);
68752    if( pList==0 ) goto exit_create_index;
68753    sqlite3ExprListSetName(pParse, pList, &nullId, 0);
68754    pList->a[0].sortOrder = (u8)sortOrder;
68755  }
68756
68757  /* Figure out how many bytes of space are required to store explicitly
68758  ** specified collation sequence names.
68759  */
68760  for(i=0; i<pList->nExpr; i++){
68761    Expr *pExpr = pList->a[i].pExpr;
68762    if( pExpr ){
68763      CollSeq *pColl = pExpr->pColl;
68764      /* Either pColl!=0 or there was an OOM failure.  But if an OOM
68765      ** failure we have quit before reaching this point. */
68766      if( ALWAYS(pColl) ){
68767        nExtra += (1 + sqlite3Strlen30(pColl->zName));
68768      }
68769    }
68770  }
68771
68772  /*
68773  ** Allocate the index structure.
68774  */
68775  nName = sqlite3Strlen30(zName);
68776  nCol = pList->nExpr;
68777  pIndex = sqlite3DbMallocZero(db,
68778      sizeof(Index) +              /* Index structure  */
68779      sizeof(int)*nCol +           /* Index.aiColumn   */
68780      sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
68781      sizeof(char *)*nCol +        /* Index.azColl     */
68782      sizeof(u8)*nCol +            /* Index.aSortOrder */
68783      nName + 1 +                  /* Index.zName      */
68784      nExtra                       /* Collation sequence names */
68785  );
68786  if( db->mallocFailed ){
68787    goto exit_create_index;
68788  }
68789  pIndex->azColl = (char**)(&pIndex[1]);
68790  pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
68791  pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
68792  pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
68793  pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
68794  zExtra = (char *)(&pIndex->zName[nName+1]);
68795  memcpy(pIndex->zName, zName, nName+1);
68796  pIndex->pTable = pTab;
68797  pIndex->nColumn = pList->nExpr;
68798  pIndex->onError = (u8)onError;
68799  pIndex->autoIndex = (u8)(pName==0);
68800  pIndex->pSchema = db->aDb[iDb].pSchema;
68801
68802  /* Check to see if we should honor DESC requests on index columns
68803  */
68804  if( pDb->pSchema->file_format>=4 ){
68805    sortOrderMask = -1;   /* Honor DESC */
68806  }else{
68807    sortOrderMask = 0;    /* Ignore DESC */
68808  }
68809
68810  /* Scan the names of the columns of the table to be indexed and
68811  ** load the column indices into the Index structure.  Report an error
68812  ** if any column is not found.
68813  **
68814  ** TODO:  Add a test to make sure that the same column is not named
68815  ** more than once within the same index.  Only the first instance of
68816  ** the column will ever be used by the optimizer.  Note that using the
68817  ** same column more than once cannot be an error because that would
68818  ** break backwards compatibility - it needs to be a warning.
68819  */
68820  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
68821    const char *zColName = pListItem->zName;
68822    Column *pTabCol;
68823    int requestedSortOrder;
68824    char *zColl;                   /* Collation sequence name */
68825
68826    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
68827      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
68828    }
68829    if( j>=pTab->nCol ){
68830      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
68831        pTab->zName, zColName);
68832      goto exit_create_index;
68833    }
68834    pIndex->aiColumn[i] = j;
68835    /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
68836    ** the way the "idxlist" non-terminal is constructed by the parser,
68837    ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
68838    ** must exist or else there must have been an OOM error.  But if there
68839    ** was an OOM error, we would never reach this point. */
68840    if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
68841      int nColl;
68842      zColl = pListItem->pExpr->pColl->zName;
68843      nColl = sqlite3Strlen30(zColl) + 1;
68844      assert( nExtra>=nColl );
68845      memcpy(zExtra, zColl, nColl);
68846      zColl = zExtra;
68847      zExtra += nColl;
68848      nExtra -= nColl;
68849    }else{
68850      zColl = pTab->aCol[j].zColl;
68851      if( !zColl ){
68852        zColl = db->pDfltColl->zName;
68853      }
68854    }
68855    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
68856      goto exit_create_index;
68857    }
68858    pIndex->azColl[i] = zColl;
68859    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
68860    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
68861  }
68862  sqlite3DefaultRowEst(pIndex);
68863
68864  if( pTab==pParse->pNewTable ){
68865    /* This routine has been called to create an automatic index as a
68866    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
68867    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
68868    ** i.e. one of:
68869    **
68870    ** CREATE TABLE t(x PRIMARY KEY, y);
68871    ** CREATE TABLE t(x, y, UNIQUE(x, y));
68872    **
68873    ** Either way, check to see if the table already has such an index. If
68874    ** so, don't bother creating this one. This only applies to
68875    ** automatically created indices. Users can do as they wish with
68876    ** explicit indices.
68877    **
68878    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
68879    ** (and thus suppressing the second one) even if they have different
68880    ** sort orders.
68881    **
68882    ** If there are different collating sequences or if the columns of
68883    ** the constraint occur in different orders, then the constraints are
68884    ** considered distinct and both result in separate indices.
68885    */
68886    Index *pIdx;
68887    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
68888      int k;
68889      assert( pIdx->onError!=OE_None );
68890      assert( pIdx->autoIndex );
68891      assert( pIndex->onError!=OE_None );
68892
68893      if( pIdx->nColumn!=pIndex->nColumn ) continue;
68894      for(k=0; k<pIdx->nColumn; k++){
68895        const char *z1;
68896        const char *z2;
68897        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
68898        z1 = pIdx->azColl[k];
68899        z2 = pIndex->azColl[k];
68900        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
68901      }
68902      if( k==pIdx->nColumn ){
68903        if( pIdx->onError!=pIndex->onError ){
68904          /* This constraint creates the same index as a previous
68905          ** constraint specified somewhere in the CREATE TABLE statement.
68906          ** However the ON CONFLICT clauses are different. If both this
68907          ** constraint and the previous equivalent constraint have explicit
68908          ** ON CONFLICT clauses this is an error. Otherwise, use the
68909          ** explicitly specified behaviour for the index.
68910          */
68911          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
68912            sqlite3ErrorMsg(pParse,
68913                "conflicting ON CONFLICT clauses specified", 0);
68914          }
68915          if( pIdx->onError==OE_Default ){
68916            pIdx->onError = pIndex->onError;
68917          }
68918        }
68919        goto exit_create_index;
68920      }
68921    }
68922  }
68923
68924  /* Link the new Index structure to its table and to the other
68925  ** in-memory database structures.
68926  */
68927  if( db->init.busy ){
68928    Index *p;
68929    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
68930                          pIndex->zName, sqlite3Strlen30(pIndex->zName),
68931                          pIndex);
68932    if( p ){
68933      assert( p==pIndex );  /* Malloc must have failed */
68934      db->mallocFailed = 1;
68935      goto exit_create_index;
68936    }
68937    db->flags |= SQLITE_InternChanges;
68938    if( pTblName!=0 ){
68939      pIndex->tnum = db->init.newTnum;
68940    }
68941  }
68942
68943  /* If the db->init.busy is 0 then create the index on disk.  This
68944  ** involves writing the index into the master table and filling in the
68945  ** index with the current table contents.
68946  **
68947  ** The db->init.busy is 0 when the user first enters a CREATE INDEX
68948  ** command.  db->init.busy is 1 when a database is opened and
68949  ** CREATE INDEX statements are read out of the master table.  In
68950  ** the latter case the index already exists on disk, which is why
68951  ** we don't want to recreate it.
68952  **
68953  ** If pTblName==0 it means this index is generated as a primary key
68954  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
68955  ** has just been created, it contains no data and the index initialization
68956  ** step can be skipped.
68957  */
68958  else{ /* if( db->init.busy==0 ) */
68959    Vdbe *v;
68960    char *zStmt;
68961    int iMem = ++pParse->nMem;
68962
68963    v = sqlite3GetVdbe(pParse);
68964    if( v==0 ) goto exit_create_index;
68965
68966
68967    /* Create the rootpage for the index
68968    */
68969    sqlite3BeginWriteOperation(pParse, 1, iDb);
68970    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
68971
68972    /* Gather the complete text of the CREATE INDEX statement into
68973    ** the zStmt variable
68974    */
68975    if( pStart ){
68976      assert( pEnd!=0 );
68977      /* A named index with an explicit CREATE INDEX statement */
68978      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
68979        onError==OE_None ? "" : " UNIQUE",
68980        pEnd->z - pName->z + 1,
68981        pName->z);
68982    }else{
68983      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
68984      /* zStmt = sqlite3MPrintf(""); */
68985      zStmt = 0;
68986    }
68987
68988    /* Add an entry in sqlite_master for this index
68989    */
68990    sqlite3NestedParse(pParse,
68991        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
68992        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
68993        pIndex->zName,
68994        pTab->zName,
68995        iMem,
68996        zStmt
68997    );
68998    sqlite3DbFree(db, zStmt);
68999
69000    /* Fill the index with data and reparse the schema. Code an OP_Expire
69001    ** to invalidate all pre-compiled statements.
69002    */
69003    if( pTblName ){
69004      sqlite3RefillIndex(pParse, pIndex, iMem);
69005      sqlite3ChangeCookie(pParse, iDb);
69006      sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
69007         sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
69008      sqlite3VdbeAddOp1(v, OP_Expire, 0);
69009    }
69010  }
69011
69012  /* When adding an index to the list of indices for a table, make
69013  ** sure all indices labeled OE_Replace come after all those labeled
69014  ** OE_Ignore.  This is necessary for the correct constraint check
69015  ** processing (in sqlite3GenerateConstraintChecks()) as part of
69016  ** UPDATE and INSERT statements.
69017  */
69018  if( db->init.busy || pTblName==0 ){
69019    if( onError!=OE_Replace || pTab->pIndex==0
69020         || pTab->pIndex->onError==OE_Replace){
69021      pIndex->pNext = pTab->pIndex;
69022      pTab->pIndex = pIndex;
69023    }else{
69024      Index *pOther = pTab->pIndex;
69025      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
69026        pOther = pOther->pNext;
69027      }
69028      pIndex->pNext = pOther->pNext;
69029      pOther->pNext = pIndex;
69030    }
69031    pRet = pIndex;
69032    pIndex = 0;
69033  }
69034
69035  /* Clean up before exiting */
69036exit_create_index:
69037  if( pIndex ){
69038    sqlite3_free(pIndex->zColAff);
69039    sqlite3DbFree(db, pIndex);
69040  }
69041  sqlite3ExprListDelete(db, pList);
69042  sqlite3SrcListDelete(db, pTblName);
69043  sqlite3DbFree(db, zName);
69044  return pRet;
69045}
69046
69047/*
69048** Fill the Index.aiRowEst[] array with default information - information
69049** to be used when we have not run the ANALYZE command.
69050**
69051** aiRowEst[0] is suppose to contain the number of elements in the index.
69052** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
69053** number of rows in the table that match any particular value of the
69054** first column of the index.  aiRowEst[2] is an estimate of the number
69055** of rows that match any particular combiniation of the first 2 columns
69056** of the index.  And so forth.  It must always be the case that
69057*
69058**           aiRowEst[N]<=aiRowEst[N-1]
69059**           aiRowEst[N]>=1
69060**
69061** Apart from that, we have little to go on besides intuition as to
69062** how aiRowEst[] should be initialized.  The numbers generated here
69063** are based on typical values found in actual indices.
69064*/
69065SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
69066  unsigned *a = pIdx->aiRowEst;
69067  int i;
69068  assert( a!=0 );
69069  a[0] = 1000000;
69070  for(i=pIdx->nColumn; i>=5; i--){
69071    a[i] = 5;
69072  }
69073  while( i>=1 ){
69074    a[i] = 11 - i;
69075    i--;
69076  }
69077  if( pIdx->onError!=OE_None ){
69078    a[pIdx->nColumn] = 1;
69079  }
69080}
69081
69082/*
69083** This routine will drop an existing named index.  This routine
69084** implements the DROP INDEX statement.
69085*/
69086SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
69087  Index *pIndex;
69088  Vdbe *v;
69089  sqlite3 *db = pParse->db;
69090  int iDb;
69091
69092  assert( pParse->nErr==0 );   /* Never called with prior errors */
69093  if( db->mallocFailed ){
69094    goto exit_drop_index;
69095  }
69096  assert( pName->nSrc==1 );
69097  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
69098    goto exit_drop_index;
69099  }
69100  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
69101  if( pIndex==0 ){
69102    if( !ifExists ){
69103      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
69104    }
69105    pParse->checkSchema = 1;
69106    goto exit_drop_index;
69107  }
69108  if( pIndex->autoIndex ){
69109    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
69110      "or PRIMARY KEY constraint cannot be dropped", 0);
69111    goto exit_drop_index;
69112  }
69113  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
69114#ifndef SQLITE_OMIT_AUTHORIZATION
69115  {
69116    int code = SQLITE_DROP_INDEX;
69117    Table *pTab = pIndex->pTable;
69118    const char *zDb = db->aDb[iDb].zName;
69119    const char *zTab = SCHEMA_TABLE(iDb);
69120    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
69121      goto exit_drop_index;
69122    }
69123    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
69124    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
69125      goto exit_drop_index;
69126    }
69127  }
69128#endif
69129
69130  /* Generate code to remove the index and from the master table */
69131  v = sqlite3GetVdbe(pParse);
69132  if( v ){
69133    sqlite3BeginWriteOperation(pParse, 1, iDb);
69134    sqlite3NestedParse(pParse,
69135       "DELETE FROM %Q.%s WHERE name=%Q",
69136       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
69137       pIndex->zName
69138    );
69139    if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
69140      sqlite3NestedParse(pParse,
69141        "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
69142        db->aDb[iDb].zName, pIndex->zName
69143      );
69144    }
69145    sqlite3ChangeCookie(pParse, iDb);
69146    destroyRootPage(pParse, pIndex->tnum, iDb);
69147    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
69148  }
69149
69150exit_drop_index:
69151  sqlite3SrcListDelete(db, pName);
69152}
69153
69154/*
69155** pArray is a pointer to an array of objects.  Each object in the
69156** array is szEntry bytes in size.  This routine allocates a new
69157** object on the end of the array.
69158**
69159** *pnEntry is the number of entries already in use.  *pnAlloc is
69160** the previously allocated size of the array.  initSize is the
69161** suggested initial array size allocation.
69162**
69163** The index of the new entry is returned in *pIdx.
69164**
69165** This routine returns a pointer to the array of objects.  This
69166** might be the same as the pArray parameter or it might be a different
69167** pointer if the array was resized.
69168*/
69169SQLITE_PRIVATE void *sqlite3ArrayAllocate(
69170  sqlite3 *db,      /* Connection to notify of malloc failures */
69171  void *pArray,     /* Array of objects.  Might be reallocated */
69172  int szEntry,      /* Size of each object in the array */
69173  int initSize,     /* Suggested initial allocation, in elements */
69174  int *pnEntry,     /* Number of objects currently in use */
69175  int *pnAlloc,     /* Current size of the allocation, in elements */
69176  int *pIdx         /* Write the index of a new slot here */
69177){
69178  char *z;
69179  if( *pnEntry >= *pnAlloc ){
69180    void *pNew;
69181    int newSize;
69182    newSize = (*pnAlloc)*2 + initSize;
69183    pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
69184    if( pNew==0 ){
69185      *pIdx = -1;
69186      return pArray;
69187    }
69188    *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
69189    pArray = pNew;
69190  }
69191  z = (char*)pArray;
69192  memset(&z[*pnEntry * szEntry], 0, szEntry);
69193  *pIdx = *pnEntry;
69194  ++*pnEntry;
69195  return pArray;
69196}
69197
69198/*
69199** Append a new element to the given IdList.  Create a new IdList if
69200** need be.
69201**
69202** A new IdList is returned, or NULL if malloc() fails.
69203*/
69204SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
69205  int i;
69206  if( pList==0 ){
69207    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
69208    if( pList==0 ) return 0;
69209    pList->nAlloc = 0;
69210  }
69211  pList->a = sqlite3ArrayAllocate(
69212      db,
69213      pList->a,
69214      sizeof(pList->a[0]),
69215      5,
69216      &pList->nId,
69217      &pList->nAlloc,
69218      &i
69219  );
69220  if( i<0 ){
69221    sqlite3IdListDelete(db, pList);
69222    return 0;
69223  }
69224  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
69225  return pList;
69226}
69227
69228/*
69229** Delete an IdList.
69230*/
69231SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
69232  int i;
69233  if( pList==0 ) return;
69234  for(i=0; i<pList->nId; i++){
69235    sqlite3DbFree(db, pList->a[i].zName);
69236  }
69237  sqlite3DbFree(db, pList->a);
69238  sqlite3DbFree(db, pList);
69239}
69240
69241/*
69242** Return the index in pList of the identifier named zId.  Return -1
69243** if not found.
69244*/
69245SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
69246  int i;
69247  if( pList==0 ) return -1;
69248  for(i=0; i<pList->nId; i++){
69249    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
69250  }
69251  return -1;
69252}
69253
69254/*
69255** Expand the space allocated for the given SrcList object by
69256** creating nExtra new slots beginning at iStart.  iStart is zero based.
69257** New slots are zeroed.
69258**
69259** For example, suppose a SrcList initially contains two entries: A,B.
69260** To append 3 new entries onto the end, do this:
69261**
69262**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
69263**
69264** After the call above it would contain:  A, B, nil, nil, nil.
69265** If the iStart argument had been 1 instead of 2, then the result
69266** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
69267** the iStart value would be 0.  The result then would
69268** be: nil, nil, nil, A, B.
69269**
69270** If a memory allocation fails the SrcList is unchanged.  The
69271** db->mallocFailed flag will be set to true.
69272*/
69273SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
69274  sqlite3 *db,       /* Database connection to notify of OOM errors */
69275  SrcList *pSrc,     /* The SrcList to be enlarged */
69276  int nExtra,        /* Number of new slots to add to pSrc->a[] */
69277  int iStart         /* Index in pSrc->a[] of first new slot */
69278){
69279  int i;
69280
69281  /* Sanity checking on calling parameters */
69282  assert( iStart>=0 );
69283  assert( nExtra>=1 );
69284  assert( pSrc!=0 );
69285  assert( iStart<=pSrc->nSrc );
69286
69287  /* Allocate additional space if needed */
69288  if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
69289    SrcList *pNew;
69290    int nAlloc = pSrc->nSrc+nExtra;
69291    int nGot;
69292    pNew = sqlite3DbRealloc(db, pSrc,
69293               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
69294    if( pNew==0 ){
69295      assert( db->mallocFailed );
69296      return pSrc;
69297    }
69298    pSrc = pNew;
69299    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
69300    pSrc->nAlloc = (u16)nGot;
69301  }
69302
69303  /* Move existing slots that come after the newly inserted slots
69304  ** out of the way */
69305  for(i=pSrc->nSrc-1; i>=iStart; i--){
69306    pSrc->a[i+nExtra] = pSrc->a[i];
69307  }
69308  pSrc->nSrc += (i16)nExtra;
69309
69310  /* Zero the newly allocated slots */
69311  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
69312  for(i=iStart; i<iStart+nExtra; i++){
69313    pSrc->a[i].iCursor = -1;
69314  }
69315
69316  /* Return a pointer to the enlarged SrcList */
69317  return pSrc;
69318}
69319
69320
69321/*
69322** Append a new table name to the given SrcList.  Create a new SrcList if
69323** need be.  A new entry is created in the SrcList even if pTable is NULL.
69324**
69325** A SrcList is returned, or NULL if there is an OOM error.  The returned
69326** SrcList might be the same as the SrcList that was input or it might be
69327** a new one.  If an OOM error does occurs, then the prior value of pList
69328** that is input to this routine is automatically freed.
69329**
69330** If pDatabase is not null, it means that the table has an optional
69331** database name prefix.  Like this:  "database.table".  The pDatabase
69332** points to the table name and the pTable points to the database name.
69333** The SrcList.a[].zName field is filled with the table name which might
69334** come from pTable (if pDatabase is NULL) or from pDatabase.
69335** SrcList.a[].zDatabase is filled with the database name from pTable,
69336** or with NULL if no database is specified.
69337**
69338** In other words, if call like this:
69339**
69340**         sqlite3SrcListAppend(D,A,B,0);
69341**
69342** Then B is a table name and the database name is unspecified.  If called
69343** like this:
69344**
69345**         sqlite3SrcListAppend(D,A,B,C);
69346**
69347** Then C is the table name and B is the database name.  If C is defined
69348** then so is B.  In other words, we never have a case where:
69349**
69350**         sqlite3SrcListAppend(D,A,0,C);
69351**
69352** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
69353** before being added to the SrcList.
69354*/
69355SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
69356  sqlite3 *db,        /* Connection to notify of malloc failures */
69357  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
69358  Token *pTable,      /* Table to append */
69359  Token *pDatabase    /* Database of the table */
69360){
69361  struct SrcList_item *pItem;
69362  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
69363  if( pList==0 ){
69364    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
69365    if( pList==0 ) return 0;
69366    pList->nAlloc = 1;
69367  }
69368  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
69369  if( db->mallocFailed ){
69370    sqlite3SrcListDelete(db, pList);
69371    return 0;
69372  }
69373  pItem = &pList->a[pList->nSrc-1];
69374  if( pDatabase && pDatabase->z==0 ){
69375    pDatabase = 0;
69376  }
69377  if( pDatabase ){
69378    Token *pTemp = pDatabase;
69379    pDatabase = pTable;
69380    pTable = pTemp;
69381  }
69382  pItem->zName = sqlite3NameFromToken(db, pTable);
69383  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
69384  return pList;
69385}
69386
69387/*
69388** Assign VdbeCursor index numbers to all tables in a SrcList
69389*/
69390SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
69391  int i;
69392  struct SrcList_item *pItem;
69393  assert(pList || pParse->db->mallocFailed );
69394  if( pList ){
69395    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
69396      if( pItem->iCursor>=0 ) break;
69397      pItem->iCursor = pParse->nTab++;
69398      if( pItem->pSelect ){
69399        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
69400      }
69401    }
69402  }
69403}
69404
69405/*
69406** Delete an entire SrcList including all its substructure.
69407*/
69408SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
69409  int i;
69410  struct SrcList_item *pItem;
69411  if( pList==0 ) return;
69412  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
69413    sqlite3DbFree(db, pItem->zDatabase);
69414    sqlite3DbFree(db, pItem->zName);
69415    sqlite3DbFree(db, pItem->zAlias);
69416    sqlite3DbFree(db, pItem->zIndex);
69417    sqlite3DeleteTable(pItem->pTab);
69418    sqlite3SelectDelete(db, pItem->pSelect);
69419    sqlite3ExprDelete(db, pItem->pOn);
69420    sqlite3IdListDelete(db, pItem->pUsing);
69421  }
69422  sqlite3DbFree(db, pList);
69423}
69424
69425/*
69426** This routine is called by the parser to add a new term to the
69427** end of a growing FROM clause.  The "p" parameter is the part of
69428** the FROM clause that has already been constructed.  "p" is NULL
69429** if this is the first term of the FROM clause.  pTable and pDatabase
69430** are the name of the table and database named in the FROM clause term.
69431** pDatabase is NULL if the database name qualifier is missing - the
69432** usual case.  If the term has a alias, then pAlias points to the
69433** alias token.  If the term is a subquery, then pSubquery is the
69434** SELECT statement that the subquery encodes.  The pTable and
69435** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
69436** parameters are the content of the ON and USING clauses.
69437**
69438** Return a new SrcList which encodes is the FROM with the new
69439** term added.
69440*/
69441SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
69442  Parse *pParse,          /* Parsing context */
69443  SrcList *p,             /* The left part of the FROM clause already seen */
69444  Token *pTable,          /* Name of the table to add to the FROM clause */
69445  Token *pDatabase,       /* Name of the database containing pTable */
69446  Token *pAlias,          /* The right-hand side of the AS subexpression */
69447  Select *pSubquery,      /* A subquery used in place of a table name */
69448  Expr *pOn,              /* The ON clause of a join */
69449  IdList *pUsing          /* The USING clause of a join */
69450){
69451  struct SrcList_item *pItem;
69452  sqlite3 *db = pParse->db;
69453  if( !p && (pOn || pUsing) ){
69454    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
69455      (pOn ? "ON" : "USING")
69456    );
69457    goto append_from_error;
69458  }
69459  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
69460  if( p==0 || NEVER(p->nSrc==0) ){
69461    goto append_from_error;
69462  }
69463  pItem = &p->a[p->nSrc-1];
69464  assert( pAlias!=0 );
69465  if( pAlias->n ){
69466    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
69467  }
69468  pItem->pSelect = pSubquery;
69469  pItem->pOn = pOn;
69470  pItem->pUsing = pUsing;
69471  return p;
69472
69473 append_from_error:
69474  assert( p==0 );
69475  sqlite3ExprDelete(db, pOn);
69476  sqlite3IdListDelete(db, pUsing);
69477  sqlite3SelectDelete(db, pSubquery);
69478  return 0;
69479}
69480
69481/*
69482** Add an INDEXED BY or NOT INDEXED clause to the most recently added
69483** element of the source-list passed as the second argument.
69484*/
69485SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
69486  assert( pIndexedBy!=0 );
69487  if( p && ALWAYS(p->nSrc>0) ){
69488    struct SrcList_item *pItem = &p->a[p->nSrc-1];
69489    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
69490    if( pIndexedBy->n==1 && !pIndexedBy->z ){
69491      /* A "NOT INDEXED" clause was supplied. See parse.y
69492      ** construct "indexed_opt" for details. */
69493      pItem->notIndexed = 1;
69494    }else{
69495      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
69496    }
69497  }
69498}
69499
69500/*
69501** When building up a FROM clause in the parser, the join operator
69502** is initially attached to the left operand.  But the code generator
69503** expects the join operator to be on the right operand.  This routine
69504** Shifts all join operators from left to right for an entire FROM
69505** clause.
69506**
69507** Example: Suppose the join is like this:
69508**
69509**           A natural cross join B
69510**
69511** The operator is "natural cross join".  The A and B operands are stored
69512** in p->a[0] and p->a[1], respectively.  The parser initially stores the
69513** operator with A.  This routine shifts that operator over to B.
69514*/
69515SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
69516  if( p && p->a ){
69517    int i;
69518    for(i=p->nSrc-1; i>0; i--){
69519      p->a[i].jointype = p->a[i-1].jointype;
69520    }
69521    p->a[0].jointype = 0;
69522  }
69523}
69524
69525/*
69526** Begin a transaction
69527*/
69528SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
69529  sqlite3 *db;
69530  Vdbe *v;
69531  int i;
69532
69533  assert( pParse!=0 );
69534  db = pParse->db;
69535  assert( db!=0 );
69536/*  if( db->aDb[0].pBt==0 ) return; */
69537  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
69538    return;
69539  }
69540  v = sqlite3GetVdbe(pParse);
69541  if( !v ) return;
69542  if( type!=TK_DEFERRED ){
69543    for(i=0; i<db->nDb; i++){
69544      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
69545      sqlite3VdbeUsesBtree(v, i);
69546    }
69547  }
69548  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
69549}
69550
69551/*
69552** Commit a transaction
69553*/
69554SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
69555  sqlite3 *db;
69556  Vdbe *v;
69557
69558  assert( pParse!=0 );
69559  db = pParse->db;
69560  assert( db!=0 );
69561/*  if( db->aDb[0].pBt==0 ) return; */
69562  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
69563    return;
69564  }
69565  v = sqlite3GetVdbe(pParse);
69566  if( v ){
69567    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
69568  }
69569}
69570
69571/*
69572** Rollback a transaction
69573*/
69574SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
69575  sqlite3 *db;
69576  Vdbe *v;
69577
69578  assert( pParse!=0 );
69579  db = pParse->db;
69580  assert( db!=0 );
69581/*  if( db->aDb[0].pBt==0 ) return; */
69582  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
69583    return;
69584  }
69585  v = sqlite3GetVdbe(pParse);
69586  if( v ){
69587    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
69588  }
69589}
69590
69591/*
69592** This function is called by the parser when it parses a command to create,
69593** release or rollback an SQL savepoint.
69594*/
69595SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
69596  char *zName = sqlite3NameFromToken(pParse->db, pName);
69597  if( zName ){
69598    Vdbe *v = sqlite3GetVdbe(pParse);
69599#ifndef SQLITE_OMIT_AUTHORIZATION
69600    static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
69601    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
69602#endif
69603    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
69604      sqlite3DbFree(pParse->db, zName);
69605      return;
69606    }
69607    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
69608  }
69609}
69610
69611/*
69612** Make sure the TEMP database is open and available for use.  Return
69613** the number of errors.  Leave any error messages in the pParse structure.
69614*/
69615SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
69616  sqlite3 *db = pParse->db;
69617  if( db->aDb[1].pBt==0 && !pParse->explain ){
69618    int rc;
69619    static const int flags =
69620          SQLITE_OPEN_READWRITE |
69621          SQLITE_OPEN_CREATE |
69622          SQLITE_OPEN_EXCLUSIVE |
69623          SQLITE_OPEN_DELETEONCLOSE |
69624          SQLITE_OPEN_TEMP_DB;
69625
69626    rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
69627                                 &db->aDb[1].pBt);
69628    if( rc!=SQLITE_OK ){
69629      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
69630        "file for storing temporary tables");
69631      pParse->rc = rc;
69632      return 1;
69633    }
69634    assert( db->aDb[1].pSchema );
69635    sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
69636                            db->dfltJournalMode);
69637  }
69638  return 0;
69639}
69640
69641/*
69642** Generate VDBE code that will verify the schema cookie and start
69643** a read-transaction for all named database files.
69644**
69645** It is important that all schema cookies be verified and all
69646** read transactions be started before anything else happens in
69647** the VDBE program.  But this routine can be called after much other
69648** code has been generated.  So here is what we do:
69649**
69650** The first time this routine is called, we code an OP_Goto that
69651** will jump to a subroutine at the end of the program.  Then we
69652** record every database that needs its schema verified in the
69653** pParse->cookieMask field.  Later, after all other code has been
69654** generated, the subroutine that does the cookie verifications and
69655** starts the transactions will be coded and the OP_Goto P2 value
69656** will be made to point to that subroutine.  The generation of the
69657** cookie verification subroutine code happens in sqlite3FinishCoding().
69658**
69659** If iDb<0 then code the OP_Goto only - don't set flag to verify the
69660** schema on any databases.  This can be used to position the OP_Goto
69661** early in the code, before we know if any database tables will be used.
69662*/
69663SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
69664  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69665
69666  if( pToplevel->cookieGoto==0 ){
69667    Vdbe *v = sqlite3GetVdbe(pToplevel);
69668    if( v==0 ) return;  /* This only happens if there was a prior error */
69669    pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
69670  }
69671  if( iDb>=0 ){
69672    sqlite3 *db = pToplevel->db;
69673    int mask;
69674
69675    assert( iDb<db->nDb );
69676    assert( db->aDb[iDb].pBt!=0 || iDb==1 );
69677    assert( iDb<SQLITE_MAX_ATTACHED+2 );
69678    mask = 1<<iDb;
69679    if( (pToplevel->cookieMask & mask)==0 ){
69680      pToplevel->cookieMask |= mask;
69681      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
69682      if( !OMIT_TEMPDB && iDb==1 ){
69683        sqlite3OpenTempDatabase(pToplevel);
69684      }
69685    }
69686  }
69687}
69688
69689/*
69690** Generate VDBE code that prepares for doing an operation that
69691** might change the database.
69692**
69693** This routine starts a new transaction if we are not already within
69694** a transaction.  If we are already within a transaction, then a checkpoint
69695** is set if the setStatement parameter is true.  A checkpoint should
69696** be set for operations that might fail (due to a constraint) part of
69697** the way through and which will need to undo some writes without having to
69698** rollback the whole transaction.  For operations where all constraints
69699** can be checked before any changes are made to the database, it is never
69700** necessary to undo a write and the checkpoint should not be set.
69701*/
69702SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
69703  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69704  sqlite3CodeVerifySchema(pParse, iDb);
69705  pToplevel->writeMask |= 1<<iDb;
69706  pToplevel->isMultiWrite |= setStatement;
69707}
69708
69709/*
69710** Indicate that the statement currently under construction might write
69711** more than one entry (example: deleting one row then inserting another,
69712** inserting multiple rows in a table, or inserting a row and index entries.)
69713** If an abort occurs after some of these writes have completed, then it will
69714** be necessary to undo the completed writes.
69715*/
69716SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
69717  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69718  pToplevel->isMultiWrite = 1;
69719}
69720
69721/*
69722** The code generator calls this routine if is discovers that it is
69723** possible to abort a statement prior to completion.  In order to
69724** perform this abort without corrupting the database, we need to make
69725** sure that the statement is protected by a statement transaction.
69726**
69727** Technically, we only need to set the mayAbort flag if the
69728** isMultiWrite flag was previously set.  There is a time dependency
69729** such that the abort must occur after the multiwrite.  This makes
69730** some statements involving the REPLACE conflict resolution algorithm
69731** go a little faster.  But taking advantage of this time dependency
69732** makes it more difficult to prove that the code is correct (in
69733** particular, it prevents us from writing an effective
69734** implementation of sqlite3AssertMayAbort()) and so we have chosen
69735** to take the safe route and skip the optimization.
69736*/
69737SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
69738  Parse *pToplevel = sqlite3ParseToplevel(pParse);
69739  pToplevel->mayAbort = 1;
69740}
69741
69742/*
69743** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
69744** error. The onError parameter determines which (if any) of the statement
69745** and/or current transaction is rolled back.
69746*/
69747SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
69748  Vdbe *v = sqlite3GetVdbe(pParse);
69749  if( onError==OE_Abort ){
69750    sqlite3MayAbort(pParse);
69751  }
69752  sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
69753}
69754
69755/*
69756** Check to see if pIndex uses the collating sequence pColl.  Return
69757** true if it does and false if it does not.
69758*/
69759#ifndef SQLITE_OMIT_REINDEX
69760static int collationMatch(const char *zColl, Index *pIndex){
69761  int i;
69762  assert( zColl!=0 );
69763  for(i=0; i<pIndex->nColumn; i++){
69764    const char *z = pIndex->azColl[i];
69765    assert( z!=0 );
69766    if( 0==sqlite3StrICmp(z, zColl) ){
69767      return 1;
69768    }
69769  }
69770  return 0;
69771}
69772#endif
69773
69774/*
69775** Recompute all indices of pTab that use the collating sequence pColl.
69776** If pColl==0 then recompute all indices of pTab.
69777*/
69778#ifndef SQLITE_OMIT_REINDEX
69779static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
69780  Index *pIndex;              /* An index associated with pTab */
69781
69782  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
69783    if( zColl==0 || collationMatch(zColl, pIndex) ){
69784      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
69785      sqlite3BeginWriteOperation(pParse, 0, iDb);
69786      sqlite3RefillIndex(pParse, pIndex, -1);
69787    }
69788  }
69789}
69790#endif
69791
69792/*
69793** Recompute all indices of all tables in all databases where the
69794** indices use the collating sequence pColl.  If pColl==0 then recompute
69795** all indices everywhere.
69796*/
69797#ifndef SQLITE_OMIT_REINDEX
69798static void reindexDatabases(Parse *pParse, char const *zColl){
69799  Db *pDb;                    /* A single database */
69800  int iDb;                    /* The database index number */
69801  sqlite3 *db = pParse->db;   /* The database connection */
69802  HashElem *k;                /* For looping over tables in pDb */
69803  Table *pTab;                /* A table in the database */
69804
69805  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
69806    assert( pDb!=0 );
69807    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
69808      pTab = (Table*)sqliteHashData(k);
69809      reindexTable(pParse, pTab, zColl);
69810    }
69811  }
69812}
69813#endif
69814
69815/*
69816** Generate code for the REINDEX command.
69817**
69818**        REINDEX                            -- 1
69819**        REINDEX  <collation>               -- 2
69820**        REINDEX  ?<database>.?<tablename>  -- 3
69821**        REINDEX  ?<database>.?<indexname>  -- 4
69822**
69823** Form 1 causes all indices in all attached databases to be rebuilt.
69824** Form 2 rebuilds all indices in all databases that use the named
69825** collating function.  Forms 3 and 4 rebuild the named index or all
69826** indices associated with the named table.
69827*/
69828#ifndef SQLITE_OMIT_REINDEX
69829SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
69830  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
69831  char *z;                    /* Name of a table or index */
69832  const char *zDb;            /* Name of the database */
69833  Table *pTab;                /* A table in the database */
69834  Index *pIndex;              /* An index associated with pTab */
69835  int iDb;                    /* The database index number */
69836  sqlite3 *db = pParse->db;   /* The database connection */
69837  Token *pObjName;            /* Name of the table or index to be reindexed */
69838
69839  /* Read the database schema. If an error occurs, leave an error message
69840  ** and code in pParse and return NULL. */
69841  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
69842    return;
69843  }
69844
69845  if( pName1==0 ){
69846    reindexDatabases(pParse, 0);
69847    return;
69848  }else if( NEVER(pName2==0) || pName2->z==0 ){
69849    char *zColl;
69850    assert( pName1->z );
69851    zColl = sqlite3NameFromToken(pParse->db, pName1);
69852    if( !zColl ) return;
69853    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
69854    if( pColl ){
69855      reindexDatabases(pParse, zColl);
69856      sqlite3DbFree(db, zColl);
69857      return;
69858    }
69859    sqlite3DbFree(db, zColl);
69860  }
69861  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
69862  if( iDb<0 ) return;
69863  z = sqlite3NameFromToken(db, pObjName);
69864  if( z==0 ) return;
69865  zDb = db->aDb[iDb].zName;
69866  pTab = sqlite3FindTable(db, z, zDb);
69867  if( pTab ){
69868    reindexTable(pParse, pTab, 0);
69869    sqlite3DbFree(db, z);
69870    return;
69871  }
69872  pIndex = sqlite3FindIndex(db, z, zDb);
69873  sqlite3DbFree(db, z);
69874  if( pIndex ){
69875    sqlite3BeginWriteOperation(pParse, 0, iDb);
69876    sqlite3RefillIndex(pParse, pIndex, -1);
69877    return;
69878  }
69879  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
69880}
69881#endif
69882
69883/*
69884** Return a dynamicly allocated KeyInfo structure that can be used
69885** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
69886**
69887** If successful, a pointer to the new structure is returned. In this case
69888** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
69889** pointer. If an error occurs (out of memory or missing collation
69890** sequence), NULL is returned and the state of pParse updated to reflect
69891** the error.
69892*/
69893SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
69894  int i;
69895  int nCol = pIdx->nColumn;
69896  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
69897  sqlite3 *db = pParse->db;
69898  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
69899
69900  if( pKey ){
69901    pKey->db = pParse->db;
69902    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
69903    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
69904    for(i=0; i<nCol; i++){
69905      char *zColl = pIdx->azColl[i];
69906      assert( zColl );
69907      pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
69908      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
69909    }
69910    pKey->nField = (u16)nCol;
69911  }
69912
69913  if( pParse->nErr ){
69914    sqlite3DbFree(db, pKey);
69915    pKey = 0;
69916  }
69917  return pKey;
69918}
69919
69920/************** End of build.c ***********************************************/
69921/************** Begin file callback.c ****************************************/
69922/*
69923** 2005 May 23
69924**
69925** The author disclaims copyright to this source code.  In place of
69926** a legal notice, here is a blessing:
69927**
69928**    May you do good and not evil.
69929**    May you find forgiveness for yourself and forgive others.
69930**    May you share freely, never taking more than you give.
69931**
69932*************************************************************************
69933**
69934** This file contains functions used to access the internal hash tables
69935** of user defined functions and collation sequences.
69936*/
69937
69938
69939/*
69940** Invoke the 'collation needed' callback to request a collation sequence
69941** in the encoding enc of name zName, length nName.
69942*/
69943static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
69944  assert( !db->xCollNeeded || !db->xCollNeeded16 );
69945  if( db->xCollNeeded ){
69946    char *zExternal = sqlite3DbStrDup(db, zName);
69947    if( !zExternal ) return;
69948    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
69949    sqlite3DbFree(db, zExternal);
69950  }
69951#ifndef SQLITE_OMIT_UTF16
69952  if( db->xCollNeeded16 ){
69953    char const *zExternal;
69954    sqlite3_value *pTmp = sqlite3ValueNew(db);
69955    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
69956    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
69957    if( zExternal ){
69958      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
69959    }
69960    sqlite3ValueFree(pTmp);
69961  }
69962#endif
69963}
69964
69965/*
69966** This routine is called if the collation factory fails to deliver a
69967** collation function in the best encoding but there may be other versions
69968** of this collation function (for other text encodings) available. Use one
69969** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
69970** possible.
69971*/
69972static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
69973  CollSeq *pColl2;
69974  char *z = pColl->zName;
69975  int i;
69976  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
69977  for(i=0; i<3; i++){
69978    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
69979    if( pColl2->xCmp!=0 ){
69980      memcpy(pColl, pColl2, sizeof(CollSeq));
69981      pColl->xDel = 0;         /* Do not copy the destructor */
69982      return SQLITE_OK;
69983    }
69984  }
69985  return SQLITE_ERROR;
69986}
69987
69988/*
69989** This function is responsible for invoking the collation factory callback
69990** or substituting a collation sequence of a different encoding when the
69991** requested collation sequence is not available in the desired encoding.
69992**
69993** If it is not NULL, then pColl must point to the database native encoding
69994** collation sequence with name zName, length nName.
69995**
69996** The return value is either the collation sequence to be used in database
69997** db for collation type name zName, length nName, or NULL, if no collation
69998** sequence can be found.
69999**
70000** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
70001*/
70002SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
70003  sqlite3* db,          /* The database connection */
70004  u8 enc,               /* The desired encoding for the collating sequence */
70005  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
70006  const char *zName     /* Collating sequence name */
70007){
70008  CollSeq *p;
70009
70010  p = pColl;
70011  if( !p ){
70012    p = sqlite3FindCollSeq(db, enc, zName, 0);
70013  }
70014  if( !p || !p->xCmp ){
70015    /* No collation sequence of this type for this encoding is registered.
70016    ** Call the collation factory to see if it can supply us with one.
70017    */
70018    callCollNeeded(db, enc, zName);
70019    p = sqlite3FindCollSeq(db, enc, zName, 0);
70020  }
70021  if( p && !p->xCmp && synthCollSeq(db, p) ){
70022    p = 0;
70023  }
70024  assert( !p || p->xCmp );
70025  return p;
70026}
70027
70028/*
70029** This routine is called on a collation sequence before it is used to
70030** check that it is defined. An undefined collation sequence exists when
70031** a database is loaded that contains references to collation sequences
70032** that have not been defined by sqlite3_create_collation() etc.
70033**
70034** If required, this routine calls the 'collation needed' callback to
70035** request a definition of the collating sequence. If this doesn't work,
70036** an equivalent collating sequence that uses a text encoding different
70037** from the main database is substituted, if one is available.
70038*/
70039SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
70040  if( pColl ){
70041    const char *zName = pColl->zName;
70042    sqlite3 *db = pParse->db;
70043    CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
70044    if( !p ){
70045      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
70046      pParse->nErr++;
70047      return SQLITE_ERROR;
70048    }
70049    assert( p==pColl );
70050  }
70051  return SQLITE_OK;
70052}
70053
70054
70055
70056/*
70057** Locate and return an entry from the db.aCollSeq hash table. If the entry
70058** specified by zName and nName is not found and parameter 'create' is
70059** true, then create a new entry. Otherwise return NULL.
70060**
70061** Each pointer stored in the sqlite3.aCollSeq hash table contains an
70062** array of three CollSeq structures. The first is the collation sequence
70063** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
70064**
70065** Stored immediately after the three collation sequences is a copy of
70066** the collation sequence name. A pointer to this string is stored in
70067** each collation sequence structure.
70068*/
70069static CollSeq *findCollSeqEntry(
70070  sqlite3 *db,          /* Database connection */
70071  const char *zName,    /* Name of the collating sequence */
70072  int create            /* Create a new entry if true */
70073){
70074  CollSeq *pColl;
70075  int nName = sqlite3Strlen30(zName);
70076  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
70077
70078  if( 0==pColl && create ){
70079    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
70080    if( pColl ){
70081      CollSeq *pDel = 0;
70082      pColl[0].zName = (char*)&pColl[3];
70083      pColl[0].enc = SQLITE_UTF8;
70084      pColl[1].zName = (char*)&pColl[3];
70085      pColl[1].enc = SQLITE_UTF16LE;
70086      pColl[2].zName = (char*)&pColl[3];
70087      pColl[2].enc = SQLITE_UTF16BE;
70088      memcpy(pColl[0].zName, zName, nName);
70089      pColl[0].zName[nName] = 0;
70090      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
70091
70092      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
70093      ** return the pColl pointer to be deleted (because it wasn't added
70094      ** to the hash table).
70095      */
70096      assert( pDel==0 || pDel==pColl );
70097      if( pDel!=0 ){
70098        db->mallocFailed = 1;
70099        sqlite3DbFree(db, pDel);
70100        pColl = 0;
70101      }
70102    }
70103  }
70104  return pColl;
70105}
70106
70107/*
70108** Parameter zName points to a UTF-8 encoded string nName bytes long.
70109** Return the CollSeq* pointer for the collation sequence named zName
70110** for the encoding 'enc' from the database 'db'.
70111**
70112** If the entry specified is not found and 'create' is true, then create a
70113** new entry.  Otherwise return NULL.
70114**
70115** A separate function sqlite3LocateCollSeq() is a wrapper around
70116** this routine.  sqlite3LocateCollSeq() invokes the collation factory
70117** if necessary and generates an error message if the collating sequence
70118** cannot be found.
70119**
70120** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
70121*/
70122SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
70123  sqlite3 *db,
70124  u8 enc,
70125  const char *zName,
70126  int create
70127){
70128  CollSeq *pColl;
70129  if( zName ){
70130    pColl = findCollSeqEntry(db, zName, create);
70131  }else{
70132    pColl = db->pDfltColl;
70133  }
70134  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
70135  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
70136  if( pColl ) pColl += enc-1;
70137  return pColl;
70138}
70139
70140/* During the search for the best function definition, this procedure
70141** is called to test how well the function passed as the first argument
70142** matches the request for a function with nArg arguments in a system
70143** that uses encoding enc. The value returned indicates how well the
70144** request is matched. A higher value indicates a better match.
70145**
70146** The returned value is always between 0 and 6, as follows:
70147**
70148** 0: Not a match, or if nArg<0 and the function is has no implementation.
70149** 1: A variable arguments function that prefers UTF-8 when a UTF-16
70150**    encoding is requested, or vice versa.
70151** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
70152**    requested, or vice versa.
70153** 3: A variable arguments function using the same text encoding.
70154** 4: A function with the exact number of arguments requested that
70155**    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
70156** 5: A function with the exact number of arguments requested that
70157**    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
70158** 6: An exact match.
70159**
70160*/
70161static int matchQuality(FuncDef *p, int nArg, u8 enc){
70162  int match = 0;
70163  if( p->nArg==-1 || p->nArg==nArg
70164   || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
70165  ){
70166    match = 1;
70167    if( p->nArg==nArg || nArg==-1 ){
70168      match = 4;
70169    }
70170    if( enc==p->iPrefEnc ){
70171      match += 2;
70172    }
70173    else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
70174             (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
70175      match += 1;
70176    }
70177  }
70178  return match;
70179}
70180
70181/*
70182** Search a FuncDefHash for a function with the given name.  Return
70183** a pointer to the matching FuncDef if found, or 0 if there is no match.
70184*/
70185static FuncDef *functionSearch(
70186  FuncDefHash *pHash,  /* Hash table to search */
70187  int h,               /* Hash of the name */
70188  const char *zFunc,   /* Name of function */
70189  int nFunc            /* Number of bytes in zFunc */
70190){
70191  FuncDef *p;
70192  for(p=pHash->a[h]; p; p=p->pHash){
70193    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
70194      return p;
70195    }
70196  }
70197  return 0;
70198}
70199
70200/*
70201** Insert a new FuncDef into a FuncDefHash hash table.
70202*/
70203SQLITE_PRIVATE void sqlite3FuncDefInsert(
70204  FuncDefHash *pHash,  /* The hash table into which to insert */
70205  FuncDef *pDef        /* The function definition to insert */
70206){
70207  FuncDef *pOther;
70208  int nName = sqlite3Strlen30(pDef->zName);
70209  u8 c1 = (u8)pDef->zName[0];
70210  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
70211  pOther = functionSearch(pHash, h, pDef->zName, nName);
70212  if( pOther ){
70213    assert( pOther!=pDef && pOther->pNext!=pDef );
70214    pDef->pNext = pOther->pNext;
70215    pOther->pNext = pDef;
70216  }else{
70217    pDef->pNext = 0;
70218    pDef->pHash = pHash->a[h];
70219    pHash->a[h] = pDef;
70220  }
70221}
70222
70223
70224
70225/*
70226** Locate a user function given a name, a number of arguments and a flag
70227** indicating whether the function prefers UTF-16 over UTF-8.  Return a
70228** pointer to the FuncDef structure that defines that function, or return
70229** NULL if the function does not exist.
70230**
70231** If the createFlag argument is true, then a new (blank) FuncDef
70232** structure is created and liked into the "db" structure if a
70233** no matching function previously existed.  When createFlag is true
70234** and the nArg parameter is -1, then only a function that accepts
70235** any number of arguments will be returned.
70236**
70237** If createFlag is false and nArg is -1, then the first valid
70238** function found is returned.  A function is valid if either xFunc
70239** or xStep is non-zero.
70240**
70241** If createFlag is false, then a function with the required name and
70242** number of arguments may be returned even if the eTextRep flag does not
70243** match that requested.
70244*/
70245SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
70246  sqlite3 *db,       /* An open database */
70247  const char *zName, /* Name of the function.  Not null-terminated */
70248  int nName,         /* Number of characters in the name */
70249  int nArg,          /* Number of arguments.  -1 means any number */
70250  u8 enc,            /* Preferred text encoding */
70251  int createFlag     /* Create new entry if true and does not otherwise exist */
70252){
70253  FuncDef *p;         /* Iterator variable */
70254  FuncDef *pBest = 0; /* Best match found so far */
70255  int bestScore = 0;  /* Score of best match */
70256  int h;              /* Hash value */
70257
70258
70259  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
70260  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
70261
70262  /* First search for a match amongst the application-defined functions.
70263  */
70264  p = functionSearch(&db->aFunc, h, zName, nName);
70265  while( p ){
70266    int score = matchQuality(p, nArg, enc);
70267    if( score>bestScore ){
70268      pBest = p;
70269      bestScore = score;
70270    }
70271    p = p->pNext;
70272  }
70273
70274  /* If no match is found, search the built-in functions.
70275  **
70276  ** Except, if createFlag is true, that means that we are trying to
70277  ** install a new function.  Whatever FuncDef structure is returned will
70278  ** have fields overwritten with new information appropriate for the
70279  ** new function.  But the FuncDefs for built-in functions are read-only.
70280  ** So we must not search for built-ins when creating a new function.
70281  */
70282  if( !createFlag && !pBest ){
70283    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
70284    p = functionSearch(pHash, h, zName, nName);
70285    while( p ){
70286      int score = matchQuality(p, nArg, enc);
70287      if( score>bestScore ){
70288        pBest = p;
70289        bestScore = score;
70290      }
70291      p = p->pNext;
70292    }
70293  }
70294
70295  /* If the createFlag parameter is true and the search did not reveal an
70296  ** exact match for the name, number of arguments and encoding, then add a
70297  ** new entry to the hash table and return it.
70298  */
70299  if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
70300      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
70301    pBest->zName = (char *)&pBest[1];
70302    pBest->nArg = (u16)nArg;
70303    pBest->iPrefEnc = enc;
70304    memcpy(pBest->zName, zName, nName);
70305    pBest->zName[nName] = 0;
70306    sqlite3FuncDefInsert(&db->aFunc, pBest);
70307  }
70308
70309  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
70310    return pBest;
70311  }
70312  return 0;
70313}
70314
70315/*
70316** Free all resources held by the schema structure. The void* argument points
70317** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
70318** pointer itself, it just cleans up subsiduary resources (i.e. the contents
70319** of the schema hash tables).
70320**
70321** The Schema.cache_size variable is not cleared.
70322*/
70323SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
70324  Hash temp1;
70325  Hash temp2;
70326  HashElem *pElem;
70327  Schema *pSchema = (Schema *)p;
70328
70329  temp1 = pSchema->tblHash;
70330  temp2 = pSchema->trigHash;
70331  sqlite3HashInit(&pSchema->trigHash);
70332  sqlite3HashClear(&pSchema->idxHash);
70333  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
70334    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
70335  }
70336  sqlite3HashClear(&temp2);
70337  sqlite3HashInit(&pSchema->tblHash);
70338  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
70339    Table *pTab = sqliteHashData(pElem);
70340    assert( pTab->dbMem==0 );
70341    sqlite3DeleteTable(pTab);
70342  }
70343  sqlite3HashClear(&temp1);
70344  sqlite3HashClear(&pSchema->fkeyHash);
70345  pSchema->pSeqTab = 0;
70346  pSchema->flags &= ~DB_SchemaLoaded;
70347}
70348
70349/*
70350** Find and return the schema associated with a BTree.  Create
70351** a new one if necessary.
70352*/
70353SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
70354  Schema * p;
70355  if( pBt ){
70356    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
70357  }else{
70358    p = (Schema *)sqlite3MallocZero(sizeof(Schema));
70359  }
70360  if( !p ){
70361    db->mallocFailed = 1;
70362  }else if ( 0==p->file_format ){
70363    sqlite3HashInit(&p->tblHash);
70364    sqlite3HashInit(&p->idxHash);
70365    sqlite3HashInit(&p->trigHash);
70366    sqlite3HashInit(&p->fkeyHash);
70367    p->enc = SQLITE_UTF8;
70368  }
70369  return p;
70370}
70371
70372/************** End of callback.c ********************************************/
70373/************** Begin file delete.c ******************************************/
70374/*
70375** 2001 September 15
70376**
70377** The author disclaims copyright to this source code.  In place of
70378** a legal notice, here is a blessing:
70379**
70380**    May you do good and not evil.
70381**    May you find forgiveness for yourself and forgive others.
70382**    May you share freely, never taking more than you give.
70383**
70384*************************************************************************
70385** This file contains C code routines that are called by the parser
70386** in order to generate code for DELETE FROM statements.
70387*/
70388
70389/*
70390** Look up every table that is named in pSrc.  If any table is not found,
70391** add an error message to pParse->zErrMsg and return NULL.  If all tables
70392** are found, return a pointer to the last table.
70393*/
70394SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
70395  struct SrcList_item *pItem = pSrc->a;
70396  Table *pTab;
70397  assert( pItem && pSrc->nSrc==1 );
70398  pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
70399  sqlite3DeleteTable(pItem->pTab);
70400  pItem->pTab = pTab;
70401  if( pTab ){
70402    pTab->nRef++;
70403  }
70404  if( sqlite3IndexedByLookup(pParse, pItem) ){
70405    pTab = 0;
70406  }
70407  return pTab;
70408}
70409
70410/*
70411** Check to make sure the given table is writable.  If it is not
70412** writable, generate an error message and return 1.  If it is
70413** writable return 0;
70414*/
70415SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
70416  /* A table is not writable under the following circumstances:
70417  **
70418  **   1) It is a virtual table and no implementation of the xUpdate method
70419  **      has been provided, or
70420  **   2) It is a system table (i.e. sqlite_master), this call is not
70421  **      part of a nested parse and writable_schema pragma has not
70422  **      been specified.
70423  **
70424  ** In either case leave an error message in pParse and return non-zero.
70425  */
70426  if( ( IsVirtual(pTab)
70427     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
70428   || ( (pTab->tabFlags & TF_Readonly)!=0
70429     && (pParse->db->flags & SQLITE_WriteSchema)==0
70430     && pParse->nested==0 )
70431  ){
70432    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
70433    return 1;
70434  }
70435
70436#ifndef SQLITE_OMIT_VIEW
70437  if( !viewOk && pTab->pSelect ){
70438    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
70439    return 1;
70440  }
70441#endif
70442  return 0;
70443}
70444
70445
70446#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
70447/*
70448** Evaluate a view and store its result in an ephemeral table.  The
70449** pWhere argument is an optional WHERE clause that restricts the
70450** set of rows in the view that are to be added to the ephemeral table.
70451*/
70452SQLITE_PRIVATE void sqlite3MaterializeView(
70453  Parse *pParse,       /* Parsing context */
70454  Table *pView,        /* View definition */
70455  Expr *pWhere,        /* Optional WHERE clause to be added */
70456  int iCur             /* Cursor number for ephemerial table */
70457){
70458  SelectDest dest;
70459  Select *pDup;
70460  sqlite3 *db = pParse->db;
70461
70462  pDup = sqlite3SelectDup(db, pView->pSelect, 0);
70463  if( pWhere ){
70464    SrcList *pFrom;
70465
70466    pWhere = sqlite3ExprDup(db, pWhere, 0);
70467    pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
70468    if( pFrom ){
70469      assert( pFrom->nSrc==1 );
70470      pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
70471      pFrom->a[0].pSelect = pDup;
70472      assert( pFrom->a[0].pOn==0 );
70473      assert( pFrom->a[0].pUsing==0 );
70474    }else{
70475      sqlite3SelectDelete(db, pDup);
70476    }
70477    pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
70478  }
70479  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
70480  sqlite3Select(pParse, pDup, &dest);
70481  sqlite3SelectDelete(db, pDup);
70482}
70483#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
70484
70485#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
70486/*
70487** Generate an expression tree to implement the WHERE, ORDER BY,
70488** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
70489**
70490**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
70491**                            \__________________________/
70492**                               pLimitWhere (pInClause)
70493*/
70494SQLITE_PRIVATE Expr *sqlite3LimitWhere(
70495  Parse *pParse,               /* The parser context */
70496  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
70497  Expr *pWhere,                /* The WHERE clause.  May be null */
70498  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
70499  Expr *pLimit,                /* The LIMIT clause.  May be null */
70500  Expr *pOffset,               /* The OFFSET clause.  May be null */
70501  char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
70502){
70503  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
70504  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
70505  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
70506  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
70507  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
70508  Select *pSelect = NULL;      /* Complete SELECT tree */
70509
70510  /* Check that there isn't an ORDER BY without a LIMIT clause.
70511  */
70512  if( pOrderBy && (pLimit == 0) ) {
70513    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
70514    pParse->parseError = 1;
70515    goto limit_where_cleanup_2;
70516  }
70517
70518  /* We only need to generate a select expression if there
70519  ** is a limit/offset term to enforce.
70520  */
70521  if( pLimit == 0 ) {
70522    /* if pLimit is null, pOffset will always be null as well. */
70523    assert( pOffset == 0 );
70524    return pWhere;
70525  }
70526
70527  /* Generate a select expression tree to enforce the limit/offset
70528  ** term for the DELETE or UPDATE statement.  For example:
70529  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
70530  ** becomes:
70531  **   DELETE FROM table_a WHERE rowid IN (
70532  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
70533  **   );
70534  */
70535
70536  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
70537  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
70538  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
70539  if( pEList == 0 ) goto limit_where_cleanup_2;
70540
70541  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
70542  ** and the SELECT subtree. */
70543  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
70544  if( pSelectSrc == 0 ) {
70545    sqlite3ExprListDelete(pParse->db, pEList);
70546    goto limit_where_cleanup_2;
70547  }
70548
70549  /* generate the SELECT expression tree. */
70550  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
70551                             pOrderBy,0,pLimit,pOffset);
70552  if( pSelect == 0 ) return 0;
70553
70554  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
70555  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
70556  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
70557  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
70558  if( pInClause == 0 ) goto limit_where_cleanup_1;
70559
70560  pInClause->x.pSelect = pSelect;
70561  pInClause->flags |= EP_xIsSelect;
70562  sqlite3ExprSetHeight(pParse, pInClause);
70563  return pInClause;
70564
70565  /* something went wrong. clean up anything allocated. */
70566limit_where_cleanup_1:
70567  sqlite3SelectDelete(pParse->db, pSelect);
70568  return 0;
70569
70570limit_where_cleanup_2:
70571  sqlite3ExprDelete(pParse->db, pWhere);
70572  sqlite3ExprListDelete(pParse->db, pOrderBy);
70573  sqlite3ExprDelete(pParse->db, pLimit);
70574  sqlite3ExprDelete(pParse->db, pOffset);
70575  return 0;
70576}
70577#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
70578
70579/*
70580** Generate code for a DELETE FROM statement.
70581**
70582**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
70583**                 \________/       \________________/
70584**                  pTabList              pWhere
70585*/
70586SQLITE_PRIVATE void sqlite3DeleteFrom(
70587  Parse *pParse,         /* The parser context */
70588  SrcList *pTabList,     /* The table from which we should delete things */
70589  Expr *pWhere           /* The WHERE clause.  May be null */
70590){
70591  Vdbe *v;               /* The virtual database engine */
70592  Table *pTab;           /* The table from which records will be deleted */
70593  const char *zDb;       /* Name of database holding pTab */
70594  int end, addr = 0;     /* A couple addresses of generated code */
70595  int i;                 /* Loop counter */
70596  WhereInfo *pWInfo;     /* Information about the WHERE clause */
70597  Index *pIdx;           /* For looping over indices of the table */
70598  int iCur;              /* VDBE Cursor number for pTab */
70599  sqlite3 *db;           /* Main database structure */
70600  AuthContext sContext;  /* Authorization context */
70601  NameContext sNC;       /* Name context to resolve expressions in */
70602  int iDb;               /* Database number */
70603  int memCnt = -1;       /* Memory cell used for change counting */
70604  int rcauth;            /* Value returned by authorization callback */
70605
70606#ifndef SQLITE_OMIT_TRIGGER
70607  int isView;                  /* True if attempting to delete from a view */
70608  Trigger *pTrigger;           /* List of table triggers, if required */
70609#endif
70610
70611  memset(&sContext, 0, sizeof(sContext));
70612  db = pParse->db;
70613  if( pParse->nErr || db->mallocFailed ){
70614    goto delete_from_cleanup;
70615  }
70616  assert( pTabList->nSrc==1 );
70617
70618  /* Locate the table which we want to delete.  This table has to be
70619  ** put in an SrcList structure because some of the subroutines we
70620  ** will be calling are designed to work with multiple tables and expect
70621  ** an SrcList* parameter instead of just a Table* parameter.
70622  */
70623  pTab = sqlite3SrcListLookup(pParse, pTabList);
70624  if( pTab==0 )  goto delete_from_cleanup;
70625
70626  /* Figure out if we have any triggers and if the table being
70627  ** deleted from is a view
70628  */
70629#ifndef SQLITE_OMIT_TRIGGER
70630  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
70631  isView = pTab->pSelect!=0;
70632#else
70633# define pTrigger 0
70634# define isView 0
70635#endif
70636#ifdef SQLITE_OMIT_VIEW
70637# undef isView
70638# define isView 0
70639#endif
70640
70641  /* If pTab is really a view, make sure it has been initialized.
70642  */
70643  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
70644    goto delete_from_cleanup;
70645  }
70646
70647  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
70648    goto delete_from_cleanup;
70649  }
70650  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
70651  assert( iDb<db->nDb );
70652  zDb = db->aDb[iDb].zName;
70653  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
70654  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
70655  if( rcauth==SQLITE_DENY ){
70656    goto delete_from_cleanup;
70657  }
70658  assert(!isView || pTrigger);
70659
70660  /* Assign  cursor number to the table and all its indices.
70661  */
70662  assert( pTabList->nSrc==1 );
70663  iCur = pTabList->a[0].iCursor = pParse->nTab++;
70664  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70665    pParse->nTab++;
70666  }
70667
70668  /* Start the view context
70669  */
70670  if( isView ){
70671    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
70672  }
70673
70674  /* Begin generating code.
70675  */
70676  v = sqlite3GetVdbe(pParse);
70677  if( v==0 ){
70678    goto delete_from_cleanup;
70679  }
70680  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
70681  sqlite3BeginWriteOperation(pParse, 1, iDb);
70682
70683  /* If we are trying to delete from a view, realize that view into
70684  ** a ephemeral table.
70685  */
70686#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
70687  if( isView ){
70688    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
70689  }
70690#endif
70691
70692  /* Resolve the column names in the WHERE clause.
70693  */
70694  memset(&sNC, 0, sizeof(sNC));
70695  sNC.pParse = pParse;
70696  sNC.pSrcList = pTabList;
70697  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
70698    goto delete_from_cleanup;
70699  }
70700
70701  /* Initialize the counter of the number of rows deleted, if
70702  ** we are counting rows.
70703  */
70704  if( db->flags & SQLITE_CountRows ){
70705    memCnt = ++pParse->nMem;
70706    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
70707  }
70708
70709#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
70710  /* Special case: A DELETE without a WHERE clause deletes everything.
70711  ** It is easier just to erase the whole table. Prior to version 3.6.5,
70712  ** this optimization caused the row change count (the value returned by
70713  ** API function sqlite3_count_changes) to be set incorrectly.  */
70714  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
70715   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
70716  ){
70717    assert( !isView );
70718    sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
70719                      pTab->zName, P4_STATIC);
70720    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70721      assert( pIdx->pSchema==pTab->pSchema );
70722      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
70723    }
70724  }else
70725#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
70726  /* The usual case: There is a WHERE clause so we have to scan through
70727  ** the table and pick which records to delete.
70728  */
70729  {
70730    int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
70731    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
70732    int regRowid;                   /* Actual register containing rowids */
70733
70734    /* Collect rowids of every row to be deleted.
70735    */
70736    sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
70737    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
70738    if( pWInfo==0 ) goto delete_from_cleanup;
70739    regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
70740    sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
70741    if( db->flags & SQLITE_CountRows ){
70742      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
70743    }
70744    sqlite3WhereEnd(pWInfo);
70745
70746    /* Delete every item whose key was written to the list during the
70747    ** database scan.  We have to delete items after the scan is complete
70748    ** because deleting an item can change the scan order.  */
70749    end = sqlite3VdbeMakeLabel(v);
70750
70751    /* Unless this is a view, open cursors for the table we are
70752    ** deleting from and all its indices. If this is a view, then the
70753    ** only effect this statement has is to fire the INSTEAD OF
70754    ** triggers.  */
70755    if( !isView ){
70756      sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
70757    }
70758
70759    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
70760
70761    /* Delete the row */
70762#ifndef SQLITE_OMIT_VIRTUALTABLE
70763    if( IsVirtual(pTab) ){
70764      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
70765      sqlite3VtabMakeWritable(pParse, pTab);
70766      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
70767      sqlite3MayAbort(pParse);
70768    }else
70769#endif
70770    {
70771      int count = (pParse->nested==0);    /* True to count changes */
70772      sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
70773    }
70774
70775    /* End of the delete loop */
70776    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
70777    sqlite3VdbeResolveLabel(v, end);
70778
70779    /* Close the cursors open on the table and its indexes. */
70780    if( !isView && !IsVirtual(pTab) ){
70781      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
70782        sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
70783      }
70784      sqlite3VdbeAddOp1(v, OP_Close, iCur);
70785    }
70786  }
70787
70788  /* Update the sqlite_sequence table by storing the content of the
70789  ** maximum rowid counter values recorded while inserting into
70790  ** autoincrement tables.
70791  */
70792  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
70793    sqlite3AutoincrementEnd(pParse);
70794  }
70795
70796  /* Return the number of rows that were deleted. If this routine is
70797  ** generating code because of a call to sqlite3NestedParse(), do not
70798  ** invoke the callback function.
70799  */
70800  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
70801    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
70802    sqlite3VdbeSetNumCols(v, 1);
70803    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
70804  }
70805
70806delete_from_cleanup:
70807  sqlite3AuthContextPop(&sContext);
70808  sqlite3SrcListDelete(db, pTabList);
70809  sqlite3ExprDelete(db, pWhere);
70810  return;
70811}
70812/* Make sure "isView" and other macros defined above are undefined. Otherwise
70813** thely may interfere with compilation of other functions in this file
70814** (or in another file, if this file becomes part of the amalgamation).  */
70815#ifdef isView
70816 #undef isView
70817#endif
70818#ifdef pTrigger
70819 #undef pTrigger
70820#endif
70821
70822/*
70823** This routine generates VDBE code that causes a single row of a
70824** single table to be deleted.
70825**
70826** The VDBE must be in a particular state when this routine is called.
70827** These are the requirements:
70828**
70829**   1.  A read/write cursor pointing to pTab, the table containing the row
70830**       to be deleted, must be opened as cursor number $iCur.
70831**
70832**   2.  Read/write cursors for all indices of pTab must be open as
70833**       cursor number base+i for the i-th index.
70834**
70835**   3.  The record number of the row to be deleted must be stored in
70836**       memory cell iRowid.
70837**
70838** This routine generates code to remove both the table record and all
70839** index entries that point to that record.
70840*/
70841SQLITE_PRIVATE void sqlite3GenerateRowDelete(
70842  Parse *pParse,     /* Parsing context */
70843  Table *pTab,       /* Table containing the row to be deleted */
70844  int iCur,          /* Cursor number for the table */
70845  int iRowid,        /* Memory cell that contains the rowid to delete */
70846  int count,         /* If non-zero, increment the row change counter */
70847  Trigger *pTrigger, /* List of triggers to (potentially) fire */
70848  int onconf         /* Default ON CONFLICT policy for triggers */
70849){
70850  Vdbe *v = pParse->pVdbe;        /* Vdbe */
70851  int iOld = 0;                   /* First register in OLD.* array */
70852  int iLabel;                     /* Label resolved to end of generated code */
70853
70854  /* Vdbe is guaranteed to have been allocated by this stage. */
70855  assert( v );
70856
70857  /* Seek cursor iCur to the row to delete. If this row no longer exists
70858  ** (this can happen if a trigger program has already deleted it), do
70859  ** not attempt to delete it or fire any DELETE triggers.  */
70860  iLabel = sqlite3VdbeMakeLabel(v);
70861  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
70862
70863  /* If there are any triggers to fire, allocate a range of registers to
70864  ** use for the old.* references in the triggers.  */
70865  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
70866    u32 mask;                     /* Mask of OLD.* columns in use */
70867    int iCol;                     /* Iterator used while populating OLD.* */
70868
70869    /* TODO: Could use temporary registers here. Also could attempt to
70870    ** avoid copying the contents of the rowid register.  */
70871    mask = sqlite3TriggerColmask(
70872        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
70873    );
70874    mask |= sqlite3FkOldmask(pParse, pTab);
70875    iOld = pParse->nMem+1;
70876    pParse->nMem += (1 + pTab->nCol);
70877
70878    /* Populate the OLD.* pseudo-table register array. These values will be
70879    ** used by any BEFORE and AFTER triggers that exist.  */
70880    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
70881    for(iCol=0; iCol<pTab->nCol; iCol++){
70882      if( mask==0xffffffff || mask&(1<<iCol) ){
70883        int iTarget = iOld + iCol + 1;
70884        sqlite3VdbeAddOp3(v, OP_Column, iCur, iCol, iTarget);
70885        sqlite3ColumnDefault(v, pTab, iCol, iTarget);
70886      }
70887    }
70888
70889    /* Invoke BEFORE DELETE trigger programs. */
70890    sqlite3CodeRowTrigger(pParse, pTrigger,
70891        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
70892    );
70893
70894    /* Seek the cursor to the row to be deleted again. It may be that
70895    ** the BEFORE triggers coded above have already removed the row
70896    ** being deleted. Do not attempt to delete the row a second time, and
70897    ** do not fire AFTER triggers.  */
70898    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
70899
70900    /* Do FK processing. This call checks that any FK constraints that
70901    ** refer to this table (i.e. constraints attached to other tables)
70902    ** are not violated by deleting this row.  */
70903    sqlite3FkCheck(pParse, pTab, iOld, 0);
70904  }
70905
70906  /* Delete the index and table entries. Skip this step if pTab is really
70907  ** a view (in which case the only effect of the DELETE statement is to
70908  ** fire the INSTEAD OF triggers).  */
70909  if( pTab->pSelect==0 ){
70910    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
70911    sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
70912    if( count ){
70913      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
70914    }
70915  }
70916
70917  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
70918  ** handle rows (possibly in other tables) that refer via a foreign key
70919  ** to the row just deleted. */
70920  sqlite3FkActions(pParse, pTab, 0, iOld);
70921
70922  /* Invoke AFTER DELETE trigger programs. */
70923  sqlite3CodeRowTrigger(pParse, pTrigger,
70924      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
70925  );
70926
70927  /* Jump here if the row had already been deleted before any BEFORE
70928  ** trigger programs were invoked. Or if a trigger program throws a
70929  ** RAISE(IGNORE) exception.  */
70930  sqlite3VdbeResolveLabel(v, iLabel);
70931}
70932
70933/*
70934** This routine generates VDBE code that causes the deletion of all
70935** index entries associated with a single row of a single table.
70936**
70937** The VDBE must be in a particular state when this routine is called.
70938** These are the requirements:
70939**
70940**   1.  A read/write cursor pointing to pTab, the table containing the row
70941**       to be deleted, must be opened as cursor number "iCur".
70942**
70943**   2.  Read/write cursors for all indices of pTab must be open as
70944**       cursor number iCur+i for the i-th index.
70945**
70946**   3.  The "iCur" cursor must be pointing to the row that is to be
70947**       deleted.
70948*/
70949SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
70950  Parse *pParse,     /* Parsing and code generating context */
70951  Table *pTab,       /* Table containing the row to be deleted */
70952  int iCur,          /* Cursor number for the table */
70953  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
70954){
70955  int i;
70956  Index *pIdx;
70957  int r1;
70958
70959  for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
70960    if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
70961    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
70962    sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
70963  }
70964}
70965
70966/*
70967** Generate code that will assemble an index key and put it in register
70968** regOut.  The key with be for index pIdx which is an index on pTab.
70969** iCur is the index of a cursor open on the pTab table and pointing to
70970** the entry that needs indexing.
70971**
70972** Return a register number which is the first in a block of
70973** registers that holds the elements of the index key.  The
70974** block of registers has already been deallocated by the time
70975** this routine returns.
70976*/
70977SQLITE_PRIVATE int sqlite3GenerateIndexKey(
70978  Parse *pParse,     /* Parsing context */
70979  Index *pIdx,       /* The index for which to generate a key */
70980  int iCur,          /* Cursor number for the pIdx->pTable table */
70981  int regOut,        /* Write the new index key to this register */
70982  int doMakeRec      /* Run the OP_MakeRecord instruction if true */
70983){
70984  Vdbe *v = pParse->pVdbe;
70985  int j;
70986  Table *pTab = pIdx->pTable;
70987  int regBase;
70988  int nCol;
70989
70990  nCol = pIdx->nColumn;
70991  regBase = sqlite3GetTempRange(pParse, nCol+1);
70992  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
70993  for(j=0; j<nCol; j++){
70994    int idx = pIdx->aiColumn[j];
70995    if( idx==pTab->iPKey ){
70996      sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
70997    }else{
70998      sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
70999      sqlite3ColumnDefault(v, pTab, idx, -1);
71000    }
71001  }
71002  if( doMakeRec ){
71003    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
71004    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
71005  }
71006  sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
71007  return regBase;
71008}
71009
71010/************** End of delete.c **********************************************/
71011/************** Begin file func.c ********************************************/
71012/*
71013** 2002 February 23
71014**
71015** The author disclaims copyright to this source code.  In place of
71016** a legal notice, here is a blessing:
71017**
71018**    May you do good and not evil.
71019**    May you find forgiveness for yourself and forgive others.
71020**    May you share freely, never taking more than you give.
71021**
71022*************************************************************************
71023** This file contains the C functions that implement various SQL
71024** functions of SQLite.
71025**
71026** There is only one exported symbol in this file - the function
71027** sqliteRegisterBuildinFunctions() found at the bottom of the file.
71028** All other code has file scope.
71029*/
71030
71031/*
71032** Return the collating function associated with a function.
71033*/
71034static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
71035  return context->pColl;
71036}
71037
71038/*
71039** Implementation of the non-aggregate min() and max() functions
71040*/
71041static void minmaxFunc(
71042  sqlite3_context *context,
71043  int argc,
71044  sqlite3_value **argv
71045){
71046  int i;
71047  int mask;    /* 0 for min() or 0xffffffff for max() */
71048  int iBest;
71049  CollSeq *pColl;
71050
71051  assert( argc>1 );
71052  mask = sqlite3_user_data(context)==0 ? 0 : -1;
71053  pColl = sqlite3GetFuncCollSeq(context);
71054  assert( pColl );
71055  assert( mask==-1 || mask==0 );
71056  iBest = 0;
71057  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
71058  for(i=1; i<argc; i++){
71059    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
71060    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
71061      testcase( mask==0 );
71062      iBest = i;
71063    }
71064  }
71065  sqlite3_result_value(context, argv[iBest]);
71066}
71067
71068/*
71069** Return the type of the argument.
71070*/
71071static void typeofFunc(
71072  sqlite3_context *context,
71073  int NotUsed,
71074  sqlite3_value **argv
71075){
71076  const char *z = 0;
71077  UNUSED_PARAMETER(NotUsed);
71078  switch( sqlite3_value_type(argv[0]) ){
71079    case SQLITE_INTEGER: z = "integer"; break;
71080    case SQLITE_TEXT:    z = "text";    break;
71081    case SQLITE_FLOAT:   z = "real";    break;
71082    case SQLITE_BLOB:    z = "blob";    break;
71083    default:             z = "null";    break;
71084  }
71085  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
71086}
71087
71088
71089/*
71090** Implementation of the length() function
71091*/
71092static void lengthFunc(
71093  sqlite3_context *context,
71094  int argc,
71095  sqlite3_value **argv
71096){
71097  int len;
71098
71099  assert( argc==1 );
71100  UNUSED_PARAMETER(argc);
71101  switch( sqlite3_value_type(argv[0]) ){
71102    case SQLITE_BLOB:
71103    case SQLITE_INTEGER:
71104    case SQLITE_FLOAT: {
71105      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
71106      break;
71107    }
71108    case SQLITE_TEXT: {
71109      const unsigned char *z = sqlite3_value_text(argv[0]);
71110      if( z==0 ) return;
71111      len = 0;
71112      while( *z ){
71113        len++;
71114        SQLITE_SKIP_UTF8(z);
71115      }
71116      sqlite3_result_int(context, len);
71117      break;
71118    }
71119    default: {
71120      sqlite3_result_null(context);
71121      break;
71122    }
71123  }
71124}
71125
71126/*
71127** Implementation of the abs() function.
71128**
71129** IMP: R-23979-26855 The abs(X) function returns the absolute value of
71130** the numeric argument X.
71131*/
71132static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71133  assert( argc==1 );
71134  UNUSED_PARAMETER(argc);
71135  switch( sqlite3_value_type(argv[0]) ){
71136    case SQLITE_INTEGER: {
71137      i64 iVal = sqlite3_value_int64(argv[0]);
71138      if( iVal<0 ){
71139        if( (iVal<<1)==0 ){
71140          /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
71141          ** abs(X) throws an integer overflow error since there is no
71142          ** equivalent positive 64-bit two complement value. */
71143          sqlite3_result_error(context, "integer overflow", -1);
71144          return;
71145        }
71146        iVal = -iVal;
71147      }
71148      sqlite3_result_int64(context, iVal);
71149      break;
71150    }
71151    case SQLITE_NULL: {
71152      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
71153      sqlite3_result_null(context);
71154      break;
71155    }
71156    default: {
71157      /* Because sqlite3_value_double() returns 0.0 if the argument is not
71158      ** something that can be converted into a number, we have:
71159      ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
71160      ** cannot be converted to a numeric value.
71161      */
71162      double rVal = sqlite3_value_double(argv[0]);
71163      if( rVal<0 ) rVal = -rVal;
71164      sqlite3_result_double(context, rVal);
71165      break;
71166    }
71167  }
71168}
71169
71170/*
71171** Implementation of the substr() function.
71172**
71173** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
71174** p1 is 1-indexed.  So substr(x,1,1) returns the first character
71175** of x.  If x is text, then we actually count UTF-8 characters.
71176** If x is a blob, then we count bytes.
71177**
71178** If p1 is negative, then we begin abs(p1) from the end of x[].
71179**
71180** If p2 is negative, return the p2 characters preceeding p1.
71181*/
71182static void substrFunc(
71183  sqlite3_context *context,
71184  int argc,
71185  sqlite3_value **argv
71186){
71187  const unsigned char *z;
71188  const unsigned char *z2;
71189  int len;
71190  int p0type;
71191  i64 p1, p2;
71192  int negP2 = 0;
71193
71194  assert( argc==3 || argc==2 );
71195  if( sqlite3_value_type(argv[1])==SQLITE_NULL
71196   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
71197  ){
71198    return;
71199  }
71200  p0type = sqlite3_value_type(argv[0]);
71201  p1 = sqlite3_value_int(argv[1]);
71202  if( p0type==SQLITE_BLOB ){
71203    len = sqlite3_value_bytes(argv[0]);
71204    z = sqlite3_value_blob(argv[0]);
71205    if( z==0 ) return;
71206    assert( len==sqlite3_value_bytes(argv[0]) );
71207  }else{
71208    z = sqlite3_value_text(argv[0]);
71209    if( z==0 ) return;
71210    len = 0;
71211    if( p1<0 ){
71212      for(z2=z; *z2; len++){
71213        SQLITE_SKIP_UTF8(z2);
71214      }
71215    }
71216  }
71217  if( argc==3 ){
71218    p2 = sqlite3_value_int(argv[2]);
71219    if( p2<0 ){
71220      p2 = -p2;
71221      negP2 = 1;
71222    }
71223  }else{
71224    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
71225  }
71226  if( p1<0 ){
71227    p1 += len;
71228    if( p1<0 ){
71229      p2 += p1;
71230      if( p2<0 ) p2 = 0;
71231      p1 = 0;
71232    }
71233  }else if( p1>0 ){
71234    p1--;
71235  }else if( p2>0 ){
71236    p2--;
71237  }
71238  if( negP2 ){
71239    p1 -= p2;
71240    if( p1<0 ){
71241      p2 += p1;
71242      p1 = 0;
71243    }
71244  }
71245  assert( p1>=0 && p2>=0 );
71246  if( p0type!=SQLITE_BLOB ){
71247    while( *z && p1 ){
71248      SQLITE_SKIP_UTF8(z);
71249      p1--;
71250    }
71251    for(z2=z; *z2 && p2; p2--){
71252      SQLITE_SKIP_UTF8(z2);
71253    }
71254    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
71255  }else{
71256    if( p1+p2>len ){
71257      p2 = len-p1;
71258      if( p2<0 ) p2 = 0;
71259    }
71260    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
71261  }
71262}
71263
71264/*
71265** Implementation of the round() function
71266*/
71267#ifndef SQLITE_OMIT_FLOATING_POINT
71268static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71269  int n = 0;
71270  double r;
71271  char *zBuf;
71272  assert( argc==1 || argc==2 );
71273  if( argc==2 ){
71274    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
71275    n = sqlite3_value_int(argv[1]);
71276    if( n>30 ) n = 30;
71277    if( n<0 ) n = 0;
71278  }
71279  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
71280  r = sqlite3_value_double(argv[0]);
71281  zBuf = sqlite3_mprintf("%.*f",n,r);
71282  if( zBuf==0 ){
71283    sqlite3_result_error_nomem(context);
71284  }else{
71285    sqlite3AtoF(zBuf, &r);
71286    sqlite3_free(zBuf);
71287    sqlite3_result_double(context, r);
71288  }
71289}
71290#endif
71291
71292/*
71293** Allocate nByte bytes of space using sqlite3_malloc(). If the
71294** allocation fails, call sqlite3_result_error_nomem() to notify
71295** the database handle that malloc() has failed and return NULL.
71296** If nByte is larger than the maximum string or blob length, then
71297** raise an SQLITE_TOOBIG exception and return NULL.
71298*/
71299static void *contextMalloc(sqlite3_context *context, i64 nByte){
71300  char *z;
71301  sqlite3 *db = sqlite3_context_db_handle(context);
71302  assert( nByte>0 );
71303  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
71304  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
71305  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71306    sqlite3_result_error_toobig(context);
71307    z = 0;
71308  }else{
71309    z = sqlite3Malloc((int)nByte);
71310    if( !z ){
71311      sqlite3_result_error_nomem(context);
71312    }
71313  }
71314  return z;
71315}
71316
71317/*
71318** Implementation of the upper() and lower() SQL functions.
71319*/
71320static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71321  char *z1;
71322  const char *z2;
71323  int i, n;
71324  UNUSED_PARAMETER(argc);
71325  z2 = (char*)sqlite3_value_text(argv[0]);
71326  n = sqlite3_value_bytes(argv[0]);
71327  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
71328  assert( z2==(char*)sqlite3_value_text(argv[0]) );
71329  if( z2 ){
71330    z1 = contextMalloc(context, ((i64)n)+1);
71331    if( z1 ){
71332      memcpy(z1, z2, n+1);
71333      for(i=0; z1[i]; i++){
71334        z1[i] = (char)sqlite3Toupper(z1[i]);
71335      }
71336      sqlite3_result_text(context, z1, -1, sqlite3_free);
71337    }
71338  }
71339}
71340static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71341  u8 *z1;
71342  const char *z2;
71343  int i, n;
71344  UNUSED_PARAMETER(argc);
71345  z2 = (char*)sqlite3_value_text(argv[0]);
71346  n = sqlite3_value_bytes(argv[0]);
71347  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
71348  assert( z2==(char*)sqlite3_value_text(argv[0]) );
71349  if( z2 ){
71350    z1 = contextMalloc(context, ((i64)n)+1);
71351    if( z1 ){
71352      memcpy(z1, z2, n+1);
71353      for(i=0; z1[i]; i++){
71354        z1[i] = sqlite3Tolower(z1[i]);
71355      }
71356      sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
71357    }
71358  }
71359}
71360
71361
71362#if 0  /* This function is never used. */
71363/*
71364** The COALESCE() and IFNULL() functions used to be implemented as shown
71365** here.  But now they are implemented as VDBE code so that unused arguments
71366** do not have to be computed.  This legacy implementation is retained as
71367** comment.
71368*/
71369/*
71370** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
71371** All three do the same thing.  They return the first non-NULL
71372** argument.
71373*/
71374static void ifnullFunc(
71375  sqlite3_context *context,
71376  int argc,
71377  sqlite3_value **argv
71378){
71379  int i;
71380  for(i=0; i<argc; i++){
71381    if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
71382      sqlite3_result_value(context, argv[i]);
71383      break;
71384    }
71385  }
71386}
71387#endif /* NOT USED */
71388#define ifnullFunc versionFunc   /* Substitute function - never called */
71389
71390/*
71391** Implementation of random().  Return a random integer.
71392*/
71393static void randomFunc(
71394  sqlite3_context *context,
71395  int NotUsed,
71396  sqlite3_value **NotUsed2
71397){
71398  sqlite_int64 r;
71399  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71400  sqlite3_randomness(sizeof(r), &r);
71401  if( r<0 ){
71402    /* We need to prevent a random number of 0x8000000000000000
71403    ** (or -9223372036854775808) since when you do abs() of that
71404    ** number of you get the same value back again.  To do this
71405    ** in a way that is testable, mask the sign bit off of negative
71406    ** values, resulting in a positive value.  Then take the
71407    ** 2s complement of that positive value.  The end result can
71408    ** therefore be no less than -9223372036854775807.
71409    */
71410    r = -(r ^ (((sqlite3_int64)1)<<63));
71411  }
71412  sqlite3_result_int64(context, r);
71413}
71414
71415/*
71416** Implementation of randomblob(N).  Return a random blob
71417** that is N bytes long.
71418*/
71419static void randomBlob(
71420  sqlite3_context *context,
71421  int argc,
71422  sqlite3_value **argv
71423){
71424  int n;
71425  unsigned char *p;
71426  assert( argc==1 );
71427  UNUSED_PARAMETER(argc);
71428  n = sqlite3_value_int(argv[0]);
71429  if( n<1 ){
71430    n = 1;
71431  }
71432  p = contextMalloc(context, n);
71433  if( p ){
71434    sqlite3_randomness(n, p);
71435    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
71436  }
71437}
71438
71439/*
71440** Implementation of the last_insert_rowid() SQL function.  The return
71441** value is the same as the sqlite3_last_insert_rowid() API function.
71442*/
71443static void last_insert_rowid(
71444  sqlite3_context *context,
71445  int NotUsed,
71446  sqlite3_value **NotUsed2
71447){
71448  sqlite3 *db = sqlite3_context_db_handle(context);
71449  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71450  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
71451}
71452
71453/*
71454** Implementation of the changes() SQL function.  The return value is the
71455** same as the sqlite3_changes() API function.
71456*/
71457static void changes(
71458  sqlite3_context *context,
71459  int NotUsed,
71460  sqlite3_value **NotUsed2
71461){
71462  sqlite3 *db = sqlite3_context_db_handle(context);
71463  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71464  sqlite3_result_int(context, sqlite3_changes(db));
71465}
71466
71467/*
71468** Implementation of the total_changes() SQL function.  The return value is
71469** the same as the sqlite3_total_changes() API function.
71470*/
71471static void total_changes(
71472  sqlite3_context *context,
71473  int NotUsed,
71474  sqlite3_value **NotUsed2
71475){
71476  sqlite3 *db = sqlite3_context_db_handle(context);
71477  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71478  sqlite3_result_int(context, sqlite3_total_changes(db));
71479}
71480
71481/*
71482** A structure defining how to do GLOB-style comparisons.
71483*/
71484struct compareInfo {
71485  u8 matchAll;
71486  u8 matchOne;
71487  u8 matchSet;
71488  u8 noCase;
71489};
71490
71491/*
71492** For LIKE and GLOB matching on EBCDIC machines, assume that every
71493** character is exactly one byte in size.  Also, all characters are
71494** able to participate in upper-case-to-lower-case mappings in EBCDIC
71495** whereas only characters less than 0x80 do in ASCII.
71496*/
71497#if defined(SQLITE_EBCDIC)
71498# define sqlite3Utf8Read(A,C)    (*(A++))
71499# define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
71500#else
71501# define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
71502#endif
71503
71504static const struct compareInfo globInfo = { '*', '?', '[', 0 };
71505/* The correct SQL-92 behavior is for the LIKE operator to ignore
71506** case.  Thus  'a' LIKE 'A' would be true. */
71507static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
71508/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
71509** is case sensitive causing 'a' LIKE 'A' to be false */
71510static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
71511
71512/*
71513** Compare two UTF-8 strings for equality where the first string can
71514** potentially be a "glob" expression.  Return true (1) if they
71515** are the same and false (0) if they are different.
71516**
71517** Globbing rules:
71518**
71519**      '*'       Matches any sequence of zero or more characters.
71520**
71521**      '?'       Matches exactly one character.
71522**
71523**     [...]      Matches one character from the enclosed list of
71524**                characters.
71525**
71526**     [^...]     Matches one character not in the enclosed list.
71527**
71528** With the [...] and [^...] matching, a ']' character can be included
71529** in the list by making it the first character after '[' or '^'.  A
71530** range of characters can be specified using '-'.  Example:
71531** "[a-z]" matches any single lower-case letter.  To match a '-', make
71532** it the last character in the list.
71533**
71534** This routine is usually quick, but can be N**2 in the worst case.
71535**
71536** Hints: to match '*' or '?', put them in "[]".  Like this:
71537**
71538**         abc[*]xyz        Matches "abc*xyz" only
71539*/
71540static int patternCompare(
71541  const u8 *zPattern,              /* The glob pattern */
71542  const u8 *zString,               /* The string to compare against the glob */
71543  const struct compareInfo *pInfo, /* Information about how to do the compare */
71544  const int esc                    /* The escape character */
71545){
71546  int c, c2;
71547  int invert;
71548  int seen;
71549  u8 matchOne = pInfo->matchOne;
71550  u8 matchAll = pInfo->matchAll;
71551  u8 matchSet = pInfo->matchSet;
71552  u8 noCase = pInfo->noCase;
71553  int prevEscape = 0;     /* True if the previous character was 'escape' */
71554
71555  while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
71556    if( !prevEscape && c==matchAll ){
71557      while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
71558               || c == matchOne ){
71559        if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
71560          return 0;
71561        }
71562      }
71563      if( c==0 ){
71564        return 1;
71565      }else if( c==esc ){
71566        c = sqlite3Utf8Read(zPattern, &zPattern);
71567        if( c==0 ){
71568          return 0;
71569        }
71570      }else if( c==matchSet ){
71571        assert( esc==0 );         /* This is GLOB, not LIKE */
71572        assert( matchSet<0x80 );  /* '[' is a single-byte character */
71573        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
71574          SQLITE_SKIP_UTF8(zString);
71575        }
71576        return *zString!=0;
71577      }
71578      while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
71579        if( noCase ){
71580          GlogUpperToLower(c2);
71581          GlogUpperToLower(c);
71582          while( c2 != 0 && c2 != c ){
71583            c2 = sqlite3Utf8Read(zString, &zString);
71584            GlogUpperToLower(c2);
71585          }
71586        }else{
71587          while( c2 != 0 && c2 != c ){
71588            c2 = sqlite3Utf8Read(zString, &zString);
71589          }
71590        }
71591        if( c2==0 ) return 0;
71592        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
71593      }
71594      return 0;
71595    }else if( !prevEscape && c==matchOne ){
71596      if( sqlite3Utf8Read(zString, &zString)==0 ){
71597        return 0;
71598      }
71599    }else if( c==matchSet ){
71600      int prior_c = 0;
71601      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
71602      seen = 0;
71603      invert = 0;
71604      c = sqlite3Utf8Read(zString, &zString);
71605      if( c==0 ) return 0;
71606      c2 = sqlite3Utf8Read(zPattern, &zPattern);
71607      if( c2=='^' ){
71608        invert = 1;
71609        c2 = sqlite3Utf8Read(zPattern, &zPattern);
71610      }
71611      if( c2==']' ){
71612        if( c==']' ) seen = 1;
71613        c2 = sqlite3Utf8Read(zPattern, &zPattern);
71614      }
71615      while( c2 && c2!=']' ){
71616        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
71617          c2 = sqlite3Utf8Read(zPattern, &zPattern);
71618          if( c>=prior_c && c<=c2 ) seen = 1;
71619          prior_c = 0;
71620        }else{
71621          if( c==c2 ){
71622            seen = 1;
71623          }
71624          prior_c = c2;
71625        }
71626        c2 = sqlite3Utf8Read(zPattern, &zPattern);
71627      }
71628      if( c2==0 || (seen ^ invert)==0 ){
71629        return 0;
71630      }
71631    }else if( esc==c && !prevEscape ){
71632      prevEscape = 1;
71633    }else{
71634      c2 = sqlite3Utf8Read(zString, &zString);
71635      if( noCase ){
71636        GlogUpperToLower(c);
71637        GlogUpperToLower(c2);
71638      }
71639      if( c!=c2 ){
71640        return 0;
71641      }
71642      prevEscape = 0;
71643    }
71644  }
71645  return *zString==0;
71646}
71647
71648/*
71649** Count the number of times that the LIKE operator (or GLOB which is
71650** just a variation of LIKE) gets called.  This is used for testing
71651** only.
71652*/
71653#ifdef SQLITE_TEST
71654SQLITE_API int sqlite3_like_count = 0;
71655#endif
71656
71657
71658/*
71659** Implementation of the like() SQL function.  This function implements
71660** the build-in LIKE operator.  The first argument to the function is the
71661** pattern and the second argument is the string.  So, the SQL statements:
71662**
71663**       A LIKE B
71664**
71665** is implemented as like(B,A).
71666**
71667** This same function (with a different compareInfo structure) computes
71668** the GLOB operator.
71669*/
71670static void likeFunc(
71671  sqlite3_context *context,
71672  int argc,
71673  sqlite3_value **argv
71674){
71675  const unsigned char *zA, *zB;
71676  int escape = 0;
71677  int nPat;
71678  sqlite3 *db = sqlite3_context_db_handle(context);
71679
71680  zB = sqlite3_value_text(argv[0]);
71681  zA = sqlite3_value_text(argv[1]);
71682
71683  /* Limit the length of the LIKE or GLOB pattern to avoid problems
71684  ** of deep recursion and N*N behavior in patternCompare().
71685  */
71686  nPat = sqlite3_value_bytes(argv[0]);
71687  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
71688  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
71689  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
71690    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
71691    return;
71692  }
71693  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
71694
71695  if( argc==3 ){
71696    /* The escape character string must consist of a single UTF-8 character.
71697    ** Otherwise, return an error.
71698    */
71699    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
71700    if( zEsc==0 ) return;
71701    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
71702      sqlite3_result_error(context,
71703          "ESCAPE expression must be a single character", -1);
71704      return;
71705    }
71706    escape = sqlite3Utf8Read(zEsc, &zEsc);
71707  }
71708  if( zA && zB ){
71709    struct compareInfo *pInfo = sqlite3_user_data(context);
71710#ifdef SQLITE_TEST
71711    sqlite3_like_count++;
71712#endif
71713
71714    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
71715  }
71716}
71717
71718/*
71719** Implementation of the NULLIF(x,y) function.  The result is the first
71720** argument if the arguments are different.  The result is NULL if the
71721** arguments are equal to each other.
71722*/
71723static void nullifFunc(
71724  sqlite3_context *context,
71725  int NotUsed,
71726  sqlite3_value **argv
71727){
71728  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
71729  UNUSED_PARAMETER(NotUsed);
71730  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
71731    sqlite3_result_value(context, argv[0]);
71732  }
71733}
71734
71735/*
71736** Implementation of the sqlite_version() function.  The result is the version
71737** of the SQLite library that is running.
71738*/
71739static void versionFunc(
71740  sqlite3_context *context,
71741  int NotUsed,
71742  sqlite3_value **NotUsed2
71743){
71744  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71745  sqlite3_result_text(context, sqlite3_version, -1, SQLITE_STATIC);
71746}
71747
71748/*
71749** Implementation of the sqlite_source_id() function. The result is a string
71750** that identifies the particular version of the source code used to build
71751** SQLite.
71752*/
71753static void sourceidFunc(
71754  sqlite3_context *context,
71755  int NotUsed,
71756  sqlite3_value **NotUsed2
71757){
71758  UNUSED_PARAMETER2(NotUsed, NotUsed2);
71759  sqlite3_result_text(context, SQLITE_SOURCE_ID, -1, SQLITE_STATIC);
71760}
71761
71762/* Array for converting from half-bytes (nybbles) into ASCII hex
71763** digits. */
71764static const char hexdigits[] = {
71765  '0', '1', '2', '3', '4', '5', '6', '7',
71766  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
71767};
71768
71769/*
71770** EXPERIMENTAL - This is not an official function.  The interface may
71771** change.  This function may disappear.  Do not write code that depends
71772** on this function.
71773**
71774** Implementation of the QUOTE() function.  This function takes a single
71775** argument.  If the argument is numeric, the return value is the same as
71776** the argument.  If the argument is NULL, the return value is the string
71777** "NULL".  Otherwise, the argument is enclosed in single quotes with
71778** single-quote escapes.
71779*/
71780static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
71781  assert( argc==1 );
71782  UNUSED_PARAMETER(argc);
71783  switch( sqlite3_value_type(argv[0]) ){
71784    case SQLITE_INTEGER:
71785    case SQLITE_FLOAT: {
71786      sqlite3_result_value(context, argv[0]);
71787      break;
71788    }
71789    case SQLITE_BLOB: {
71790      char *zText = 0;
71791      char const *zBlob = sqlite3_value_blob(argv[0]);
71792      int nBlob = sqlite3_value_bytes(argv[0]);
71793      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
71794      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
71795      if( zText ){
71796        int i;
71797        for(i=0; i<nBlob; i++){
71798          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
71799          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
71800        }
71801        zText[(nBlob*2)+2] = '\'';
71802        zText[(nBlob*2)+3] = '\0';
71803        zText[0] = 'X';
71804        zText[1] = '\'';
71805        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
71806        sqlite3_free(zText);
71807      }
71808      break;
71809    }
71810    case SQLITE_TEXT: {
71811      int i,j;
71812      u64 n;
71813      const unsigned char *zArg = sqlite3_value_text(argv[0]);
71814      char *z;
71815
71816      if( zArg==0 ) return;
71817      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
71818      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
71819      if( z ){
71820        z[0] = '\'';
71821        for(i=0, j=1; zArg[i]; i++){
71822          z[j++] = zArg[i];
71823          if( zArg[i]=='\'' ){
71824            z[j++] = '\'';
71825          }
71826        }
71827        z[j++] = '\'';
71828        z[j] = 0;
71829        sqlite3_result_text(context, z, j, sqlite3_free);
71830      }
71831      break;
71832    }
71833    default: {
71834      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
71835      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
71836      break;
71837    }
71838  }
71839}
71840
71841/*
71842** The hex() function.  Interpret the argument as a blob.  Return
71843** a hexadecimal rendering as text.
71844*/
71845static void hexFunc(
71846  sqlite3_context *context,
71847  int argc,
71848  sqlite3_value **argv
71849){
71850  int i, n;
71851  const unsigned char *pBlob;
71852  char *zHex, *z;
71853  assert( argc==1 );
71854  UNUSED_PARAMETER(argc);
71855  pBlob = sqlite3_value_blob(argv[0]);
71856  n = sqlite3_value_bytes(argv[0]);
71857  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
71858  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
71859  if( zHex ){
71860    for(i=0; i<n; i++, pBlob++){
71861      unsigned char c = *pBlob;
71862      *(z++) = hexdigits[(c>>4)&0xf];
71863      *(z++) = hexdigits[c&0xf];
71864    }
71865    *z = 0;
71866    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
71867  }
71868}
71869
71870/*
71871** The zeroblob(N) function returns a zero-filled blob of size N bytes.
71872*/
71873static void zeroblobFunc(
71874  sqlite3_context *context,
71875  int argc,
71876  sqlite3_value **argv
71877){
71878  i64 n;
71879  sqlite3 *db = sqlite3_context_db_handle(context);
71880  assert( argc==1 );
71881  UNUSED_PARAMETER(argc);
71882  n = sqlite3_value_int64(argv[0]);
71883  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
71884  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
71885  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71886    sqlite3_result_error_toobig(context);
71887  }else{
71888    sqlite3_result_zeroblob(context, (int)n);
71889  }
71890}
71891
71892/*
71893** The replace() function.  Three arguments are all strings: call
71894** them A, B, and C. The result is also a string which is derived
71895** from A by replacing every occurance of B with C.  The match
71896** must be exact.  Collating sequences are not used.
71897*/
71898static void replaceFunc(
71899  sqlite3_context *context,
71900  int argc,
71901  sqlite3_value **argv
71902){
71903  const unsigned char *zStr;        /* The input string A */
71904  const unsigned char *zPattern;    /* The pattern string B */
71905  const unsigned char *zRep;        /* The replacement string C */
71906  unsigned char *zOut;              /* The output */
71907  int nStr;                /* Size of zStr */
71908  int nPattern;            /* Size of zPattern */
71909  int nRep;                /* Size of zRep */
71910  i64 nOut;                /* Maximum size of zOut */
71911  int loopLimit;           /* Last zStr[] that might match zPattern[] */
71912  int i, j;                /* Loop counters */
71913
71914  assert( argc==3 );
71915  UNUSED_PARAMETER(argc);
71916  zStr = sqlite3_value_text(argv[0]);
71917  if( zStr==0 ) return;
71918  nStr = sqlite3_value_bytes(argv[0]);
71919  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
71920  zPattern = sqlite3_value_text(argv[1]);
71921  if( zPattern==0 ){
71922    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
71923            || sqlite3_context_db_handle(context)->mallocFailed );
71924    return;
71925  }
71926  if( zPattern[0]==0 ){
71927    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
71928    sqlite3_result_value(context, argv[0]);
71929    return;
71930  }
71931  nPattern = sqlite3_value_bytes(argv[1]);
71932  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
71933  zRep = sqlite3_value_text(argv[2]);
71934  if( zRep==0 ) return;
71935  nRep = sqlite3_value_bytes(argv[2]);
71936  assert( zRep==sqlite3_value_text(argv[2]) );
71937  nOut = nStr + 1;
71938  assert( nOut<SQLITE_MAX_LENGTH );
71939  zOut = contextMalloc(context, (i64)nOut);
71940  if( zOut==0 ){
71941    return;
71942  }
71943  loopLimit = nStr - nPattern;
71944  for(i=j=0; i<=loopLimit; i++){
71945    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
71946      zOut[j++] = zStr[i];
71947    }else{
71948      u8 *zOld;
71949      sqlite3 *db = sqlite3_context_db_handle(context);
71950      nOut += nRep - nPattern;
71951      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
71952      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
71953      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71954        sqlite3_result_error_toobig(context);
71955        sqlite3DbFree(db, zOut);
71956        return;
71957      }
71958      zOld = zOut;
71959      zOut = sqlite3_realloc(zOut, (int)nOut);
71960      if( zOut==0 ){
71961        sqlite3_result_error_nomem(context);
71962        sqlite3DbFree(db, zOld);
71963        return;
71964      }
71965      memcpy(&zOut[j], zRep, nRep);
71966      j += nRep;
71967      i += nPattern-1;
71968    }
71969  }
71970  assert( j+nStr-i+1==nOut );
71971  memcpy(&zOut[j], &zStr[i], nStr-i);
71972  j += nStr - i;
71973  assert( j<=nOut );
71974  zOut[j] = 0;
71975  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
71976}
71977
71978/*
71979** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
71980** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
71981*/
71982static void trimFunc(
71983  sqlite3_context *context,
71984  int argc,
71985  sqlite3_value **argv
71986){
71987  const unsigned char *zIn;         /* Input string */
71988  const unsigned char *zCharSet;    /* Set of characters to trim */
71989  int nIn;                          /* Number of bytes in input */
71990  int flags;                        /* 1: trimleft  2: trimright  3: trim */
71991  int i;                            /* Loop counter */
71992  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
71993  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
71994  int nChar;                        /* Number of characters in zCharSet */
71995
71996  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
71997    return;
71998  }
71999  zIn = sqlite3_value_text(argv[0]);
72000  if( zIn==0 ) return;
72001  nIn = sqlite3_value_bytes(argv[0]);
72002  assert( zIn==sqlite3_value_text(argv[0]) );
72003  if( argc==1 ){
72004    static const unsigned char lenOne[] = { 1 };
72005    static unsigned char * const azOne[] = { (u8*)" " };
72006    nChar = 1;
72007    aLen = (u8*)lenOne;
72008    azChar = (unsigned char **)azOne;
72009    zCharSet = 0;
72010  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
72011    return;
72012  }else{
72013    const unsigned char *z;
72014    for(z=zCharSet, nChar=0; *z; nChar++){
72015      SQLITE_SKIP_UTF8(z);
72016    }
72017    if( nChar>0 ){
72018      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
72019      if( azChar==0 ){
72020        return;
72021      }
72022      aLen = (unsigned char*)&azChar[nChar];
72023      for(z=zCharSet, nChar=0; *z; nChar++){
72024        azChar[nChar] = (unsigned char *)z;
72025        SQLITE_SKIP_UTF8(z);
72026        aLen[nChar] = (u8)(z - azChar[nChar]);
72027      }
72028    }
72029  }
72030  if( nChar>0 ){
72031    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
72032    if( flags & 1 ){
72033      while( nIn>0 ){
72034        int len = 0;
72035        for(i=0; i<nChar; i++){
72036          len = aLen[i];
72037          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
72038        }
72039        if( i>=nChar ) break;
72040        zIn += len;
72041        nIn -= len;
72042      }
72043    }
72044    if( flags & 2 ){
72045      while( nIn>0 ){
72046        int len = 0;
72047        for(i=0; i<nChar; i++){
72048          len = aLen[i];
72049          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
72050        }
72051        if( i>=nChar ) break;
72052        nIn -= len;
72053      }
72054    }
72055    if( zCharSet ){
72056      sqlite3_free(azChar);
72057    }
72058  }
72059  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
72060}
72061
72062
72063/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
72064** is only available if the SQLITE_SOUNDEX compile-time option is used
72065** when SQLite is built.
72066*/
72067#ifdef SQLITE_SOUNDEX
72068/*
72069** Compute the soundex encoding of a word.
72070**
72071** IMP: R-59782-00072 The soundex(X) function returns a string that is the
72072** soundex encoding of the string X.
72073*/
72074static void soundexFunc(
72075  sqlite3_context *context,
72076  int argc,
72077  sqlite3_value **argv
72078){
72079  char zResult[8];
72080  const u8 *zIn;
72081  int i, j;
72082  static const unsigned char iCode[] = {
72083    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72084    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72085    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72086    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
72087    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
72088    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
72089    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
72090    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
72091  };
72092  assert( argc==1 );
72093  zIn = (u8*)sqlite3_value_text(argv[0]);
72094  if( zIn==0 ) zIn = (u8*)"";
72095  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
72096  if( zIn[i] ){
72097    u8 prevcode = iCode[zIn[i]&0x7f];
72098    zResult[0] = sqlite3Toupper(zIn[i]);
72099    for(j=1; j<4 && zIn[i]; i++){
72100      int code = iCode[zIn[i]&0x7f];
72101      if( code>0 ){
72102        if( code!=prevcode ){
72103          prevcode = code;
72104          zResult[j++] = code + '0';
72105        }
72106      }else{
72107        prevcode = 0;
72108      }
72109    }
72110    while( j<4 ){
72111      zResult[j++] = '0';
72112    }
72113    zResult[j] = 0;
72114    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
72115  }else{
72116    /* IMP: R-64894-50321 The string "?000" is returned if the argument
72117    ** is NULL or contains no ASCII alphabetic characters. */
72118    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
72119  }
72120}
72121#endif /* SQLITE_SOUNDEX */
72122
72123#ifndef SQLITE_OMIT_LOAD_EXTENSION
72124/*
72125** A function that loads a shared-library extension then returns NULL.
72126*/
72127static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
72128  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
72129  const char *zProc;
72130  sqlite3 *db = sqlite3_context_db_handle(context);
72131  char *zErrMsg = 0;
72132
72133  if( argc==2 ){
72134    zProc = (const char *)sqlite3_value_text(argv[1]);
72135  }else{
72136    zProc = 0;
72137  }
72138  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
72139    sqlite3_result_error(context, zErrMsg, -1);
72140    sqlite3_free(zErrMsg);
72141  }
72142}
72143#endif
72144
72145
72146/*
72147** An instance of the following structure holds the context of a
72148** sum() or avg() aggregate computation.
72149*/
72150typedef struct SumCtx SumCtx;
72151struct SumCtx {
72152  double rSum;      /* Floating point sum */
72153  i64 iSum;         /* Integer sum */
72154  i64 cnt;          /* Number of elements summed */
72155  u8 overflow;      /* True if integer overflow seen */
72156  u8 approx;        /* True if non-integer value was input to the sum */
72157};
72158
72159/*
72160** Routines used to compute the sum, average, and total.
72161**
72162** The SUM() function follows the (broken) SQL standard which means
72163** that it returns NULL if it sums over no inputs.  TOTAL returns
72164** 0.0 in that case.  In addition, TOTAL always returns a float where
72165** SUM might return an integer if it never encounters a floating point
72166** value.  TOTAL never fails, but SUM might through an exception if
72167** it overflows an integer.
72168*/
72169static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
72170  SumCtx *p;
72171  int type;
72172  assert( argc==1 );
72173  UNUSED_PARAMETER(argc);
72174  p = sqlite3_aggregate_context(context, sizeof(*p));
72175  type = sqlite3_value_numeric_type(argv[0]);
72176  if( p && type!=SQLITE_NULL ){
72177    p->cnt++;
72178    if( type==SQLITE_INTEGER ){
72179      i64 v = sqlite3_value_int64(argv[0]);
72180      p->rSum += v;
72181      if( (p->approx|p->overflow)==0 ){
72182        i64 iNewSum = p->iSum + v;
72183        int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
72184        int s2 = (int)(v       >> (sizeof(i64)*8-1));
72185        int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
72186        p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
72187        p->iSum = iNewSum;
72188      }
72189    }else{
72190      p->rSum += sqlite3_value_double(argv[0]);
72191      p->approx = 1;
72192    }
72193  }
72194}
72195static void sumFinalize(sqlite3_context *context){
72196  SumCtx *p;
72197  p = sqlite3_aggregate_context(context, 0);
72198  if( p && p->cnt>0 ){
72199    if( p->overflow ){
72200      sqlite3_result_error(context,"integer overflow",-1);
72201    }else if( p->approx ){
72202      sqlite3_result_double(context, p->rSum);
72203    }else{
72204      sqlite3_result_int64(context, p->iSum);
72205    }
72206  }
72207}
72208static void avgFinalize(sqlite3_context *context){
72209  SumCtx *p;
72210  p = sqlite3_aggregate_context(context, 0);
72211  if( p && p->cnt>0 ){
72212    sqlite3_result_double(context, p->rSum/(double)p->cnt);
72213  }
72214}
72215static void totalFinalize(sqlite3_context *context){
72216  SumCtx *p;
72217  p = sqlite3_aggregate_context(context, 0);
72218  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
72219  sqlite3_result_double(context, p ? p->rSum : (double)0);
72220}
72221
72222/*
72223** The following structure keeps track of state information for the
72224** count() aggregate function.
72225*/
72226typedef struct CountCtx CountCtx;
72227struct CountCtx {
72228  i64 n;
72229};
72230
72231/*
72232** Routines to implement the count() aggregate function.
72233*/
72234static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
72235  CountCtx *p;
72236  p = sqlite3_aggregate_context(context, sizeof(*p));
72237  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
72238    p->n++;
72239  }
72240
72241#ifndef SQLITE_OMIT_DEPRECATED
72242  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
72243  ** sure it still operates correctly, verify that its count agrees with our
72244  ** internal count when using count(*) and when the total count can be
72245  ** expressed as a 32-bit integer. */
72246  assert( argc==1 || p==0 || p->n>0x7fffffff
72247          || p->n==sqlite3_aggregate_count(context) );
72248#endif
72249}
72250static void countFinalize(sqlite3_context *context){
72251  CountCtx *p;
72252  p = sqlite3_aggregate_context(context, 0);
72253  sqlite3_result_int64(context, p ? p->n : 0);
72254}
72255
72256/*
72257** Routines to implement min() and max() aggregate functions.
72258*/
72259static void minmaxStep(
72260  sqlite3_context *context,
72261  int NotUsed,
72262  sqlite3_value **argv
72263){
72264  Mem *pArg  = (Mem *)argv[0];
72265  Mem *pBest;
72266  UNUSED_PARAMETER(NotUsed);
72267
72268  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
72269  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
72270  if( !pBest ) return;
72271
72272  if( pBest->flags ){
72273    int max;
72274    int cmp;
72275    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
72276    /* This step function is used for both the min() and max() aggregates,
72277    ** the only difference between the two being that the sense of the
72278    ** comparison is inverted. For the max() aggregate, the
72279    ** sqlite3_user_data() function returns (void *)-1. For min() it
72280    ** returns (void *)db, where db is the sqlite3* database pointer.
72281    ** Therefore the next statement sets variable 'max' to 1 for the max()
72282    ** aggregate, or 0 for min().
72283    */
72284    max = sqlite3_user_data(context)!=0;
72285    cmp = sqlite3MemCompare(pBest, pArg, pColl);
72286    if( (max && cmp<0) || (!max && cmp>0) ){
72287      sqlite3VdbeMemCopy(pBest, pArg);
72288    }
72289  }else{
72290    sqlite3VdbeMemCopy(pBest, pArg);
72291  }
72292}
72293static void minMaxFinalize(sqlite3_context *context){
72294  sqlite3_value *pRes;
72295  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
72296  if( pRes ){
72297    if( ALWAYS(pRes->flags) ){
72298      sqlite3_result_value(context, pRes);
72299    }
72300    sqlite3VdbeMemRelease(pRes);
72301  }
72302}
72303
72304/*
72305** group_concat(EXPR, ?SEPARATOR?)
72306*/
72307static void groupConcatStep(
72308  sqlite3_context *context,
72309  int argc,
72310  sqlite3_value **argv
72311){
72312  const char *zVal;
72313  StrAccum *pAccum;
72314  const char *zSep;
72315  int nVal, nSep;
72316  assert( argc==1 || argc==2 );
72317  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
72318  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
72319
72320  if( pAccum ){
72321    sqlite3 *db = sqlite3_context_db_handle(context);
72322    int firstTerm = pAccum->useMalloc==0;
72323    pAccum->useMalloc = 1;
72324    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
72325    if( !firstTerm ){
72326      if( argc==2 ){
72327        zSep = (char*)sqlite3_value_text(argv[1]);
72328        nSep = sqlite3_value_bytes(argv[1]);
72329      }else{
72330        zSep = ",";
72331        nSep = 1;
72332      }
72333      sqlite3StrAccumAppend(pAccum, zSep, nSep);
72334    }
72335    zVal = (char*)sqlite3_value_text(argv[0]);
72336    nVal = sqlite3_value_bytes(argv[0]);
72337    sqlite3StrAccumAppend(pAccum, zVal, nVal);
72338  }
72339}
72340static void groupConcatFinalize(sqlite3_context *context){
72341  StrAccum *pAccum;
72342  pAccum = sqlite3_aggregate_context(context, 0);
72343  if( pAccum ){
72344    if( pAccum->tooBig ){
72345      sqlite3_result_error_toobig(context);
72346    }else if( pAccum->mallocFailed ){
72347      sqlite3_result_error_nomem(context);
72348    }else{
72349      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
72350                          sqlite3_free);
72351    }
72352  }
72353}
72354
72355/*
72356** This function registered all of the above C functions as SQL
72357** functions.  This should be the only routine in this file with
72358** external linkage.
72359*/
72360SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
72361#ifndef SQLITE_OMIT_ALTERTABLE
72362  sqlite3AlterFunctions(db);
72363#endif
72364  if( !db->mallocFailed ){
72365    int rc = sqlite3_overload_function(db, "MATCH", 2);
72366    assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
72367    if( rc==SQLITE_NOMEM ){
72368      db->mallocFailed = 1;
72369    }
72370  }
72371}
72372
72373/*
72374** Set the LIKEOPT flag on the 2-argument function with the given name.
72375*/
72376static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
72377  FuncDef *pDef;
72378  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
72379                             2, SQLITE_UTF8, 0);
72380  if( ALWAYS(pDef) ){
72381    pDef->flags = flagVal;
72382  }
72383}
72384
72385/*
72386** Register the built-in LIKE and GLOB functions.  The caseSensitive
72387** parameter determines whether or not the LIKE operator is case
72388** sensitive.  GLOB is always case sensitive.
72389*/
72390SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
72391  struct compareInfo *pInfo;
72392  if( caseSensitive ){
72393    pInfo = (struct compareInfo*)&likeInfoAlt;
72394  }else{
72395    pInfo = (struct compareInfo*)&likeInfoNorm;
72396  }
72397  sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
72398  sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
72399  sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY,
72400      (struct compareInfo*)&globInfo, likeFunc, 0,0);
72401  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
72402  setLikeOptFlag(db, "like",
72403      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
72404}
72405
72406/*
72407** pExpr points to an expression which implements a function.  If
72408** it is appropriate to apply the LIKE optimization to that function
72409** then set aWc[0] through aWc[2] to the wildcard characters and
72410** return TRUE.  If the function is not a LIKE-style function then
72411** return FALSE.
72412*/
72413SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
72414  FuncDef *pDef;
72415  if( pExpr->op!=TK_FUNCTION
72416   || !pExpr->x.pList
72417   || pExpr->x.pList->nExpr!=2
72418  ){
72419    return 0;
72420  }
72421  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
72422  pDef = sqlite3FindFunction(db, pExpr->u.zToken,
72423                             sqlite3Strlen30(pExpr->u.zToken),
72424                             2, SQLITE_UTF8, 0);
72425  if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
72426    return 0;
72427  }
72428
72429  /* The memcpy() statement assumes that the wildcard characters are
72430  ** the first three statements in the compareInfo structure.  The
72431  ** asserts() that follow verify that assumption
72432  */
72433  memcpy(aWc, pDef->pUserData, 3);
72434  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
72435  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
72436  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
72437  *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
72438  return 1;
72439}
72440
72441/*
72442** All all of the FuncDef structures in the aBuiltinFunc[] array above
72443** to the global function hash table.  This occurs at start-time (as
72444** a consequence of calling sqlite3_initialize()).
72445**
72446** After this routine runs
72447*/
72448SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
72449  /*
72450  ** The following array holds FuncDef structures for all of the functions
72451  ** defined in this file.
72452  **
72453  ** The array cannot be constant since changes are made to the
72454  ** FuncDef.pHash elements at start-time.  The elements of this array
72455  ** are read-only after initialization is complete.
72456  */
72457  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
72458    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
72459    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
72460    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
72461    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
72462    FUNCTION(trim,               1, 3, 0, trimFunc         ),
72463    FUNCTION(trim,               2, 3, 0, trimFunc         ),
72464    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
72465    FUNCTION(min,                0, 0, 1, 0                ),
72466    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
72467    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
72468    FUNCTION(max,                0, 1, 1, 0                ),
72469    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
72470    FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
72471    FUNCTION(length,             1, 0, 0, lengthFunc       ),
72472    FUNCTION(substr,             2, 0, 0, substrFunc       ),
72473    FUNCTION(substr,             3, 0, 0, substrFunc       ),
72474    FUNCTION(abs,                1, 0, 0, absFunc          ),
72475#ifndef SQLITE_OMIT_FLOATING_POINT
72476    FUNCTION(round,              1, 0, 0, roundFunc        ),
72477    FUNCTION(round,              2, 0, 0, roundFunc        ),
72478#endif
72479    FUNCTION(upper,              1, 0, 0, upperFunc        ),
72480    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
72481    FUNCTION(coalesce,           1, 0, 0, 0                ),
72482    FUNCTION(coalesce,           0, 0, 0, 0                ),
72483/*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
72484    {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0},
72485    FUNCTION(hex,                1, 0, 0, hexFunc          ),
72486/*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
72487    {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0},
72488    FUNCTION(random,             0, 0, 0, randomFunc       ),
72489    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
72490    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
72491    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
72492    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
72493    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
72494    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
72495    FUNCTION(changes,            0, 0, 0, changes          ),
72496    FUNCTION(total_changes,      0, 0, 0, total_changes    ),
72497    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
72498    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
72499  #ifdef SQLITE_SOUNDEX
72500    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
72501  #endif
72502  #ifndef SQLITE_OMIT_LOAD_EXTENSION
72503    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
72504    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
72505  #endif
72506    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
72507    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
72508    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
72509 /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
72510    {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
72511    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
72512    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
72513    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
72514
72515    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72516  #ifdef SQLITE_CASE_SENSITIVE_LIKE
72517    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72518    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
72519  #else
72520    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
72521    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
72522  #endif
72523  };
72524
72525  int i;
72526  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
72527  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
72528
72529  for(i=0; i<ArraySize(aBuiltinFunc); i++){
72530    sqlite3FuncDefInsert(pHash, &aFunc[i]);
72531  }
72532  sqlite3RegisterDateTimeFunctions();
72533}
72534
72535/************** End of func.c ************************************************/
72536/************** Begin file fkey.c ********************************************/
72537/*
72538**
72539** The author disclaims copyright to this source code.  In place of
72540** a legal notice, here is a blessing:
72541**
72542**    May you do good and not evil.
72543**    May you find forgiveness for yourself and forgive others.
72544**    May you share freely, never taking more than you give.
72545**
72546*************************************************************************
72547** This file contains code used by the compiler to add foreign key
72548** support to compiled SQL statements.
72549*/
72550
72551#ifndef SQLITE_OMIT_FOREIGN_KEY
72552#ifndef SQLITE_OMIT_TRIGGER
72553
72554/*
72555** Deferred and Immediate FKs
72556** --------------------------
72557**
72558** Foreign keys in SQLite come in two flavours: deferred and immediate.
72559** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
72560** is returned and the current statement transaction rolled back. If a
72561** deferred foreign key constraint is violated, no action is taken
72562** immediately. However if the application attempts to commit the
72563** transaction before fixing the constraint violation, the attempt fails.
72564**
72565** Deferred constraints are implemented using a simple counter associated
72566** with the database handle. The counter is set to zero each time a
72567** database transaction is opened. Each time a statement is executed
72568** that causes a foreign key violation, the counter is incremented. Each
72569** time a statement is executed that removes an existing violation from
72570** the database, the counter is decremented. When the transaction is
72571** committed, the commit fails if the current value of the counter is
72572** greater than zero. This scheme has two big drawbacks:
72573**
72574**   * When a commit fails due to a deferred foreign key constraint,
72575**     there is no way to tell which foreign constraint is not satisfied,
72576**     or which row it is not satisfied for.
72577**
72578**   * If the database contains foreign key violations when the
72579**     transaction is opened, this may cause the mechanism to malfunction.
72580**
72581** Despite these problems, this approach is adopted as it seems simpler
72582** than the alternatives.
72583**
72584** INSERT operations:
72585**
72586**   I.1) For each FK for which the table is the child table, search
72587**        the parent table for a match. If none is found increment the
72588**        constraint counter.
72589**
72590**   I.2) For each FK for which the table is the parent table,
72591**        search the child table for rows that correspond to the new
72592**        row in the parent table. Decrement the counter for each row
72593**        found (as the constraint is now satisfied).
72594**
72595** DELETE operations:
72596**
72597**   D.1) For each FK for which the table is the child table,
72598**        search the parent table for a row that corresponds to the
72599**        deleted row in the child table. If such a row is not found,
72600**        decrement the counter.
72601**
72602**   D.2) For each FK for which the table is the parent table, search
72603**        the child table for rows that correspond to the deleted row
72604**        in the parent table. For each found increment the counter.
72605**
72606** UPDATE operations:
72607**
72608**   An UPDATE command requires that all 4 steps above are taken, but only
72609**   for FK constraints for which the affected columns are actually
72610**   modified (values must be compared at runtime).
72611**
72612** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
72613** This simplifies the implementation a bit.
72614**
72615** For the purposes of immediate FK constraints, the OR REPLACE conflict
72616** resolution is considered to delete rows before the new row is inserted.
72617** If a delete caused by OR REPLACE violates an FK constraint, an exception
72618** is thrown, even if the FK constraint would be satisfied after the new
72619** row is inserted.
72620**
72621** Immediate constraints are usually handled similarly. The only difference
72622** is that the counter used is stored as part of each individual statement
72623** object (struct Vdbe). If, after the statement has run, its immediate
72624** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
72625** and the statement transaction is rolled back. An exception is an INSERT
72626** statement that inserts a single row only (no triggers). In this case,
72627** instead of using a counter, an exception is thrown immediately if the
72628** INSERT violates a foreign key constraint. This is necessary as such
72629** an INSERT does not open a statement transaction.
72630**
72631** TODO: How should dropping a table be handled? How should renaming a
72632** table be handled?
72633**
72634**
72635** Query API Notes
72636** ---------------
72637**
72638** Before coding an UPDATE or DELETE row operation, the code-generator
72639** for those two operations needs to know whether or not the operation
72640** requires any FK processing and, if so, which columns of the original
72641** row are required by the FK processing VDBE code (i.e. if FKs were
72642** implemented using triggers, which of the old.* columns would be
72643** accessed). No information is required by the code-generator before
72644** coding an INSERT operation. The functions used by the UPDATE/DELETE
72645** generation code to query for this information are:
72646**
72647**   sqlite3FkRequired() - Test to see if FK processing is required.
72648**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
72649**
72650**
72651** Externally accessible module functions
72652** --------------------------------------
72653**
72654**   sqlite3FkCheck()    - Check for foreign key violations.
72655**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
72656**   sqlite3FkDelete()   - Delete an FKey structure.
72657*/
72658
72659/*
72660** VDBE Calling Convention
72661** -----------------------
72662**
72663** Example:
72664**
72665**   For the following INSERT statement:
72666**
72667**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
72668**     INSERT INTO t1 VALUES(1, 2, 3.1);
72669**
72670**   Register (x):        2    (type integer)
72671**   Register (x+1):      1    (type integer)
72672**   Register (x+2):      NULL (type NULL)
72673**   Register (x+3):      3.1  (type real)
72674*/
72675
72676/*
72677** A foreign key constraint requires that the key columns in the parent
72678** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
72679** Given that pParent is the parent table for foreign key constraint pFKey,
72680** search the schema a unique index on the parent key columns.
72681**
72682** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
72683** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
72684** is set to point to the unique index.
72685**
72686** If the parent key consists of a single column (the foreign key constraint
72687** is not a composite foreign key), output variable *paiCol is set to NULL.
72688** Otherwise, it is set to point to an allocated array of size N, where
72689** N is the number of columns in the parent key. The first element of the
72690** array is the index of the child table column that is mapped by the FK
72691** constraint to the parent table column stored in the left-most column
72692** of index *ppIdx. The second element of the array is the index of the
72693** child table column that corresponds to the second left-most column of
72694** *ppIdx, and so on.
72695**
72696** If the required index cannot be found, either because:
72697**
72698**   1) The named parent key columns do not exist, or
72699**
72700**   2) The named parent key columns do exist, but are not subject to a
72701**      UNIQUE or PRIMARY KEY constraint, or
72702**
72703**   3) No parent key columns were provided explicitly as part of the
72704**      foreign key definition, and the parent table does not have a
72705**      PRIMARY KEY, or
72706**
72707**   4) No parent key columns were provided explicitly as part of the
72708**      foreign key definition, and the PRIMARY KEY of the parent table
72709**      consists of a a different number of columns to the child key in
72710**      the child table.
72711**
72712** then non-zero is returned, and a "foreign key mismatch" error loaded
72713** into pParse. If an OOM error occurs, non-zero is returned and the
72714** pParse->db->mallocFailed flag is set.
72715*/
72716static int locateFkeyIndex(
72717  Parse *pParse,                  /* Parse context to store any error in */
72718  Table *pParent,                 /* Parent table of FK constraint pFKey */
72719  FKey *pFKey,                    /* Foreign key to find index for */
72720  Index **ppIdx,                  /* OUT: Unique index on parent table */
72721  int **paiCol                    /* OUT: Map of index columns in pFKey */
72722){
72723  Index *pIdx = 0;                    /* Value to return via *ppIdx */
72724  int *aiCol = 0;                     /* Value to return via *paiCol */
72725  int nCol = pFKey->nCol;             /* Number of columns in parent key */
72726  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
72727
72728  /* The caller is responsible for zeroing output parameters. */
72729  assert( ppIdx && *ppIdx==0 );
72730  assert( !paiCol || *paiCol==0 );
72731  assert( pParse );
72732
72733  /* If this is a non-composite (single column) foreign key, check if it
72734  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
72735  ** and *paiCol set to zero and return early.
72736  **
72737  ** Otherwise, for a composite foreign key (more than one column), allocate
72738  ** space for the aiCol array (returned via output parameter *paiCol).
72739  ** Non-composite foreign keys do not require the aiCol array.
72740  */
72741  if( nCol==1 ){
72742    /* The FK maps to the IPK if any of the following are true:
72743    **
72744    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
72745    **      mapped to the primary key of table pParent, or
72746    **   2) The FK is explicitly mapped to a column declared as INTEGER
72747    **      PRIMARY KEY.
72748    */
72749    if( pParent->iPKey>=0 ){
72750      if( !zKey ) return 0;
72751      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
72752    }
72753  }else if( paiCol ){
72754    assert( nCol>1 );
72755    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
72756    if( !aiCol ) return 1;
72757    *paiCol = aiCol;
72758  }
72759
72760  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
72761    if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
72762      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
72763      ** of columns. If each indexed column corresponds to a foreign key
72764      ** column of pFKey, then this index is a winner.  */
72765
72766      if( zKey==0 ){
72767        /* If zKey is NULL, then this foreign key is implicitly mapped to
72768        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
72769        ** identified by the test (Index.autoIndex==2).  */
72770        if( pIdx->autoIndex==2 ){
72771          if( aiCol ){
72772            int i;
72773            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
72774          }
72775          break;
72776        }
72777      }else{
72778        /* If zKey is non-NULL, then this foreign key was declared to
72779        ** map to an explicit list of columns in table pParent. Check if this
72780        ** index matches those columns. Also, check that the index uses
72781        ** the default collation sequences for each column. */
72782        int i, j;
72783        for(i=0; i<nCol; i++){
72784          int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
72785          char *zDfltColl;                  /* Def. collation for column */
72786          char *zIdxCol;                    /* Name of indexed column */
72787
72788          /* If the index uses a collation sequence that is different from
72789          ** the default collation sequence for the column, this index is
72790          ** unusable. Bail out early in this case.  */
72791          zDfltColl = pParent->aCol[iCol].zColl;
72792          if( !zDfltColl ){
72793            zDfltColl = "BINARY";
72794          }
72795          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
72796
72797          zIdxCol = pParent->aCol[iCol].zName;
72798          for(j=0; j<nCol; j++){
72799            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
72800              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
72801              break;
72802            }
72803          }
72804          if( j==nCol ) break;
72805        }
72806        if( i==nCol ) break;      /* pIdx is usable */
72807      }
72808    }
72809  }
72810
72811  if( !pIdx ){
72812    if( !pParse->disableTriggers ){
72813      sqlite3ErrorMsg(pParse, "foreign key mismatch");
72814    }
72815    sqlite3DbFree(pParse->db, aiCol);
72816    return 1;
72817  }
72818
72819  *ppIdx = pIdx;
72820  return 0;
72821}
72822
72823/*
72824** This function is called when a row is inserted into or deleted from the
72825** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
72826** on the child table of pFKey, this function is invoked twice for each row
72827** affected - once to "delete" the old row, and then again to "insert" the
72828** new row.
72829**
72830** Each time it is called, this function generates VDBE code to locate the
72831** row in the parent table that corresponds to the row being inserted into
72832** or deleted from the child table. If the parent row can be found, no
72833** special action is taken. Otherwise, if the parent row can *not* be
72834** found in the parent table:
72835**
72836**   Operation | FK type   | Action taken
72837**   --------------------------------------------------------------------------
72838**   INSERT      immediate   Increment the "immediate constraint counter".
72839**
72840**   DELETE      immediate   Decrement the "immediate constraint counter".
72841**
72842**   INSERT      deferred    Increment the "deferred constraint counter".
72843**
72844**   DELETE      deferred    Decrement the "deferred constraint counter".
72845**
72846** These operations are identified in the comment at the top of this file
72847** (fkey.c) as "I.1" and "D.1".
72848*/
72849static void fkLookupParent(
72850  Parse *pParse,        /* Parse context */
72851  int iDb,              /* Index of database housing pTab */
72852  Table *pTab,          /* Parent table of FK pFKey */
72853  Index *pIdx,          /* Unique index on parent key columns in pTab */
72854  FKey *pFKey,          /* Foreign key constraint */
72855  int *aiCol,           /* Map from parent key columns to child table columns */
72856  int regData,          /* Address of array containing child table row */
72857  int nIncr,            /* Increment constraint counter by this */
72858  int isIgnore          /* If true, pretend pTab contains all NULL values */
72859){
72860  int i;                                    /* Iterator variable */
72861  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
72862  int iCur = pParse->nTab - 1;              /* Cursor number to use */
72863  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
72864
72865  /* If nIncr is less than zero, then check at runtime if there are any
72866  ** outstanding constraints to resolve. If there are not, there is no need
72867  ** to check if deleting this row resolves any outstanding violations.
72868  **
72869  ** Check if any of the key columns in the child table row are NULL. If
72870  ** any are, then the constraint is considered satisfied. No need to
72871  ** search for a matching row in the parent table.  */
72872  if( nIncr<0 ){
72873    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
72874  }
72875  for(i=0; i<pFKey->nCol; i++){
72876    int iReg = aiCol[i] + regData + 1;
72877    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
72878  }
72879
72880  if( isIgnore==0 ){
72881    if( pIdx==0 ){
72882      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
72883      ** column of the parent table (table pTab).  */
72884      int iMustBeInt;               /* Address of MustBeInt instruction */
72885      int regTemp = sqlite3GetTempReg(pParse);
72886
72887      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
72888      ** apply the affinity of the parent key). If this fails, then there
72889      ** is no matching parent key. Before using MustBeInt, make a copy of
72890      ** the value. Otherwise, the value inserted into the child key column
72891      ** will have INTEGER affinity applied to it, which may not be correct.  */
72892      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
72893      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
72894
72895      /* If the parent table is the same as the child table, and we are about
72896      ** to increment the constraint-counter (i.e. this is an INSERT operation),
72897      ** then check if the row being inserted matches itself. If so, do not
72898      ** increment the constraint-counter.  */
72899      if( pTab==pFKey->pFrom && nIncr==1 ){
72900        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
72901      }
72902
72903      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
72904      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
72905      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
72906      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
72907      sqlite3VdbeJumpHere(v, iMustBeInt);
72908      sqlite3ReleaseTempReg(pParse, regTemp);
72909    }else{
72910      int nCol = pFKey->nCol;
72911      int regTemp = sqlite3GetTempRange(pParse, nCol);
72912      int regRec = sqlite3GetTempReg(pParse);
72913      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
72914
72915      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
72916      sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
72917      for(i=0; i<nCol; i++){
72918        sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
72919      }
72920
72921      /* If the parent table is the same as the child table, and we are about
72922      ** to increment the constraint-counter (i.e. this is an INSERT operation),
72923      ** then check if the row being inserted matches itself. If so, do not
72924      ** increment the constraint-counter.  */
72925      if( pTab==pFKey->pFrom && nIncr==1 ){
72926        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
72927        for(i=0; i<nCol; i++){
72928          int iChild = aiCol[i]+1+regData;
72929          int iParent = pIdx->aiColumn[i]+1+regData;
72930          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
72931        }
72932        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
72933      }
72934
72935      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
72936      sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
72937      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
72938
72939      sqlite3ReleaseTempReg(pParse, regRec);
72940      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
72941    }
72942  }
72943
72944  if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
72945    /* Special case: If this is an INSERT statement that will insert exactly
72946    ** one row into the table, raise a constraint immediately instead of
72947    ** incrementing a counter. This is necessary as the VM code is being
72948    ** generated for will not open a statement transaction.  */
72949    assert( nIncr==1 );
72950    sqlite3HaltConstraint(
72951        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
72952    );
72953  }else{
72954    if( nIncr>0 && pFKey->isDeferred==0 ){
72955      sqlite3ParseToplevel(pParse)->mayAbort = 1;
72956    }
72957    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
72958  }
72959
72960  sqlite3VdbeResolveLabel(v, iOk);
72961  sqlite3VdbeAddOp1(v, OP_Close, iCur);
72962}
72963
72964/*
72965** This function is called to generate code executed when a row is deleted
72966** from the parent table of foreign key constraint pFKey and, if pFKey is
72967** deferred, when a row is inserted into the same table. When generating
72968** code for an SQL UPDATE operation, this function may be called twice -
72969** once to "delete" the old row and once to "insert" the new row.
72970**
72971** The code generated by this function scans through the rows in the child
72972** table that correspond to the parent table row being deleted or inserted.
72973** For each child row found, one of the following actions is taken:
72974**
72975**   Operation | FK type   | Action taken
72976**   --------------------------------------------------------------------------
72977**   DELETE      immediate   Increment the "immediate constraint counter".
72978**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
72979**                           throw a "foreign key constraint failed" exception.
72980**
72981**   INSERT      immediate   Decrement the "immediate constraint counter".
72982**
72983**   DELETE      deferred    Increment the "deferred constraint counter".
72984**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
72985**                           throw a "foreign key constraint failed" exception.
72986**
72987**   INSERT      deferred    Decrement the "deferred constraint counter".
72988**
72989** These operations are identified in the comment at the top of this file
72990** (fkey.c) as "I.2" and "D.2".
72991*/
72992static void fkScanChildren(
72993  Parse *pParse,                  /* Parse context */
72994  SrcList *pSrc,                  /* SrcList containing the table to scan */
72995  Table *pTab,
72996  Index *pIdx,                    /* Foreign key index */
72997  FKey *pFKey,                    /* Foreign key relationship */
72998  int *aiCol,                     /* Map from pIdx cols to child table cols */
72999  int regData,                    /* Referenced table data starts here */
73000  int nIncr                       /* Amount to increment deferred counter by */
73001){
73002  sqlite3 *db = pParse->db;       /* Database handle */
73003  int i;                          /* Iterator variable */
73004  Expr *pWhere = 0;               /* WHERE clause to scan with */
73005  NameContext sNameContext;       /* Context used to resolve WHERE clause */
73006  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
73007  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
73008  Vdbe *v = sqlite3GetVdbe(pParse);
73009
73010  assert( !pIdx || pIdx->pTable==pTab );
73011
73012  if( nIncr<0 ){
73013    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
73014  }
73015
73016  /* Create an Expr object representing an SQL expression like:
73017  **
73018  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
73019  **
73020  ** The collation sequence used for the comparison should be that of
73021  ** the parent key columns. The affinity of the parent key column should
73022  ** be applied to each child key value before the comparison takes place.
73023  */
73024  for(i=0; i<pFKey->nCol; i++){
73025    Expr *pLeft;                  /* Value from parent table row */
73026    Expr *pRight;                 /* Column ref to child table */
73027    Expr *pEq;                    /* Expression (pLeft = pRight) */
73028    int iCol;                     /* Index of column in child table */
73029    const char *zCol;             /* Name of column in child table */
73030
73031    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
73032    if( pLeft ){
73033      /* Set the collation sequence and affinity of the LHS of each TK_EQ
73034      ** expression to the parent key column defaults.  */
73035      if( pIdx ){
73036        Column *pCol;
73037        iCol = pIdx->aiColumn[i];
73038        pCol = &pIdx->pTable->aCol[iCol];
73039        pLeft->iTable = regData+iCol+1;
73040        pLeft->affinity = pCol->affinity;
73041        pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
73042      }else{
73043        pLeft->iTable = regData;
73044        pLeft->affinity = SQLITE_AFF_INTEGER;
73045      }
73046    }
73047    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
73048    assert( iCol>=0 );
73049    zCol = pFKey->pFrom->aCol[iCol].zName;
73050    pRight = sqlite3Expr(db, TK_ID, zCol);
73051    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
73052    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73053  }
73054
73055  /* If the child table is the same as the parent table, and this scan
73056  ** is taking place as part of a DELETE operation (operation D.2), omit the
73057  ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
73058  ** clause, where $rowid is the rowid of the row being deleted.  */
73059  if( pTab==pFKey->pFrom && nIncr>0 ){
73060    Expr *pEq;                    /* Expression (pLeft = pRight) */
73061    Expr *pLeft;                  /* Value from parent table row */
73062    Expr *pRight;                 /* Column ref to child table */
73063    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
73064    pRight = sqlite3Expr(db, TK_COLUMN, 0);
73065    if( pLeft && pRight ){
73066      pLeft->iTable = regData;
73067      pLeft->affinity = SQLITE_AFF_INTEGER;
73068      pRight->iTable = pSrc->a[0].iCursor;
73069      pRight->iColumn = -1;
73070    }
73071    pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
73072    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73073  }
73074
73075  /* Resolve the references in the WHERE clause. */
73076  memset(&sNameContext, 0, sizeof(NameContext));
73077  sNameContext.pSrcList = pSrc;
73078  sNameContext.pParse = pParse;
73079  sqlite3ResolveExprNames(&sNameContext, pWhere);
73080
73081  /* Create VDBE to loop through the entries in pSrc that match the WHERE
73082  ** clause. If the constraint is not deferred, throw an exception for
73083  ** each row found. Otherwise, for deferred constraints, increment the
73084  ** deferred constraint counter by nIncr for each row selected.  */
73085  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
73086  if( nIncr>0 && pFKey->isDeferred==0 ){
73087    sqlite3ParseToplevel(pParse)->mayAbort = 1;
73088  }
73089  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
73090  if( pWInfo ){
73091    sqlite3WhereEnd(pWInfo);
73092  }
73093
73094  /* Clean up the WHERE clause constructed above. */
73095  sqlite3ExprDelete(db, pWhere);
73096  if( iFkIfZero ){
73097    sqlite3VdbeJumpHere(v, iFkIfZero);
73098  }
73099}
73100
73101/*
73102** This function returns a pointer to the head of a linked list of FK
73103** constraints for which table pTab is the parent table. For example,
73104** given the following schema:
73105**
73106**   CREATE TABLE t1(a PRIMARY KEY);
73107**   CREATE TABLE t2(b REFERENCES t1(a);
73108**
73109** Calling this function with table "t1" as an argument returns a pointer
73110** to the FKey structure representing the foreign key constraint on table
73111** "t2". Calling this function with "t2" as the argument would return a
73112** NULL pointer (as there are no FK constraints for which t2 is the parent
73113** table).
73114*/
73115SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
73116  int nName = sqlite3Strlen30(pTab->zName);
73117  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
73118}
73119
73120/*
73121** The second argument is a Trigger structure allocated by the
73122** fkActionTrigger() routine. This function deletes the Trigger structure
73123** and all of its sub-components.
73124**
73125** The Trigger structure or any of its sub-components may be allocated from
73126** the lookaside buffer belonging to database handle dbMem.
73127*/
73128static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
73129  if( p ){
73130    TriggerStep *pStep = p->step_list;
73131    sqlite3ExprDelete(dbMem, pStep->pWhere);
73132    sqlite3ExprListDelete(dbMem, pStep->pExprList);
73133    sqlite3SelectDelete(dbMem, pStep->pSelect);
73134    sqlite3ExprDelete(dbMem, p->pWhen);
73135    sqlite3DbFree(dbMem, p);
73136  }
73137}
73138
73139/*
73140** This function is called to generate code that runs when table pTab is
73141** being dropped from the database. The SrcList passed as the second argument
73142** to this function contains a single entry guaranteed to resolve to
73143** table pTab.
73144**
73145** Normally, no code is required. However, if either
73146**
73147**   (a) The table is the parent table of a FK constraint, or
73148**   (b) The table is the child table of a deferred FK constraint and it is
73149**       determined at runtime that there are outstanding deferred FK
73150**       constraint violations in the database,
73151**
73152** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
73153** the table from the database. Triggers are disabled while running this
73154** DELETE, but foreign key actions are not.
73155*/
73156SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
73157  sqlite3 *db = pParse->db;
73158  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
73159    int iSkip = 0;
73160    Vdbe *v = sqlite3GetVdbe(pParse);
73161
73162    assert( v );                  /* VDBE has already been allocated */
73163    if( sqlite3FkReferences(pTab)==0 ){
73164      /* Search for a deferred foreign key constraint for which this table
73165      ** is the child table. If one cannot be found, return without
73166      ** generating any VDBE code. If one can be found, then jump over
73167      ** the entire DELETE if there are no outstanding deferred constraints
73168      ** when this statement is run.  */
73169      FKey *p;
73170      for(p=pTab->pFKey; p; p=p->pNextFrom){
73171        if( p->isDeferred ) break;
73172      }
73173      if( !p ) return;
73174      iSkip = sqlite3VdbeMakeLabel(v);
73175      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
73176    }
73177
73178    pParse->disableTriggers = 1;
73179    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
73180    pParse->disableTriggers = 0;
73181
73182    /* If the DELETE has generated immediate foreign key constraint
73183    ** violations, halt the VDBE and return an error at this point, before
73184    ** any modifications to the schema are made. This is because statement
73185    ** transactions are not able to rollback schema changes.  */
73186    sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
73187    sqlite3HaltConstraint(
73188        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
73189    );
73190
73191    if( iSkip ){
73192      sqlite3VdbeResolveLabel(v, iSkip);
73193    }
73194  }
73195}
73196
73197/*
73198** This function is called when inserting, deleting or updating a row of
73199** table pTab to generate VDBE code to perform foreign key constraint
73200** processing for the operation.
73201**
73202** For a DELETE operation, parameter regOld is passed the index of the
73203** first register in an array of (pTab->nCol+1) registers containing the
73204** rowid of the row being deleted, followed by each of the column values
73205** of the row being deleted, from left to right. Parameter regNew is passed
73206** zero in this case.
73207**
73208** For an INSERT operation, regOld is passed zero and regNew is passed the
73209** first register of an array of (pTab->nCol+1) registers containing the new
73210** row data.
73211**
73212** For an UPDATE operation, this function is called twice. Once before
73213** the original record is deleted from the table using the calling convention
73214** described for DELETE. Then again after the original record is deleted
73215** but before the new record is inserted using the INSERT convention.
73216*/
73217SQLITE_PRIVATE void sqlite3FkCheck(
73218  Parse *pParse,                  /* Parse context */
73219  Table *pTab,                    /* Row is being deleted from this table */
73220  int regOld,                     /* Previous row data is stored here */
73221  int regNew                      /* New row data is stored here */
73222){
73223  sqlite3 *db = pParse->db;       /* Database handle */
73224  Vdbe *v;                        /* VM to write code to */
73225  FKey *pFKey;                    /* Used to iterate through FKs */
73226  int iDb;                        /* Index of database containing pTab */
73227  const char *zDb;                /* Name of database containing pTab */
73228  int isIgnoreErrors = pParse->disableTriggers;
73229
73230  /* Exactly one of regOld and regNew should be non-zero. */
73231  assert( (regOld==0)!=(regNew==0) );
73232
73233  /* If foreign-keys are disabled, this function is a no-op. */
73234  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
73235
73236  v = sqlite3GetVdbe(pParse);
73237  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73238  zDb = db->aDb[iDb].zName;
73239
73240  /* Loop through all the foreign key constraints for which pTab is the
73241  ** child table (the table that the foreign key definition is part of).  */
73242  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
73243    Table *pTo;                   /* Parent table of foreign key pFKey */
73244    Index *pIdx = 0;              /* Index on key columns in pTo */
73245    int *aiFree = 0;
73246    int *aiCol;
73247    int iCol;
73248    int i;
73249    int isIgnore = 0;
73250
73251    /* Find the parent table of this foreign key. Also find a unique index
73252    ** on the parent key columns in the parent table. If either of these
73253    ** schema items cannot be located, set an error in pParse and return
73254    ** early.  */
73255    if( pParse->disableTriggers ){
73256      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
73257    }else{
73258      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
73259    }
73260    if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
73261      if( !isIgnoreErrors || db->mallocFailed ) return;
73262      continue;
73263    }
73264    assert( pFKey->nCol==1 || (aiFree && pIdx) );
73265
73266    if( aiFree ){
73267      aiCol = aiFree;
73268    }else{
73269      iCol = pFKey->aCol[0].iFrom;
73270      aiCol = &iCol;
73271    }
73272    for(i=0; i<pFKey->nCol; i++){
73273      if( aiCol[i]==pTab->iPKey ){
73274        aiCol[i] = -1;
73275      }
73276#ifndef SQLITE_OMIT_AUTHORIZATION
73277      /* Request permission to read the parent key columns. If the
73278      ** authorization callback returns SQLITE_IGNORE, behave as if any
73279      ** values read from the parent table are NULL. */
73280      if( db->xAuth ){
73281        int rcauth;
73282        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
73283        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
73284        isIgnore = (rcauth==SQLITE_IGNORE);
73285      }
73286#endif
73287    }
73288
73289    /* Take a shared-cache advisory read-lock on the parent table. Allocate
73290    ** a cursor to use to search the unique index on the parent key columns
73291    ** in the parent table.  */
73292    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
73293    pParse->nTab++;
73294
73295    if( regOld!=0 ){
73296      /* A row is being removed from the child table. Search for the parent.
73297      ** If the parent does not exist, removing the child row resolves an
73298      ** outstanding foreign key constraint violation. */
73299      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
73300    }
73301    if( regNew!=0 ){
73302      /* A row is being added to the child table. If a parent row cannot
73303      ** be found, adding the child row has violated the FK constraint. */
73304      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
73305    }
73306
73307    sqlite3DbFree(db, aiFree);
73308  }
73309
73310  /* Loop through all the foreign key constraints that refer to this table */
73311  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
73312    Index *pIdx = 0;              /* Foreign key index for pFKey */
73313    SrcList *pSrc;
73314    int *aiCol = 0;
73315
73316    if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
73317      assert( regOld==0 && regNew!=0 );
73318      /* Inserting a single row into a parent table cannot cause an immediate
73319      ** foreign key violation. So do nothing in this case.  */
73320      continue;
73321    }
73322
73323    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
73324      if( !isIgnoreErrors || db->mallocFailed ) return;
73325      continue;
73326    }
73327    assert( aiCol || pFKey->nCol==1 );
73328
73329    /* Create a SrcList structure containing a single table (the table
73330    ** the foreign key that refers to this table is attached to). This
73331    ** is required for the sqlite3WhereXXX() interface.  */
73332    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
73333    if( pSrc ){
73334      struct SrcList_item *pItem = pSrc->a;
73335      pItem->pTab = pFKey->pFrom;
73336      pItem->zName = pFKey->pFrom->zName;
73337      pItem->pTab->nRef++;
73338      pItem->iCursor = pParse->nTab++;
73339
73340      if( regNew!=0 ){
73341        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
73342      }
73343      if( regOld!=0 ){
73344        /* If there is a RESTRICT action configured for the current operation
73345        ** on the parent table of this FK, then throw an exception
73346        ** immediately if the FK constraint is violated, even if this is a
73347        ** deferred trigger. That's what RESTRICT means. To defer checking
73348        ** the constraint, the FK should specify NO ACTION (represented
73349        ** using OE_None). NO ACTION is the default.  */
73350        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
73351      }
73352      pItem->zName = 0;
73353      sqlite3SrcListDelete(db, pSrc);
73354    }
73355    sqlite3DbFree(db, aiCol);
73356  }
73357}
73358
73359#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
73360
73361/*
73362** This function is called before generating code to update or delete a
73363** row contained in table pTab.
73364*/
73365SQLITE_PRIVATE u32 sqlite3FkOldmask(
73366  Parse *pParse,                  /* Parse context */
73367  Table *pTab                     /* Table being modified */
73368){
73369  u32 mask = 0;
73370  if( pParse->db->flags&SQLITE_ForeignKeys ){
73371    FKey *p;
73372    int i;
73373    for(p=pTab->pFKey; p; p=p->pNextFrom){
73374      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
73375    }
73376    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
73377      Index *pIdx = 0;
73378      locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
73379      if( pIdx ){
73380        for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
73381      }
73382    }
73383  }
73384  return mask;
73385}
73386
73387/*
73388** This function is called before generating code to update or delete a
73389** row contained in table pTab. If the operation is a DELETE, then
73390** parameter aChange is passed a NULL value. For an UPDATE, aChange points
73391** to an array of size N, where N is the number of columns in table pTab.
73392** If the i'th column is not modified by the UPDATE, then the corresponding
73393** entry in the aChange[] array is set to -1. If the column is modified,
73394** the value is 0 or greater. Parameter chngRowid is set to true if the
73395** UPDATE statement modifies the rowid fields of the table.
73396**
73397** If any foreign key processing will be required, this function returns
73398** true. If there is no foreign key related processing, this function
73399** returns false.
73400*/
73401SQLITE_PRIVATE int sqlite3FkRequired(
73402  Parse *pParse,                  /* Parse context */
73403  Table *pTab,                    /* Table being modified */
73404  int *aChange,                   /* Non-NULL for UPDATE operations */
73405  int chngRowid                   /* True for UPDATE that affects rowid */
73406){
73407  if( pParse->db->flags&SQLITE_ForeignKeys ){
73408    if( !aChange ){
73409      /* A DELETE operation. Foreign key processing is required if the
73410      ** table in question is either the child or parent table for any
73411      ** foreign key constraint.  */
73412      return (sqlite3FkReferences(pTab) || pTab->pFKey);
73413    }else{
73414      /* This is an UPDATE. Foreign key processing is only required if the
73415      ** operation modifies one or more child or parent key columns. */
73416      int i;
73417      FKey *p;
73418
73419      /* Check if any child key columns are being modified. */
73420      for(p=pTab->pFKey; p; p=p->pNextFrom){
73421        for(i=0; i<p->nCol; i++){
73422          int iChildKey = p->aCol[i].iFrom;
73423          if( aChange[iChildKey]>=0 ) return 1;
73424          if( iChildKey==pTab->iPKey && chngRowid ) return 1;
73425        }
73426      }
73427
73428      /* Check if any parent key columns are being modified. */
73429      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
73430        for(i=0; i<p->nCol; i++){
73431          char *zKey = p->aCol[i].zCol;
73432          int iKey;
73433          for(iKey=0; iKey<pTab->nCol; iKey++){
73434            Column *pCol = &pTab->aCol[iKey];
73435            if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
73436              if( aChange[iKey]>=0 ) return 1;
73437              if( iKey==pTab->iPKey && chngRowid ) return 1;
73438            }
73439          }
73440        }
73441      }
73442    }
73443  }
73444  return 0;
73445}
73446
73447/*
73448** This function is called when an UPDATE or DELETE operation is being
73449** compiled on table pTab, which is the parent table of foreign-key pFKey.
73450** If the current operation is an UPDATE, then the pChanges parameter is
73451** passed a pointer to the list of columns being modified. If it is a
73452** DELETE, pChanges is passed a NULL pointer.
73453**
73454** It returns a pointer to a Trigger structure containing a trigger
73455** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
73456** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
73457** returned (these actions require no special handling by the triggers
73458** sub-system, code for them is created by fkScanChildren()).
73459**
73460** For example, if pFKey is the foreign key and pTab is table "p" in
73461** the following schema:
73462**
73463**   CREATE TABLE p(pk PRIMARY KEY);
73464**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
73465**
73466** then the returned trigger structure is equivalent to:
73467**
73468**   CREATE TRIGGER ... DELETE ON p BEGIN
73469**     DELETE FROM c WHERE ck = old.pk;
73470**   END;
73471**
73472** The returned pointer is cached as part of the foreign key object. It
73473** is eventually freed along with the rest of the foreign key object by
73474** sqlite3FkDelete().
73475*/
73476static Trigger *fkActionTrigger(
73477  Parse *pParse,                  /* Parse context */
73478  Table *pTab,                    /* Table being updated or deleted from */
73479  FKey *pFKey,                    /* Foreign key to get action for */
73480  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
73481){
73482  sqlite3 *db = pParse->db;       /* Database handle */
73483  int action;                     /* One of OE_None, OE_Cascade etc. */
73484  Trigger *pTrigger;              /* Trigger definition to return */
73485  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
73486
73487  action = pFKey->aAction[iAction];
73488  pTrigger = pFKey->apTrigger[iAction];
73489
73490  if( action!=OE_None && !pTrigger ){
73491    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
73492    char const *zFrom;            /* Name of child table */
73493    int nFrom;                    /* Length in bytes of zFrom */
73494    Index *pIdx = 0;              /* Parent key index for this FK */
73495    int *aiCol = 0;               /* child table cols -> parent key cols */
73496    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
73497    Expr *pWhere = 0;             /* WHERE clause of trigger step */
73498    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
73499    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
73500    int i;                        /* Iterator variable */
73501    Expr *pWhen = 0;              /* WHEN clause for the trigger */
73502
73503    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
73504    assert( aiCol || pFKey->nCol==1 );
73505
73506    for(i=0; i<pFKey->nCol; i++){
73507      Token tOld = { "old", 3 };  /* Literal "old" token */
73508      Token tNew = { "new", 3 };  /* Literal "new" token */
73509      Token tFromCol;             /* Name of column in child table */
73510      Token tToCol;               /* Name of column in parent table */
73511      int iFromCol;               /* Idx of column in child table */
73512      Expr *pEq;                  /* tFromCol = OLD.tToCol */
73513
73514      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
73515      assert( iFromCol>=0 );
73516      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
73517      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
73518
73519      tToCol.n = sqlite3Strlen30(tToCol.z);
73520      tFromCol.n = sqlite3Strlen30(tFromCol.z);
73521
73522      /* Create the expression "OLD.zToCol = zFromCol". It is important
73523      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
73524      ** that the affinity and collation sequence associated with the
73525      ** parent table are used for the comparison. */
73526      pEq = sqlite3PExpr(pParse, TK_EQ,
73527          sqlite3PExpr(pParse, TK_DOT,
73528            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
73529            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
73530          , 0),
73531          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
73532      , 0);
73533      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
73534
73535      /* For ON UPDATE, construct the next term of the WHEN clause.
73536      ** The final WHEN clause will be like this:
73537      **
73538      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
73539      */
73540      if( pChanges ){
73541        pEq = sqlite3PExpr(pParse, TK_IS,
73542            sqlite3PExpr(pParse, TK_DOT,
73543              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
73544              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
73545              0),
73546            sqlite3PExpr(pParse, TK_DOT,
73547              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
73548              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
73549              0),
73550            0);
73551        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
73552      }
73553
73554      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
73555        Expr *pNew;
73556        if( action==OE_Cascade ){
73557          pNew = sqlite3PExpr(pParse, TK_DOT,
73558            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
73559            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
73560          , 0);
73561        }else if( action==OE_SetDflt ){
73562          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
73563          if( pDflt ){
73564            pNew = sqlite3ExprDup(db, pDflt, 0);
73565          }else{
73566            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
73567          }
73568        }else{
73569          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
73570        }
73571        pList = sqlite3ExprListAppend(pParse, pList, pNew);
73572        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
73573      }
73574    }
73575    sqlite3DbFree(db, aiCol);
73576
73577    zFrom = pFKey->pFrom->zName;
73578    nFrom = sqlite3Strlen30(zFrom);
73579
73580    if( action==OE_Restrict ){
73581      Token tFrom;
73582      Expr *pRaise;
73583
73584      tFrom.z = zFrom;
73585      tFrom.n = nFrom;
73586      pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
73587      if( pRaise ){
73588        pRaise->affinity = OE_Abort;
73589      }
73590      pSelect = sqlite3SelectNew(pParse,
73591          sqlite3ExprListAppend(pParse, 0, pRaise),
73592          sqlite3SrcListAppend(db, 0, &tFrom, 0),
73593          pWhere,
73594          0, 0, 0, 0, 0, 0
73595      );
73596      pWhere = 0;
73597    }
73598
73599    /* In the current implementation, pTab->dbMem==0 for all tables except
73600    ** for temporary tables used to describe subqueries.  And temporary
73601    ** tables do not have foreign key constraints.  Hence, pTab->dbMem
73602    ** should always be 0 there.
73603    */
73604    enableLookaside = db->lookaside.bEnabled;
73605    db->lookaside.bEnabled = 0;
73606
73607    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
73608        sizeof(Trigger) +         /* struct Trigger */
73609        sizeof(TriggerStep) +     /* Single step in trigger program */
73610        nFrom + 1                 /* Space for pStep->target.z */
73611    );
73612    if( pTrigger ){
73613      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
73614      pStep->target.z = (char *)&pStep[1];
73615      pStep->target.n = nFrom;
73616      memcpy((char *)pStep->target.z, zFrom, nFrom);
73617
73618      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
73619      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
73620      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
73621      if( pWhen ){
73622        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
73623        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
73624      }
73625    }
73626
73627    /* Re-enable the lookaside buffer, if it was disabled earlier. */
73628    db->lookaside.bEnabled = enableLookaside;
73629
73630    sqlite3ExprDelete(db, pWhere);
73631    sqlite3ExprDelete(db, pWhen);
73632    sqlite3ExprListDelete(db, pList);
73633    sqlite3SelectDelete(db, pSelect);
73634    if( db->mallocFailed==1 ){
73635      fkTriggerDelete(db, pTrigger);
73636      return 0;
73637    }
73638
73639    switch( action ){
73640      case OE_Restrict:
73641        pStep->op = TK_SELECT;
73642        break;
73643      case OE_Cascade:
73644        if( !pChanges ){
73645          pStep->op = TK_DELETE;
73646          break;
73647        }
73648      default:
73649        pStep->op = TK_UPDATE;
73650    }
73651    pStep->pTrig = pTrigger;
73652    pTrigger->pSchema = pTab->pSchema;
73653    pTrigger->pTabSchema = pTab->pSchema;
73654    pFKey->apTrigger[iAction] = pTrigger;
73655    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
73656  }
73657
73658  return pTrigger;
73659}
73660
73661/*
73662** This function is called when deleting or updating a row to implement
73663** any required CASCADE, SET NULL or SET DEFAULT actions.
73664*/
73665SQLITE_PRIVATE void sqlite3FkActions(
73666  Parse *pParse,                  /* Parse context */
73667  Table *pTab,                    /* Table being updated or deleted from */
73668  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
73669  int regOld                      /* Address of array containing old row */
73670){
73671  /* If foreign-key support is enabled, iterate through all FKs that
73672  ** refer to table pTab. If there is an action associated with the FK
73673  ** for this operation (either update or delete), invoke the associated
73674  ** trigger sub-program.  */
73675  if( pParse->db->flags&SQLITE_ForeignKeys ){
73676    FKey *pFKey;                  /* Iterator variable */
73677    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
73678      Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
73679      if( pAction ){
73680        sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
73681      }
73682    }
73683  }
73684}
73685
73686#endif /* ifndef SQLITE_OMIT_TRIGGER */
73687
73688/*
73689** Free all memory associated with foreign key definitions attached to
73690** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
73691** hash table.
73692*/
73693SQLITE_PRIVATE void sqlite3FkDelete(Table *pTab){
73694  FKey *pFKey;                    /* Iterator variable */
73695  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
73696
73697  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
73698
73699    /* Remove the FK from the fkeyHash hash table. */
73700    if( pFKey->pPrevTo ){
73701      pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
73702    }else{
73703      void *data = (void *)pFKey->pNextTo;
73704      const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
73705      sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
73706    }
73707    if( pFKey->pNextTo ){
73708      pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
73709    }
73710
73711    /* Delete any triggers created to implement actions for this FK. */
73712#ifndef SQLITE_OMIT_TRIGGER
73713    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
73714    fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
73715#endif
73716
73717    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
73718    ** classified as either immediate or deferred.
73719    */
73720    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
73721
73722    pNext = pFKey->pNextFrom;
73723    sqlite3DbFree(pTab->dbMem, pFKey);
73724  }
73725}
73726#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
73727
73728/************** End of fkey.c ************************************************/
73729/************** Begin file insert.c ******************************************/
73730/*
73731** 2001 September 15
73732**
73733** The author disclaims copyright to this source code.  In place of
73734** a legal notice, here is a blessing:
73735**
73736**    May you do good and not evil.
73737**    May you find forgiveness for yourself and forgive others.
73738**    May you share freely, never taking more than you give.
73739**
73740*************************************************************************
73741** This file contains C code routines that are called by the parser
73742** to handle INSERT statements in SQLite.
73743*/
73744
73745/*
73746** Generate code that will open a table for reading.
73747*/
73748SQLITE_PRIVATE void sqlite3OpenTable(
73749  Parse *p,       /* Generate code into this VDBE */
73750  int iCur,       /* The cursor number of the table */
73751  int iDb,        /* The database index in sqlite3.aDb[] */
73752  Table *pTab,    /* The table to be opened */
73753  int opcode      /* OP_OpenRead or OP_OpenWrite */
73754){
73755  Vdbe *v;
73756  if( IsVirtual(pTab) ) return;
73757  v = sqlite3GetVdbe(p);
73758  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
73759  sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
73760  sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
73761  sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
73762  VdbeComment((v, "%s", pTab->zName));
73763}
73764
73765/*
73766** Return a pointer to the column affinity string associated with index
73767** pIdx. A column affinity string has one character for each column in
73768** the table, according to the affinity of the column:
73769**
73770**  Character      Column affinity
73771**  ------------------------------
73772**  'a'            TEXT
73773**  'b'            NONE
73774**  'c'            NUMERIC
73775**  'd'            INTEGER
73776**  'e'            REAL
73777**
73778** An extra 'b' is appended to the end of the string to cover the
73779** rowid that appears as the last column in every index.
73780**
73781** Memory for the buffer containing the column index affinity string
73782** is managed along with the rest of the Index structure. It will be
73783** released when sqlite3DeleteIndex() is called.
73784*/
73785SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
73786  if( !pIdx->zColAff ){
73787    /* The first time a column affinity string for a particular index is
73788    ** required, it is allocated and populated here. It is then stored as
73789    ** a member of the Index structure for subsequent use.
73790    **
73791    ** The column affinity string will eventually be deleted by
73792    ** sqliteDeleteIndex() when the Index structure itself is cleaned
73793    ** up.
73794    */
73795    int n;
73796    Table *pTab = pIdx->pTable;
73797    sqlite3 *db = sqlite3VdbeDb(v);
73798    pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
73799    if( !pIdx->zColAff ){
73800      db->mallocFailed = 1;
73801      return 0;
73802    }
73803    for(n=0; n<pIdx->nColumn; n++){
73804      pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
73805    }
73806    pIdx->zColAff[n++] = SQLITE_AFF_NONE;
73807    pIdx->zColAff[n] = 0;
73808  }
73809
73810  return pIdx->zColAff;
73811}
73812
73813/*
73814** Set P4 of the most recently inserted opcode to a column affinity
73815** string for table pTab. A column affinity string has one character
73816** for each column indexed by the index, according to the affinity of the
73817** column:
73818**
73819**  Character      Column affinity
73820**  ------------------------------
73821**  'a'            TEXT
73822**  'b'            NONE
73823**  'c'            NUMERIC
73824**  'd'            INTEGER
73825**  'e'            REAL
73826*/
73827SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
73828  /* The first time a column affinity string for a particular table
73829  ** is required, it is allocated and populated here. It is then
73830  ** stored as a member of the Table structure for subsequent use.
73831  **
73832  ** The column affinity string will eventually be deleted by
73833  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
73834  */
73835  if( !pTab->zColAff ){
73836    char *zColAff;
73837    int i;
73838    sqlite3 *db = sqlite3VdbeDb(v);
73839
73840    zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
73841    if( !zColAff ){
73842      db->mallocFailed = 1;
73843      return;
73844    }
73845
73846    for(i=0; i<pTab->nCol; i++){
73847      zColAff[i] = pTab->aCol[i].affinity;
73848    }
73849    zColAff[pTab->nCol] = '\0';
73850
73851    pTab->zColAff = zColAff;
73852  }
73853
73854  sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
73855}
73856
73857/*
73858** Return non-zero if the table pTab in database iDb or any of its indices
73859** have been opened at any point in the VDBE program beginning at location
73860** iStartAddr throught the end of the program.  This is used to see if
73861** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
73862** run without using temporary table for the results of the SELECT.
73863*/
73864static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
73865  Vdbe *v = sqlite3GetVdbe(p);
73866  int i;
73867  int iEnd = sqlite3VdbeCurrentAddr(v);
73868#ifndef SQLITE_OMIT_VIRTUALTABLE
73869  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
73870#endif
73871
73872  for(i=iStartAddr; i<iEnd; i++){
73873    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
73874    assert( pOp!=0 );
73875    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
73876      Index *pIndex;
73877      int tnum = pOp->p2;
73878      if( tnum==pTab->tnum ){
73879        return 1;
73880      }
73881      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
73882        if( tnum==pIndex->tnum ){
73883          return 1;
73884        }
73885      }
73886    }
73887#ifndef SQLITE_OMIT_VIRTUALTABLE
73888    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
73889      assert( pOp->p4.pVtab!=0 );
73890      assert( pOp->p4type==P4_VTAB );
73891      return 1;
73892    }
73893#endif
73894  }
73895  return 0;
73896}
73897
73898#ifndef SQLITE_OMIT_AUTOINCREMENT
73899/*
73900** Locate or create an AutoincInfo structure associated with table pTab
73901** which is in database iDb.  Return the register number for the register
73902** that holds the maximum rowid.
73903**
73904** There is at most one AutoincInfo structure per table even if the
73905** same table is autoincremented multiple times due to inserts within
73906** triggers.  A new AutoincInfo structure is created if this is the
73907** first use of table pTab.  On 2nd and subsequent uses, the original
73908** AutoincInfo structure is used.
73909**
73910** Three memory locations are allocated:
73911**
73912**   (1)  Register to hold the name of the pTab table.
73913**   (2)  Register to hold the maximum ROWID of pTab.
73914**   (3)  Register to hold the rowid in sqlite_sequence of pTab
73915**
73916** The 2nd register is the one that is returned.  That is all the
73917** insert routine needs to know about.
73918*/
73919static int autoIncBegin(
73920  Parse *pParse,      /* Parsing context */
73921  int iDb,            /* Index of the database holding pTab */
73922  Table *pTab         /* The table we are writing to */
73923){
73924  int memId = 0;      /* Register holding maximum rowid */
73925  if( pTab->tabFlags & TF_Autoincrement ){
73926    Parse *pToplevel = sqlite3ParseToplevel(pParse);
73927    AutoincInfo *pInfo;
73928
73929    pInfo = pToplevel->pAinc;
73930    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
73931    if( pInfo==0 ){
73932      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
73933      if( pInfo==0 ) return 0;
73934      pInfo->pNext = pToplevel->pAinc;
73935      pToplevel->pAinc = pInfo;
73936      pInfo->pTab = pTab;
73937      pInfo->iDb = iDb;
73938      pToplevel->nMem++;                  /* Register to hold name of table */
73939      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
73940      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
73941    }
73942    memId = pInfo->regCtr;
73943  }
73944  return memId;
73945}
73946
73947/*
73948** This routine generates code that will initialize all of the
73949** register used by the autoincrement tracker.
73950*/
73951SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
73952  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
73953  sqlite3 *db = pParse->db;  /* The database connection */
73954  Db *pDb;                   /* Database only autoinc table */
73955  int memId;                 /* Register holding max rowid */
73956  int addr;                  /* A VDBE address */
73957  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
73958
73959  /* This routine is never called during trigger-generation.  It is
73960  ** only called from the top-level */
73961  assert( pParse->pTriggerTab==0 );
73962  assert( pParse==sqlite3ParseToplevel(pParse) );
73963
73964  assert( v );   /* We failed long ago if this is not so */
73965  for(p = pParse->pAinc; p; p = p->pNext){
73966    pDb = &db->aDb[p->iDb];
73967    memId = p->regCtr;
73968    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
73969    addr = sqlite3VdbeCurrentAddr(v);
73970    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
73971    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
73972    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
73973    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
73974    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
73975    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
73976    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
73977    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
73978    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
73979    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
73980    sqlite3VdbeAddOp0(v, OP_Close);
73981  }
73982}
73983
73984/*
73985** Update the maximum rowid for an autoincrement calculation.
73986**
73987** This routine should be called when the top of the stack holds a
73988** new rowid that is about to be inserted.  If that new rowid is
73989** larger than the maximum rowid in the memId memory cell, then the
73990** memory cell is updated.  The stack is unchanged.
73991*/
73992static void autoIncStep(Parse *pParse, int memId, int regRowid){
73993  if( memId>0 ){
73994    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
73995  }
73996}
73997
73998/*
73999** This routine generates the code needed to write autoincrement
74000** maximum rowid values back into the sqlite_sequence register.
74001** Every statement that might do an INSERT into an autoincrement
74002** table (either directly or through triggers) needs to call this
74003** routine just before the "exit" code.
74004*/
74005SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
74006  AutoincInfo *p;
74007  Vdbe *v = pParse->pVdbe;
74008  sqlite3 *db = pParse->db;
74009
74010  assert( v );
74011  for(p = pParse->pAinc; p; p = p->pNext){
74012    Db *pDb = &db->aDb[p->iDb];
74013    int j1, j2, j3, j4, j5;
74014    int iRec;
74015    int memId = p->regCtr;
74016
74017    iRec = sqlite3GetTempReg(pParse);
74018    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
74019    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
74020    j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
74021    j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
74022    j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
74023    sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
74024    sqlite3VdbeJumpHere(v, j2);
74025    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
74026    j5 = sqlite3VdbeAddOp0(v, OP_Goto);
74027    sqlite3VdbeJumpHere(v, j4);
74028    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
74029    sqlite3VdbeJumpHere(v, j1);
74030    sqlite3VdbeJumpHere(v, j5);
74031    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
74032    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
74033    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
74034    sqlite3VdbeAddOp0(v, OP_Close);
74035    sqlite3ReleaseTempReg(pParse, iRec);
74036  }
74037}
74038#else
74039/*
74040** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
74041** above are all no-ops
74042*/
74043# define autoIncBegin(A,B,C) (0)
74044# define autoIncStep(A,B,C)
74045#endif /* SQLITE_OMIT_AUTOINCREMENT */
74046
74047
74048/* Forward declaration */
74049static int xferOptimization(
74050  Parse *pParse,        /* Parser context */
74051  Table *pDest,         /* The table we are inserting into */
74052  Select *pSelect,      /* A SELECT statement to use as the data source */
74053  int onError,          /* How to handle constraint errors */
74054  int iDbDest           /* The database of pDest */
74055);
74056
74057/*
74058** This routine is call to handle SQL of the following forms:
74059**
74060**    insert into TABLE (IDLIST) values(EXPRLIST)
74061**    insert into TABLE (IDLIST) select
74062**
74063** The IDLIST following the table name is always optional.  If omitted,
74064** then a list of all columns for the table is substituted.  The IDLIST
74065** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
74066**
74067** The pList parameter holds EXPRLIST in the first form of the INSERT
74068** statement above, and pSelect is NULL.  For the second form, pList is
74069** NULL and pSelect is a pointer to the select statement used to generate
74070** data for the insert.
74071**
74072** The code generated follows one of four templates.  For a simple
74073** select with data coming from a VALUES clause, the code executes
74074** once straight down through.  Pseudo-code follows (we call this
74075** the "1st template"):
74076**
74077**         open write cursor to <table> and its indices
74078**         puts VALUES clause expressions onto the stack
74079**         write the resulting record into <table>
74080**         cleanup
74081**
74082** The three remaining templates assume the statement is of the form
74083**
74084**   INSERT INTO <table> SELECT ...
74085**
74086** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
74087** in other words if the SELECT pulls all columns from a single table
74088** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
74089** if <table2> and <table1> are distinct tables but have identical
74090** schemas, including all the same indices, then a special optimization
74091** is invoked that copies raw records from <table2> over to <table1>.
74092** See the xferOptimization() function for the implementation of this
74093** template.  This is the 2nd template.
74094**
74095**         open a write cursor to <table>
74096**         open read cursor on <table2>
74097**         transfer all records in <table2> over to <table>
74098**         close cursors
74099**         foreach index on <table>
74100**           open a write cursor on the <table> index
74101**           open a read cursor on the corresponding <table2> index
74102**           transfer all records from the read to the write cursors
74103**           close cursors
74104**         end foreach
74105**
74106** The 3rd template is for when the second template does not apply
74107** and the SELECT clause does not read from <table> at any time.
74108** The generated code follows this template:
74109**
74110**         EOF <- 0
74111**         X <- A
74112**         goto B
74113**      A: setup for the SELECT
74114**         loop over the rows in the SELECT
74115**           load values into registers R..R+n
74116**           yield X
74117**         end loop
74118**         cleanup after the SELECT
74119**         EOF <- 1
74120**         yield X
74121**         goto A
74122**      B: open write cursor to <table> and its indices
74123**      C: yield X
74124**         if EOF goto D
74125**         insert the select result into <table> from R..R+n
74126**         goto C
74127**      D: cleanup
74128**
74129** The 4th template is used if the insert statement takes its
74130** values from a SELECT but the data is being inserted into a table
74131** that is also read as part of the SELECT.  In the third form,
74132** we have to use a intermediate table to store the results of
74133** the select.  The template is like this:
74134**
74135**         EOF <- 0
74136**         X <- A
74137**         goto B
74138**      A: setup for the SELECT
74139**         loop over the tables in the SELECT
74140**           load value into register R..R+n
74141**           yield X
74142**         end loop
74143**         cleanup after the SELECT
74144**         EOF <- 1
74145**         yield X
74146**         halt-error
74147**      B: open temp table
74148**      L: yield X
74149**         if EOF goto M
74150**         insert row from R..R+n into temp table
74151**         goto L
74152**      M: open write cursor to <table> and its indices
74153**         rewind temp table
74154**      C: loop over rows of intermediate table
74155**           transfer values form intermediate table into <table>
74156**         end loop
74157**      D: cleanup
74158*/
74159SQLITE_PRIVATE void sqlite3Insert(
74160  Parse *pParse,        /* Parser context */
74161  SrcList *pTabList,    /* Name of table into which we are inserting */
74162  ExprList *pList,      /* List of values to be inserted */
74163  Select *pSelect,      /* A SELECT statement to use as the data source */
74164  IdList *pColumn,      /* Column names corresponding to IDLIST. */
74165  int onError           /* How to handle constraint errors */
74166){
74167  sqlite3 *db;          /* The main database structure */
74168  Table *pTab;          /* The table to insert into.  aka TABLE */
74169  char *zTab;           /* Name of the table into which we are inserting */
74170  const char *zDb;      /* Name of the database holding this table */
74171  int i, j, idx;        /* Loop counters */
74172  Vdbe *v;              /* Generate code into this virtual machine */
74173  Index *pIdx;          /* For looping over indices of the table */
74174  int nColumn;          /* Number of columns in the data */
74175  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
74176  int baseCur = 0;      /* VDBE Cursor number for pTab */
74177  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
74178  int endOfLoop;        /* Label for the end of the insertion loop */
74179  int useTempTable = 0; /* Store SELECT results in intermediate table */
74180  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
74181  int addrInsTop = 0;   /* Jump to label "D" */
74182  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
74183  int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
74184  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
74185  int iDb;              /* Index of database holding TABLE */
74186  Db *pDb;              /* The database containing table being inserted into */
74187  int appendFlag = 0;   /* True if the insert is likely to be an append */
74188
74189  /* Register allocations */
74190  int regFromSelect = 0;/* Base register for data coming from SELECT */
74191  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
74192  int regRowCount = 0;  /* Memory cell used for the row counter */
74193  int regIns;           /* Block of regs holding rowid+data being inserted */
74194  int regRowid;         /* registers holding insert rowid */
74195  int regData;          /* register holding first column to insert */
74196  int regRecord;        /* Holds the assemblied row record */
74197  int regEof = 0;       /* Register recording end of SELECT data */
74198  int *aRegIdx = 0;     /* One register allocated to each index */
74199
74200#ifndef SQLITE_OMIT_TRIGGER
74201  int isView;                 /* True if attempting to insert into a view */
74202  Trigger *pTrigger;          /* List of triggers on pTab, if required */
74203  int tmask;                  /* Mask of trigger times */
74204#endif
74205
74206  db = pParse->db;
74207  memset(&dest, 0, sizeof(dest));
74208  if( pParse->nErr || db->mallocFailed ){
74209    goto insert_cleanup;
74210  }
74211
74212  /* Locate the table into which we will be inserting new information.
74213  */
74214  assert( pTabList->nSrc==1 );
74215  zTab = pTabList->a[0].zName;
74216  if( NEVER(zTab==0) ) goto insert_cleanup;
74217  pTab = sqlite3SrcListLookup(pParse, pTabList);
74218  if( pTab==0 ){
74219    goto insert_cleanup;
74220  }
74221  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74222  assert( iDb<db->nDb );
74223  pDb = &db->aDb[iDb];
74224  zDb = pDb->zName;
74225  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
74226    goto insert_cleanup;
74227  }
74228
74229  /* Figure out if we have any triggers and if the table being
74230  ** inserted into is a view
74231  */
74232#ifndef SQLITE_OMIT_TRIGGER
74233  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
74234  isView = pTab->pSelect!=0;
74235#else
74236# define pTrigger 0
74237# define tmask 0
74238# define isView 0
74239#endif
74240#ifdef SQLITE_OMIT_VIEW
74241# undef isView
74242# define isView 0
74243#endif
74244  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
74245
74246  /* If pTab is really a view, make sure it has been initialized.
74247  ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
74248  ** module table).
74249  */
74250  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
74251    goto insert_cleanup;
74252  }
74253
74254  /* Ensure that:
74255  *  (a) the table is not read-only,
74256  *  (b) that if it is a view then ON INSERT triggers exist
74257  */
74258  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
74259    goto insert_cleanup;
74260  }
74261
74262  /* Allocate a VDBE
74263  */
74264  v = sqlite3GetVdbe(pParse);
74265  if( v==0 ) goto insert_cleanup;
74266  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
74267  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
74268
74269#ifndef SQLITE_OMIT_XFER_OPT
74270  /* If the statement is of the form
74271  **
74272  **       INSERT INTO <table1> SELECT * FROM <table2>;
74273  **
74274  ** Then special optimizations can be applied that make the transfer
74275  ** very fast and which reduce fragmentation of indices.
74276  **
74277  ** This is the 2nd template.
74278  */
74279  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
74280    assert( !pTrigger );
74281    assert( pList==0 );
74282    goto insert_end;
74283  }
74284#endif /* SQLITE_OMIT_XFER_OPT */
74285
74286  /* If this is an AUTOINCREMENT table, look up the sequence number in the
74287  ** sqlite_sequence table and store it in memory cell regAutoinc.
74288  */
74289  regAutoinc = autoIncBegin(pParse, iDb, pTab);
74290
74291  /* Figure out how many columns of data are supplied.  If the data
74292  ** is coming from a SELECT statement, then generate a co-routine that
74293  ** produces a single row of the SELECT on each invocation.  The
74294  ** co-routine is the common header to the 3rd and 4th templates.
74295  */
74296  if( pSelect ){
74297    /* Data is coming from a SELECT.  Generate code to implement that SELECT
74298    ** as a co-routine.  The code is common to both the 3rd and 4th
74299    ** templates:
74300    **
74301    **         EOF <- 0
74302    **         X <- A
74303    **         goto B
74304    **      A: setup for the SELECT
74305    **         loop over the tables in the SELECT
74306    **           load value into register R..R+n
74307    **           yield X
74308    **         end loop
74309    **         cleanup after the SELECT
74310    **         EOF <- 1
74311    **         yield X
74312    **         halt-error
74313    **
74314    ** On each invocation of the co-routine, it puts a single row of the
74315    ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
74316    ** (These output registers are allocated by sqlite3Select().)  When
74317    ** the SELECT completes, it sets the EOF flag stored in regEof.
74318    */
74319    int rc, j1;
74320
74321    regEof = ++pParse->nMem;
74322    sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
74323    VdbeComment((v, "SELECT eof flag"));
74324    sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
74325    addrSelect = sqlite3VdbeCurrentAddr(v)+2;
74326    sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
74327    j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
74328    VdbeComment((v, "Jump over SELECT coroutine"));
74329
74330    /* Resolve the expressions in the SELECT statement and execute it. */
74331    rc = sqlite3Select(pParse, pSelect, &dest);
74332    assert( pParse->nErr==0 || rc );
74333    if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
74334      goto insert_cleanup;
74335    }
74336    sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
74337    sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
74338    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
74339    VdbeComment((v, "End of SELECT coroutine"));
74340    sqlite3VdbeJumpHere(v, j1);                          /* label B: */
74341
74342    regFromSelect = dest.iMem;
74343    assert( pSelect->pEList );
74344    nColumn = pSelect->pEList->nExpr;
74345    assert( dest.nMem==nColumn );
74346
74347    /* Set useTempTable to TRUE if the result of the SELECT statement
74348    ** should be written into a temporary table (template 4).  Set to
74349    ** FALSE if each* row of the SELECT can be written directly into
74350    ** the destination table (template 3).
74351    **
74352    ** A temp table must be used if the table being updated is also one
74353    ** of the tables being read by the SELECT statement.  Also use a
74354    ** temp table in the case of row triggers.
74355    */
74356    if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
74357      useTempTable = 1;
74358    }
74359
74360    if( useTempTable ){
74361      /* Invoke the coroutine to extract information from the SELECT
74362      ** and add it to a transient table srcTab.  The code generated
74363      ** here is from the 4th template:
74364      **
74365      **      B: open temp table
74366      **      L: yield X
74367      **         if EOF goto M
74368      **         insert row from R..R+n into temp table
74369      **         goto L
74370      **      M: ...
74371      */
74372      int regRec;          /* Register to hold packed record */
74373      int regTempRowid;    /* Register to hold temp table ROWID */
74374      int addrTop;         /* Label "L" */
74375      int addrIf;          /* Address of jump to M */
74376
74377      srcTab = pParse->nTab++;
74378      regRec = sqlite3GetTempReg(pParse);
74379      regTempRowid = sqlite3GetTempReg(pParse);
74380      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
74381      addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
74382      addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
74383      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
74384      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
74385      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
74386      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
74387      sqlite3VdbeJumpHere(v, addrIf);
74388      sqlite3ReleaseTempReg(pParse, regRec);
74389      sqlite3ReleaseTempReg(pParse, regTempRowid);
74390    }
74391  }else{
74392    /* This is the case if the data for the INSERT is coming from a VALUES
74393    ** clause
74394    */
74395    NameContext sNC;
74396    memset(&sNC, 0, sizeof(sNC));
74397    sNC.pParse = pParse;
74398    srcTab = -1;
74399    assert( useTempTable==0 );
74400    nColumn = pList ? pList->nExpr : 0;
74401    for(i=0; i<nColumn; i++){
74402      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
74403        goto insert_cleanup;
74404      }
74405    }
74406  }
74407
74408  /* Make sure the number of columns in the source data matches the number
74409  ** of columns to be inserted into the table.
74410  */
74411  if( IsVirtual(pTab) ){
74412    for(i=0; i<pTab->nCol; i++){
74413      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
74414    }
74415  }
74416  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
74417    sqlite3ErrorMsg(pParse,
74418       "table %S has %d columns but %d values were supplied",
74419       pTabList, 0, pTab->nCol-nHidden, nColumn);
74420    goto insert_cleanup;
74421  }
74422  if( pColumn!=0 && nColumn!=pColumn->nId ){
74423    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
74424    goto insert_cleanup;
74425  }
74426
74427  /* If the INSERT statement included an IDLIST term, then make sure
74428  ** all elements of the IDLIST really are columns of the table and
74429  ** remember the column indices.
74430  **
74431  ** If the table has an INTEGER PRIMARY KEY column and that column
74432  ** is named in the IDLIST, then record in the keyColumn variable
74433  ** the index into IDLIST of the primary key column.  keyColumn is
74434  ** the index of the primary key as it appears in IDLIST, not as
74435  ** is appears in the original table.  (The index of the primary
74436  ** key in the original table is pTab->iPKey.)
74437  */
74438  if( pColumn ){
74439    for(i=0; i<pColumn->nId; i++){
74440      pColumn->a[i].idx = -1;
74441    }
74442    for(i=0; i<pColumn->nId; i++){
74443      for(j=0; j<pTab->nCol; j++){
74444        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
74445          pColumn->a[i].idx = j;
74446          if( j==pTab->iPKey ){
74447            keyColumn = i;
74448          }
74449          break;
74450        }
74451      }
74452      if( j>=pTab->nCol ){
74453        if( sqlite3IsRowid(pColumn->a[i].zName) ){
74454          keyColumn = i;
74455        }else{
74456          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
74457              pTabList, 0, pColumn->a[i].zName);
74458          pParse->nErr++;
74459          goto insert_cleanup;
74460        }
74461      }
74462    }
74463  }
74464
74465  /* If there is no IDLIST term but the table has an integer primary
74466  ** key, the set the keyColumn variable to the primary key column index
74467  ** in the original table definition.
74468  */
74469  if( pColumn==0 && nColumn>0 ){
74470    keyColumn = pTab->iPKey;
74471  }
74472
74473  /* Initialize the count of rows to be inserted
74474  */
74475  if( db->flags & SQLITE_CountRows ){
74476    regRowCount = ++pParse->nMem;
74477    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
74478  }
74479
74480  /* If this is not a view, open the table and and all indices */
74481  if( !isView ){
74482    int nIdx;
74483
74484    baseCur = pParse->nTab;
74485    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
74486    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
74487    if( aRegIdx==0 ){
74488      goto insert_cleanup;
74489    }
74490    for(i=0; i<nIdx; i++){
74491      aRegIdx[i] = ++pParse->nMem;
74492    }
74493  }
74494
74495  /* This is the top of the main insertion loop */
74496  if( useTempTable ){
74497    /* This block codes the top of loop only.  The complete loop is the
74498    ** following pseudocode (template 4):
74499    **
74500    **         rewind temp table
74501    **      C: loop over rows of intermediate table
74502    **           transfer values form intermediate table into <table>
74503    **         end loop
74504    **      D: ...
74505    */
74506    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
74507    addrCont = sqlite3VdbeCurrentAddr(v);
74508  }else if( pSelect ){
74509    /* This block codes the top of loop only.  The complete loop is the
74510    ** following pseudocode (template 3):
74511    **
74512    **      C: yield X
74513    **         if EOF goto D
74514    **         insert the select result into <table> from R..R+n
74515    **         goto C
74516    **      D: ...
74517    */
74518    addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
74519    addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
74520  }
74521
74522  /* Allocate registers for holding the rowid of the new row,
74523  ** the content of the new row, and the assemblied row record.
74524  */
74525  regRecord = ++pParse->nMem;
74526  regRowid = regIns = pParse->nMem+1;
74527  pParse->nMem += pTab->nCol + 1;
74528  if( IsVirtual(pTab) ){
74529    regRowid++;
74530    pParse->nMem++;
74531  }
74532  regData = regRowid+1;
74533
74534  /* Run the BEFORE and INSTEAD OF triggers, if there are any
74535  */
74536  endOfLoop = sqlite3VdbeMakeLabel(v);
74537  if( tmask & TRIGGER_BEFORE ){
74538    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
74539
74540    /* build the NEW.* reference row.  Note that if there is an INTEGER
74541    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
74542    ** translated into a unique ID for the row.  But on a BEFORE trigger,
74543    ** we do not know what the unique ID will be (because the insert has
74544    ** not happened yet) so we substitute a rowid of -1
74545    */
74546    if( keyColumn<0 ){
74547      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
74548    }else{
74549      int j1;
74550      if( useTempTable ){
74551        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
74552      }else{
74553        assert( pSelect==0 );  /* Otherwise useTempTable is true */
74554        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
74555      }
74556      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
74557      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
74558      sqlite3VdbeJumpHere(v, j1);
74559      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
74560    }
74561
74562    /* Cannot have triggers on a virtual table. If it were possible,
74563    ** this block would have to account for hidden column.
74564    */
74565    assert( !IsVirtual(pTab) );
74566
74567    /* Create the new column data
74568    */
74569    for(i=0; i<pTab->nCol; i++){
74570      if( pColumn==0 ){
74571        j = i;
74572      }else{
74573        for(j=0; j<pColumn->nId; j++){
74574          if( pColumn->a[j].idx==i ) break;
74575        }
74576      }
74577      if( pColumn && j>=pColumn->nId ){
74578        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
74579      }else if( useTempTable ){
74580        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
74581      }else{
74582        assert( pSelect==0 ); /* Otherwise useTempTable is true */
74583        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
74584      }
74585    }
74586
74587    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
74588    ** do not attempt any conversions before assembling the record.
74589    ** If this is a real table, attempt conversions as required by the
74590    ** table column affinities.
74591    */
74592    if( !isView ){
74593      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
74594      sqlite3TableAffinityStr(v, pTab);
74595    }
74596
74597    /* Fire BEFORE or INSTEAD OF triggers */
74598    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
74599        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
74600
74601    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
74602  }
74603
74604  /* Push the record number for the new entry onto the stack.  The
74605  ** record number is a randomly generate integer created by NewRowid
74606  ** except when the table has an INTEGER PRIMARY KEY column, in which
74607  ** case the record number is the same as that column.
74608  */
74609  if( !isView ){
74610    if( IsVirtual(pTab) ){
74611      /* The row that the VUpdate opcode will delete: none */
74612      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
74613    }
74614    if( keyColumn>=0 ){
74615      if( useTempTable ){
74616        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
74617      }else if( pSelect ){
74618        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
74619      }else{
74620        VdbeOp *pOp;
74621        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
74622        pOp = sqlite3VdbeGetOp(v, -1);
74623        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
74624          appendFlag = 1;
74625          pOp->opcode = OP_NewRowid;
74626          pOp->p1 = baseCur;
74627          pOp->p2 = regRowid;
74628          pOp->p3 = regAutoinc;
74629        }
74630      }
74631      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
74632      ** to generate a unique primary key value.
74633      */
74634      if( !appendFlag ){
74635        int j1;
74636        if( !IsVirtual(pTab) ){
74637          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
74638          sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
74639          sqlite3VdbeJumpHere(v, j1);
74640        }else{
74641          j1 = sqlite3VdbeCurrentAddr(v);
74642          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
74643        }
74644        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
74645      }
74646    }else if( IsVirtual(pTab) ){
74647      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
74648    }else{
74649      sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
74650      appendFlag = 1;
74651    }
74652    autoIncStep(pParse, regAutoinc, regRowid);
74653
74654    /* Push onto the stack, data for all columns of the new entry, beginning
74655    ** with the first column.
74656    */
74657    nHidden = 0;
74658    for(i=0; i<pTab->nCol; i++){
74659      int iRegStore = regRowid+1+i;
74660      if( i==pTab->iPKey ){
74661        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
74662        ** Whenever this column is read, the record number will be substituted
74663        ** in its place.  So will fill this column with a NULL to avoid
74664        ** taking up data space with information that will never be used. */
74665        sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
74666        continue;
74667      }
74668      if( pColumn==0 ){
74669        if( IsHiddenColumn(&pTab->aCol[i]) ){
74670          assert( IsVirtual(pTab) );
74671          j = -1;
74672          nHidden++;
74673        }else{
74674          j = i - nHidden;
74675        }
74676      }else{
74677        for(j=0; j<pColumn->nId; j++){
74678          if( pColumn->a[j].idx==i ) break;
74679        }
74680      }
74681      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
74682        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
74683      }else if( useTempTable ){
74684        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
74685      }else if( pSelect ){
74686        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
74687      }else{
74688        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
74689      }
74690    }
74691
74692    /* Generate code to check constraints and generate index keys and
74693    ** do the insertion.
74694    */
74695#ifndef SQLITE_OMIT_VIRTUALTABLE
74696    if( IsVirtual(pTab) ){
74697      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
74698      sqlite3VtabMakeWritable(pParse, pTab);
74699      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
74700      sqlite3MayAbort(pParse);
74701    }else
74702#endif
74703    {
74704      int isReplace;    /* Set to true if constraints may cause a replace */
74705      sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
74706          keyColumn>=0, 0, onError, endOfLoop, &isReplace
74707      );
74708      sqlite3FkCheck(pParse, pTab, 0, regIns);
74709      sqlite3CompleteInsertion(
74710          pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
74711      );
74712    }
74713  }
74714
74715  /* Update the count of rows that are inserted
74716  */
74717  if( (db->flags & SQLITE_CountRows)!=0 ){
74718    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
74719  }
74720
74721  if( pTrigger ){
74722    /* Code AFTER triggers */
74723    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
74724        pTab, regData-2-pTab->nCol, onError, endOfLoop);
74725  }
74726
74727  /* The bottom of the main insertion loop, if the data source
74728  ** is a SELECT statement.
74729  */
74730  sqlite3VdbeResolveLabel(v, endOfLoop);
74731  if( useTempTable ){
74732    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
74733    sqlite3VdbeJumpHere(v, addrInsTop);
74734    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
74735  }else if( pSelect ){
74736    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
74737    sqlite3VdbeJumpHere(v, addrInsTop);
74738  }
74739
74740  if( !IsVirtual(pTab) && !isView ){
74741    /* Close all tables opened */
74742    sqlite3VdbeAddOp1(v, OP_Close, baseCur);
74743    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
74744      sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
74745    }
74746  }
74747
74748insert_end:
74749  /* Update the sqlite_sequence table by storing the content of the
74750  ** maximum rowid counter values recorded while inserting into
74751  ** autoincrement tables.
74752  */
74753  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
74754    sqlite3AutoincrementEnd(pParse);
74755  }
74756
74757  /*
74758  ** Return the number of rows inserted. If this routine is
74759  ** generating code because of a call to sqlite3NestedParse(), do not
74760  ** invoke the callback function.
74761  */
74762  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
74763    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
74764    sqlite3VdbeSetNumCols(v, 1);
74765    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
74766  }
74767
74768insert_cleanup:
74769  sqlite3SrcListDelete(db, pTabList);
74770  sqlite3ExprListDelete(db, pList);
74771  sqlite3SelectDelete(db, pSelect);
74772  sqlite3IdListDelete(db, pColumn);
74773  sqlite3DbFree(db, aRegIdx);
74774}
74775
74776/* Make sure "isView" and other macros defined above are undefined. Otherwise
74777** thely may interfere with compilation of other functions in this file
74778** (or in another file, if this file becomes part of the amalgamation).  */
74779#ifdef isView
74780 #undef isView
74781#endif
74782#ifdef pTrigger
74783 #undef pTrigger
74784#endif
74785#ifdef tmask
74786 #undef tmask
74787#endif
74788
74789
74790/*
74791** Generate code to do constraint checks prior to an INSERT or an UPDATE.
74792**
74793** The input is a range of consecutive registers as follows:
74794**
74795**    1.  The rowid of the row after the update.
74796**
74797**    2.  The data in the first column of the entry after the update.
74798**
74799**    i.  Data from middle columns...
74800**
74801**    N.  The data in the last column of the entry after the update.
74802**
74803** The regRowid parameter is the index of the register containing (1).
74804**
74805** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
74806** the address of a register containing the rowid before the update takes
74807** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
74808** is false, indicating an INSERT statement, then a non-zero rowidChng
74809** indicates that the rowid was explicitly specified as part of the
74810** INSERT statement. If rowidChng is false, it means that  the rowid is
74811** computed automatically in an insert or that the rowid value is not
74812** modified by an update.
74813**
74814** The code generated by this routine store new index entries into
74815** registers identified by aRegIdx[].  No index entry is created for
74816** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
74817** the same as the order of indices on the linked list of indices
74818** attached to the table.
74819**
74820** This routine also generates code to check constraints.  NOT NULL,
74821** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
74822** then the appropriate action is performed.  There are five possible
74823** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
74824**
74825**  Constraint type  Action       What Happens
74826**  ---------------  ----------   ----------------------------------------
74827**  any              ROLLBACK     The current transaction is rolled back and
74828**                                sqlite3_exec() returns immediately with a
74829**                                return code of SQLITE_CONSTRAINT.
74830**
74831**  any              ABORT        Back out changes from the current command
74832**                                only (do not do a complete rollback) then
74833**                                cause sqlite3_exec() to return immediately
74834**                                with SQLITE_CONSTRAINT.
74835**
74836**  any              FAIL         Sqlite_exec() returns immediately with a
74837**                                return code of SQLITE_CONSTRAINT.  The
74838**                                transaction is not rolled back and any
74839**                                prior changes are retained.
74840**
74841**  any              IGNORE       The record number and data is popped from
74842**                                the stack and there is an immediate jump
74843**                                to label ignoreDest.
74844**
74845**  NOT NULL         REPLACE      The NULL value is replace by the default
74846**                                value for that column.  If the default value
74847**                                is NULL, the action is the same as ABORT.
74848**
74849**  UNIQUE           REPLACE      The other row that conflicts with the row
74850**                                being inserted is removed.
74851**
74852**  CHECK            REPLACE      Illegal.  The results in an exception.
74853**
74854** Which action to take is determined by the overrideError parameter.
74855** Or if overrideError==OE_Default, then the pParse->onError parameter
74856** is used.  Or if pParse->onError==OE_Default then the onError value
74857** for the constraint is used.
74858**
74859** The calling routine must open a read/write cursor for pTab with
74860** cursor number "baseCur".  All indices of pTab must also have open
74861** read/write cursors with cursor number baseCur+i for the i-th cursor.
74862** Except, if there is no possibility of a REPLACE action then
74863** cursors do not need to be open for indices where aRegIdx[i]==0.
74864*/
74865SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
74866  Parse *pParse,      /* The parser context */
74867  Table *pTab,        /* the table into which we are inserting */
74868  int baseCur,        /* Index of a read/write cursor pointing at pTab */
74869  int regRowid,       /* Index of the range of input registers */
74870  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
74871  int rowidChng,      /* True if the rowid might collide with existing entry */
74872  int isUpdate,       /* True for UPDATE, False for INSERT */
74873  int overrideError,  /* Override onError to this if not OE_Default */
74874  int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
74875  int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
74876){
74877  int i;              /* loop counter */
74878  Vdbe *v;            /* VDBE under constrution */
74879  int nCol;           /* Number of columns */
74880  int onError;        /* Conflict resolution strategy */
74881  int j1;             /* Addresss of jump instruction */
74882  int j2 = 0, j3;     /* Addresses of jump instructions */
74883  int regData;        /* Register containing first data column */
74884  int iCur;           /* Table cursor number */
74885  Index *pIdx;         /* Pointer to one of the indices */
74886  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
74887  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
74888
74889  v = sqlite3GetVdbe(pParse);
74890  assert( v!=0 );
74891  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
74892  nCol = pTab->nCol;
74893  regData = regRowid + 1;
74894
74895  /* Test all NOT NULL constraints.
74896  */
74897  for(i=0; i<nCol; i++){
74898    if( i==pTab->iPKey ){
74899      continue;
74900    }
74901    onError = pTab->aCol[i].notNull;
74902    if( onError==OE_None ) continue;
74903    if( overrideError!=OE_Default ){
74904      onError = overrideError;
74905    }else if( onError==OE_Default ){
74906      onError = OE_Abort;
74907    }
74908    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
74909      onError = OE_Abort;
74910    }
74911    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
74912        || onError==OE_Ignore || onError==OE_Replace );
74913    switch( onError ){
74914      case OE_Abort:
74915        sqlite3MayAbort(pParse);
74916      case OE_Rollback:
74917      case OE_Fail: {
74918        char *zMsg;
74919        j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
74920                                  SQLITE_CONSTRAINT, onError, regData+i);
74921        zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
74922                              pTab->zName, pTab->aCol[i].zName);
74923        sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
74924        break;
74925      }
74926      case OE_Ignore: {
74927        sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
74928        break;
74929      }
74930      default: {
74931        assert( onError==OE_Replace );
74932        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
74933        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
74934        sqlite3VdbeJumpHere(v, j1);
74935        break;
74936      }
74937    }
74938  }
74939
74940  /* Test all CHECK constraints
74941  */
74942#ifndef SQLITE_OMIT_CHECK
74943  if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
74944    int allOk = sqlite3VdbeMakeLabel(v);
74945    pParse->ckBase = regData;
74946    sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
74947    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
74948    if( onError==OE_Ignore ){
74949      sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
74950    }else{
74951      sqlite3HaltConstraint(pParse, onError, 0, 0);
74952    }
74953    sqlite3VdbeResolveLabel(v, allOk);
74954  }
74955#endif /* !defined(SQLITE_OMIT_CHECK) */
74956
74957  /* If we have an INTEGER PRIMARY KEY, make sure the primary key
74958  ** of the new record does not previously exist.  Except, if this
74959  ** is an UPDATE and the primary key is not changing, that is OK.
74960  */
74961  if( rowidChng ){
74962    onError = pTab->keyConf;
74963    if( overrideError!=OE_Default ){
74964      onError = overrideError;
74965    }else if( onError==OE_Default ){
74966      onError = OE_Abort;
74967    }
74968
74969    if( isUpdate ){
74970      j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
74971    }
74972    j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
74973    switch( onError ){
74974      default: {
74975        onError = OE_Abort;
74976        /* Fall thru into the next case */
74977      }
74978      case OE_Rollback:
74979      case OE_Abort:
74980      case OE_Fail: {
74981        sqlite3HaltConstraint(
74982          pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
74983        break;
74984      }
74985      case OE_Replace: {
74986        /* If there are DELETE triggers on this table and the
74987        ** recursive-triggers flag is set, call GenerateRowDelete() to
74988        ** remove the conflicting row from the the table. This will fire
74989        ** the triggers and remove both the table and index b-tree entries.
74990        **
74991        ** Otherwise, if there are no triggers or the recursive-triggers
74992        ** flag is not set, call GenerateRowIndexDelete(). This removes
74993        ** the index b-tree entries only. The table b-tree entry will be
74994        ** replaced by the new entry when it is inserted.  */
74995        Trigger *pTrigger = 0;
74996        if( pParse->db->flags&SQLITE_RecTriggers ){
74997          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
74998        }
74999        sqlite3MultiWrite(pParse);
75000        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
75001          sqlite3GenerateRowDelete(
75002              pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
75003          );
75004        }else{
75005          sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
75006        }
75007        seenReplace = 1;
75008        break;
75009      }
75010      case OE_Ignore: {
75011        assert( seenReplace==0 );
75012        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
75013        break;
75014      }
75015    }
75016    sqlite3VdbeJumpHere(v, j3);
75017    if( isUpdate ){
75018      sqlite3VdbeJumpHere(v, j2);
75019    }
75020  }
75021
75022  /* Test all UNIQUE constraints by creating entries for each UNIQUE
75023  ** index and making sure that duplicate entries do not already exist.
75024  ** Add the new records to the indices as we go.
75025  */
75026  for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
75027    int regIdx;
75028    int regR;
75029
75030    if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
75031
75032    /* Create a key for accessing the index entry */
75033    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
75034    for(i=0; i<pIdx->nColumn; i++){
75035      int idx = pIdx->aiColumn[i];
75036      if( idx==pTab->iPKey ){
75037        sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
75038      }else{
75039        sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
75040      }
75041    }
75042    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
75043    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
75044    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
75045    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
75046
75047    /* Find out what action to take in case there is an indexing conflict */
75048    onError = pIdx->onError;
75049    if( onError==OE_None ){
75050      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
75051      continue;  /* pIdx is not a UNIQUE index */
75052    }
75053    if( overrideError!=OE_Default ){
75054      onError = overrideError;
75055    }else if( onError==OE_Default ){
75056      onError = OE_Abort;
75057    }
75058    if( seenReplace ){
75059      if( onError==OE_Ignore ) onError = OE_Replace;
75060      else if( onError==OE_Fail ) onError = OE_Abort;
75061    }
75062
75063    /* Check to see if the new index entry will be unique */
75064    regR = sqlite3GetTempReg(pParse);
75065    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
75066    j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
75067                           regR, SQLITE_INT_TO_PTR(regIdx),
75068                           P4_INT32);
75069    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
75070
75071    /* Generate code that executes if the new index entry is not unique */
75072    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
75073        || onError==OE_Ignore || onError==OE_Replace );
75074    switch( onError ){
75075      case OE_Rollback:
75076      case OE_Abort:
75077      case OE_Fail: {
75078        int j;
75079        StrAccum errMsg;
75080        const char *zSep;
75081        char *zErr;
75082
75083        sqlite3StrAccumInit(&errMsg, 0, 0, 200);
75084        errMsg.db = pParse->db;
75085        zSep = pIdx->nColumn>1 ? "columns " : "column ";
75086        for(j=0; j<pIdx->nColumn; j++){
75087          char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
75088          sqlite3StrAccumAppend(&errMsg, zSep, -1);
75089          zSep = ", ";
75090          sqlite3StrAccumAppend(&errMsg, zCol, -1);
75091        }
75092        sqlite3StrAccumAppend(&errMsg,
75093            pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
75094        zErr = sqlite3StrAccumFinish(&errMsg);
75095        sqlite3HaltConstraint(pParse, onError, zErr, 0);
75096        sqlite3DbFree(errMsg.db, zErr);
75097        break;
75098      }
75099      case OE_Ignore: {
75100        assert( seenReplace==0 );
75101        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
75102        break;
75103      }
75104      default: {
75105        Trigger *pTrigger = 0;
75106        assert( onError==OE_Replace );
75107        sqlite3MultiWrite(pParse);
75108        if( pParse->db->flags&SQLITE_RecTriggers ){
75109          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
75110        }
75111        sqlite3GenerateRowDelete(
75112            pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
75113        );
75114        seenReplace = 1;
75115        break;
75116      }
75117    }
75118    sqlite3VdbeJumpHere(v, j3);
75119    sqlite3ReleaseTempReg(pParse, regR);
75120  }
75121
75122  if( pbMayReplace ){
75123    *pbMayReplace = seenReplace;
75124  }
75125}
75126
75127/*
75128** This routine generates code to finish the INSERT or UPDATE operation
75129** that was started by a prior call to sqlite3GenerateConstraintChecks.
75130** A consecutive range of registers starting at regRowid contains the
75131** rowid and the content to be inserted.
75132**
75133** The arguments to this routine should be the same as the first six
75134** arguments to sqlite3GenerateConstraintChecks.
75135*/
75136SQLITE_PRIVATE void sqlite3CompleteInsertion(
75137  Parse *pParse,      /* The parser context */
75138  Table *pTab,        /* the table into which we are inserting */
75139  int baseCur,        /* Index of a read/write cursor pointing at pTab */
75140  int regRowid,       /* Range of content */
75141  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
75142  int isUpdate,       /* True for UPDATE, False for INSERT */
75143  int appendBias,     /* True if this is likely to be an append */
75144  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
75145){
75146  int i;
75147  Vdbe *v;
75148  int nIdx;
75149  Index *pIdx;
75150  u8 pik_flags;
75151  int regData;
75152  int regRec;
75153
75154  v = sqlite3GetVdbe(pParse);
75155  assert( v!=0 );
75156  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
75157  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
75158  for(i=nIdx-1; i>=0; i--){
75159    if( aRegIdx[i]==0 ) continue;
75160    sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
75161    if( useSeekResult ){
75162      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
75163    }
75164  }
75165  regData = regRowid + 1;
75166  regRec = sqlite3GetTempReg(pParse);
75167  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
75168  sqlite3TableAffinityStr(v, pTab);
75169  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
75170  if( pParse->nested ){
75171    pik_flags = 0;
75172  }else{
75173    pik_flags = OPFLAG_NCHANGE;
75174    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
75175  }
75176  if( appendBias ){
75177    pik_flags |= OPFLAG_APPEND;
75178  }
75179  if( useSeekResult ){
75180    pik_flags |= OPFLAG_USESEEKRESULT;
75181  }
75182  sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
75183  if( !pParse->nested ){
75184    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
75185  }
75186  sqlite3VdbeChangeP5(v, pik_flags);
75187}
75188
75189/*
75190** Generate code that will open cursors for a table and for all
75191** indices of that table.  The "baseCur" parameter is the cursor number used
75192** for the table.  Indices are opened on subsequent cursors.
75193**
75194** Return the number of indices on the table.
75195*/
75196SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
75197  Parse *pParse,   /* Parsing context */
75198  Table *pTab,     /* Table to be opened */
75199  int baseCur,     /* Cursor number assigned to the table */
75200  int op           /* OP_OpenRead or OP_OpenWrite */
75201){
75202  int i;
75203  int iDb;
75204  Index *pIdx;
75205  Vdbe *v;
75206
75207  if( IsVirtual(pTab) ) return 0;
75208  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
75209  v = sqlite3GetVdbe(pParse);
75210  assert( v!=0 );
75211  sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
75212  for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
75213    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
75214    assert( pIdx->pSchema==pTab->pSchema );
75215    sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
75216                      (char*)pKey, P4_KEYINFO_HANDOFF);
75217    VdbeComment((v, "%s", pIdx->zName));
75218  }
75219  if( pParse->nTab<baseCur+i ){
75220    pParse->nTab = baseCur+i;
75221  }
75222  return i-1;
75223}
75224
75225
75226#ifdef SQLITE_TEST
75227/*
75228** The following global variable is incremented whenever the
75229** transfer optimization is used.  This is used for testing
75230** purposes only - to make sure the transfer optimization really
75231** is happening when it is suppose to.
75232*/
75233SQLITE_API int sqlite3_xferopt_count;
75234#endif /* SQLITE_TEST */
75235
75236
75237#ifndef SQLITE_OMIT_XFER_OPT
75238/*
75239** Check to collation names to see if they are compatible.
75240*/
75241static int xferCompatibleCollation(const char *z1, const char *z2){
75242  if( z1==0 ){
75243    return z2==0;
75244  }
75245  if( z2==0 ){
75246    return 0;
75247  }
75248  return sqlite3StrICmp(z1, z2)==0;
75249}
75250
75251
75252/*
75253** Check to see if index pSrc is compatible as a source of data
75254** for index pDest in an insert transfer optimization.  The rules
75255** for a compatible index:
75256**
75257**    *   The index is over the same set of columns
75258**    *   The same DESC and ASC markings occurs on all columns
75259**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
75260**    *   The same collating sequence on each column
75261*/
75262static int xferCompatibleIndex(Index *pDest, Index *pSrc){
75263  int i;
75264  assert( pDest && pSrc );
75265  assert( pDest->pTable!=pSrc->pTable );
75266  if( pDest->nColumn!=pSrc->nColumn ){
75267    return 0;   /* Different number of columns */
75268  }
75269  if( pDest->onError!=pSrc->onError ){
75270    return 0;   /* Different conflict resolution strategies */
75271  }
75272  for(i=0; i<pSrc->nColumn; i++){
75273    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
75274      return 0;   /* Different columns indexed */
75275    }
75276    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
75277      return 0;   /* Different sort orders */
75278    }
75279    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
75280      return 0;   /* Different collating sequences */
75281    }
75282  }
75283
75284  /* If no test above fails then the indices must be compatible */
75285  return 1;
75286}
75287
75288/*
75289** Attempt the transfer optimization on INSERTs of the form
75290**
75291**     INSERT INTO tab1 SELECT * FROM tab2;
75292**
75293** This optimization is only attempted if
75294**
75295**    (1)  tab1 and tab2 have identical schemas including all the
75296**         same indices and constraints
75297**
75298**    (2)  tab1 and tab2 are different tables
75299**
75300**    (3)  There must be no triggers on tab1
75301**
75302**    (4)  The result set of the SELECT statement is "*"
75303**
75304**    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
75305**         or LIMIT clause.
75306**
75307**    (6)  The SELECT statement is a simple (not a compound) select that
75308**         contains only tab2 in its FROM clause
75309**
75310** This method for implementing the INSERT transfers raw records from
75311** tab2 over to tab1.  The columns are not decoded.  Raw records from
75312** the indices of tab2 are transfered to tab1 as well.  In so doing,
75313** the resulting tab1 has much less fragmentation.
75314**
75315** This routine returns TRUE if the optimization is attempted.  If any
75316** of the conditions above fail so that the optimization should not
75317** be attempted, then this routine returns FALSE.
75318*/
75319static int xferOptimization(
75320  Parse *pParse,        /* Parser context */
75321  Table *pDest,         /* The table we are inserting into */
75322  Select *pSelect,      /* A SELECT statement to use as the data source */
75323  int onError,          /* How to handle constraint errors */
75324  int iDbDest           /* The database of pDest */
75325){
75326  ExprList *pEList;                /* The result set of the SELECT */
75327  Table *pSrc;                     /* The table in the FROM clause of SELECT */
75328  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
75329  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
75330  int i;                           /* Loop counter */
75331  int iDbSrc;                      /* The database of pSrc */
75332  int iSrc, iDest;                 /* Cursors from source and destination */
75333  int addr1, addr2;                /* Loop addresses */
75334  int emptyDestTest;               /* Address of test for empty pDest */
75335  int emptySrcTest;                /* Address of test for empty pSrc */
75336  Vdbe *v;                         /* The VDBE we are building */
75337  KeyInfo *pKey;                   /* Key information for an index */
75338  int regAutoinc;                  /* Memory register used by AUTOINC */
75339  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
75340  int regData, regRowid;           /* Registers holding data and rowid */
75341
75342  if( pSelect==0 ){
75343    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
75344  }
75345  if( sqlite3TriggerList(pParse, pDest) ){
75346    return 0;   /* tab1 must not have triggers */
75347  }
75348#ifndef SQLITE_OMIT_VIRTUALTABLE
75349  if( pDest->tabFlags & TF_Virtual ){
75350    return 0;   /* tab1 must not be a virtual table */
75351  }
75352#endif
75353  if( onError==OE_Default ){
75354    onError = OE_Abort;
75355  }
75356  if( onError!=OE_Abort && onError!=OE_Rollback ){
75357    return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
75358  }
75359  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
75360  if( pSelect->pSrc->nSrc!=1 ){
75361    return 0;   /* FROM clause must have exactly one term */
75362  }
75363  if( pSelect->pSrc->a[0].pSelect ){
75364    return 0;   /* FROM clause cannot contain a subquery */
75365  }
75366  if( pSelect->pWhere ){
75367    return 0;   /* SELECT may not have a WHERE clause */
75368  }
75369  if( pSelect->pOrderBy ){
75370    return 0;   /* SELECT may not have an ORDER BY clause */
75371  }
75372  /* Do not need to test for a HAVING clause.  If HAVING is present but
75373  ** there is no ORDER BY, we will get an error. */
75374  if( pSelect->pGroupBy ){
75375    return 0;   /* SELECT may not have a GROUP BY clause */
75376  }
75377  if( pSelect->pLimit ){
75378    return 0;   /* SELECT may not have a LIMIT clause */
75379  }
75380  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
75381  if( pSelect->pPrior ){
75382    return 0;   /* SELECT may not be a compound query */
75383  }
75384  if( pSelect->selFlags & SF_Distinct ){
75385    return 0;   /* SELECT may not be DISTINCT */
75386  }
75387  pEList = pSelect->pEList;
75388  assert( pEList!=0 );
75389  if( pEList->nExpr!=1 ){
75390    return 0;   /* The result set must have exactly one column */
75391  }
75392  assert( pEList->a[0].pExpr );
75393  if( pEList->a[0].pExpr->op!=TK_ALL ){
75394    return 0;   /* The result set must be the special operator "*" */
75395  }
75396
75397  /* At this point we have established that the statement is of the
75398  ** correct syntactic form to participate in this optimization.  Now
75399  ** we have to check the semantics.
75400  */
75401  pItem = pSelect->pSrc->a;
75402  pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
75403  if( pSrc==0 ){
75404    return 0;   /* FROM clause does not contain a real table */
75405  }
75406  if( pSrc==pDest ){
75407    return 0;   /* tab1 and tab2 may not be the same table */
75408  }
75409#ifndef SQLITE_OMIT_VIRTUALTABLE
75410  if( pSrc->tabFlags & TF_Virtual ){
75411    return 0;   /* tab2 must not be a virtual table */
75412  }
75413#endif
75414  if( pSrc->pSelect ){
75415    return 0;   /* tab2 may not be a view */
75416  }
75417  if( pDest->nCol!=pSrc->nCol ){
75418    return 0;   /* Number of columns must be the same in tab1 and tab2 */
75419  }
75420  if( pDest->iPKey!=pSrc->iPKey ){
75421    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
75422  }
75423  for(i=0; i<pDest->nCol; i++){
75424    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
75425      return 0;    /* Affinity must be the same on all columns */
75426    }
75427    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
75428      return 0;    /* Collating sequence must be the same on all columns */
75429    }
75430    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
75431      return 0;    /* tab2 must be NOT NULL if tab1 is */
75432    }
75433  }
75434  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
75435    if( pDestIdx->onError!=OE_None ){
75436      destHasUniqueIdx = 1;
75437    }
75438    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
75439      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
75440    }
75441    if( pSrcIdx==0 ){
75442      return 0;    /* pDestIdx has no corresponding index in pSrc */
75443    }
75444  }
75445#ifndef SQLITE_OMIT_CHECK
75446  if( pDest->pCheck && !sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
75447    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
75448  }
75449#endif
75450
75451  /* If we get this far, it means either:
75452  **
75453  **    *   We can always do the transfer if the table contains an
75454  **        an integer primary key
75455  **
75456  **    *   We can conditionally do the transfer if the destination
75457  **        table is empty.
75458  */
75459#ifdef SQLITE_TEST
75460  sqlite3_xferopt_count++;
75461#endif
75462  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
75463  v = sqlite3GetVdbe(pParse);
75464  sqlite3CodeVerifySchema(pParse, iDbSrc);
75465  iSrc = pParse->nTab++;
75466  iDest = pParse->nTab++;
75467  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
75468  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
75469  if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
75470    /* If tables do not have an INTEGER PRIMARY KEY and there
75471    ** are indices to be copied and the destination is not empty,
75472    ** we have to disallow the transfer optimization because the
75473    ** the rowids might change which will mess up indexing.
75474    **
75475    ** Or if the destination has a UNIQUE index and is not empty,
75476    ** we also disallow the transfer optimization because we cannot
75477    ** insure that all entries in the union of DEST and SRC will be
75478    ** unique.
75479    */
75480    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
75481    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
75482    sqlite3VdbeJumpHere(v, addr1);
75483  }else{
75484    emptyDestTest = 0;
75485  }
75486  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
75487  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
75488  regData = sqlite3GetTempReg(pParse);
75489  regRowid = sqlite3GetTempReg(pParse);
75490  if( pDest->iPKey>=0 ){
75491    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
75492    addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
75493    sqlite3HaltConstraint(
75494        pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
75495    sqlite3VdbeJumpHere(v, addr2);
75496    autoIncStep(pParse, regAutoinc, regRowid);
75497  }else if( pDest->pIndex==0 ){
75498    addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
75499  }else{
75500    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
75501    assert( (pDest->tabFlags & TF_Autoincrement)==0 );
75502  }
75503  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
75504  sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
75505  sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
75506  sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
75507  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
75508  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
75509    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
75510      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
75511    }
75512    assert( pSrcIdx );
75513    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
75514    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75515    pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
75516    sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
75517                      (char*)pKey, P4_KEYINFO_HANDOFF);
75518    VdbeComment((v, "%s", pSrcIdx->zName));
75519    pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
75520    sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
75521                      (char*)pKey, P4_KEYINFO_HANDOFF);
75522    VdbeComment((v, "%s", pDestIdx->zName));
75523    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
75524    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
75525    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
75526    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
75527    sqlite3VdbeJumpHere(v, addr1);
75528  }
75529  sqlite3VdbeJumpHere(v, emptySrcTest);
75530  sqlite3ReleaseTempReg(pParse, regRowid);
75531  sqlite3ReleaseTempReg(pParse, regData);
75532  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
75533  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75534  if( emptyDestTest ){
75535    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
75536    sqlite3VdbeJumpHere(v, emptyDestTest);
75537    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
75538    return 0;
75539  }else{
75540    return 1;
75541  }
75542}
75543#endif /* SQLITE_OMIT_XFER_OPT */
75544
75545/************** End of insert.c **********************************************/
75546/************** Begin file legacy.c ******************************************/
75547/*
75548** 2001 September 15
75549**
75550** The author disclaims copyright to this source code.  In place of
75551** a legal notice, here is a blessing:
75552**
75553**    May you do good and not evil.
75554**    May you find forgiveness for yourself and forgive others.
75555**    May you share freely, never taking more than you give.
75556**
75557*************************************************************************
75558** Main file for the SQLite library.  The routines in this file
75559** implement the programmer interface to the library.  Routines in
75560** other files are for internal use by SQLite and should not be
75561** accessed by users of the library.
75562*/
75563
75564
75565/*
75566** Execute SQL code.  Return one of the SQLITE_ success/failure
75567** codes.  Also write an error message into memory obtained from
75568** malloc() and make *pzErrMsg point to that message.
75569**
75570** If the SQL is a query, then for each row in the query result
75571** the xCallback() function is called.  pArg becomes the first
75572** argument to xCallback().  If xCallback=NULL then no callback
75573** is invoked, even for queries.
75574*/
75575SQLITE_API int sqlite3_exec(
75576  sqlite3 *db,                /* The database on which the SQL executes */
75577  const char *zSql,           /* The SQL to be executed */
75578  sqlite3_callback xCallback, /* Invoke this callback routine */
75579  void *pArg,                 /* First argument to xCallback() */
75580  char **pzErrMsg             /* Write error messages here */
75581){
75582  int rc = SQLITE_OK;         /* Return code */
75583  const char *zLeftover;      /* Tail of unprocessed SQL */
75584  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
75585  char **azCols = 0;          /* Names of result columns */
75586  int nRetry = 0;             /* Number of retry attempts */
75587  int callbackIsInit;         /* True if callback data is initialized */
75588
75589  if( zSql==0 ) zSql = "";
75590
75591  sqlite3_mutex_enter(db->mutex);
75592  sqlite3Error(db, SQLITE_OK, 0);
75593  while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
75594    int nCol;
75595    char **azVals = 0;
75596
75597    pStmt = 0;
75598    rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
75599    assert( rc==SQLITE_OK || pStmt==0 );
75600    if( rc!=SQLITE_OK ){
75601      continue;
75602    }
75603    if( !pStmt ){
75604      /* this happens for a comment or white-space */
75605      zSql = zLeftover;
75606      continue;
75607    }
75608
75609    callbackIsInit = 0;
75610    nCol = sqlite3_column_count(pStmt);
75611
75612    while( 1 ){
75613      int i;
75614      rc = sqlite3_step(pStmt);
75615
75616      /* Invoke the callback function if required */
75617      if( xCallback && (SQLITE_ROW==rc ||
75618          (SQLITE_DONE==rc && !callbackIsInit
75619                           && db->flags&SQLITE_NullCallback)) ){
75620        if( !callbackIsInit ){
75621          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
75622          if( azCols==0 ){
75623            goto exec_out;
75624          }
75625          for(i=0; i<nCol; i++){
75626            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
75627            /* sqlite3VdbeSetColName() installs column names as UTF8
75628            ** strings so there is no way for sqlite3_column_name() to fail. */
75629            assert( azCols[i]!=0 );
75630          }
75631          callbackIsInit = 1;
75632        }
75633        if( rc==SQLITE_ROW ){
75634          azVals = &azCols[nCol];
75635          for(i=0; i<nCol; i++){
75636            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
75637            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
75638              db->mallocFailed = 1;
75639              goto exec_out;
75640            }
75641          }
75642        }
75643        if( xCallback(pArg, nCol, azVals, azCols) ){
75644          rc = SQLITE_ABORT;
75645          sqlite3VdbeFinalize((Vdbe *)pStmt);
75646          pStmt = 0;
75647          sqlite3Error(db, SQLITE_ABORT, 0);
75648          goto exec_out;
75649        }
75650      }
75651
75652      if( rc!=SQLITE_ROW ){
75653        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
75654        pStmt = 0;
75655        if( rc!=SQLITE_SCHEMA ){
75656          nRetry = 0;
75657          zSql = zLeftover;
75658          while( sqlite3Isspace(zSql[0]) ) zSql++;
75659        }
75660        break;
75661      }
75662    }
75663
75664    sqlite3DbFree(db, azCols);
75665    azCols = 0;
75666  }
75667
75668exec_out:
75669  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
75670  sqlite3DbFree(db, azCols);
75671
75672  rc = sqlite3ApiExit(db, rc);
75673  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
75674    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
75675    *pzErrMsg = sqlite3Malloc(nErrMsg);
75676    if( *pzErrMsg ){
75677      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
75678    }else{
75679      rc = SQLITE_NOMEM;
75680      sqlite3Error(db, SQLITE_NOMEM, 0);
75681    }
75682  }else if( pzErrMsg ){
75683    *pzErrMsg = 0;
75684  }
75685
75686  assert( (rc&db->errMask)==rc );
75687  sqlite3_mutex_leave(db->mutex);
75688  return rc;
75689}
75690
75691/************** End of legacy.c **********************************************/
75692/************** Begin file loadext.c *****************************************/
75693/*
75694** 2006 June 7
75695**
75696** The author disclaims copyright to this source code.  In place of
75697** a legal notice, here is a blessing:
75698**
75699**    May you do good and not evil.
75700**    May you find forgiveness for yourself and forgive others.
75701**    May you share freely, never taking more than you give.
75702**
75703*************************************************************************
75704** This file contains code used to dynamically load extensions into
75705** the SQLite library.
75706*/
75707
75708#ifndef SQLITE_CORE
75709  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
75710#endif
75711/************** Include sqlite3ext.h in the middle of loadext.c **************/
75712/************** Begin file sqlite3ext.h **************************************/
75713/*
75714** 2006 June 7
75715**
75716** The author disclaims copyright to this source code.  In place of
75717** a legal notice, here is a blessing:
75718**
75719**    May you do good and not evil.
75720**    May you find forgiveness for yourself and forgive others.
75721**    May you share freely, never taking more than you give.
75722**
75723*************************************************************************
75724** This header file defines the SQLite interface for use by
75725** shared libraries that want to be imported as extensions into
75726** an SQLite instance.  Shared libraries that intend to be loaded
75727** as extensions by SQLite should #include this file instead of
75728** sqlite3.h.
75729*/
75730#ifndef _SQLITE3EXT_H_
75731#define _SQLITE3EXT_H_
75732
75733typedef struct sqlite3_api_routines sqlite3_api_routines;
75734
75735/*
75736** The following structure holds pointers to all of the SQLite API
75737** routines.
75738**
75739** WARNING:  In order to maintain backwards compatibility, add new
75740** interfaces to the end of this structure only.  If you insert new
75741** interfaces in the middle of this structure, then older different
75742** versions of SQLite will not be able to load each others' shared
75743** libraries!
75744*/
75745struct sqlite3_api_routines {
75746  void * (*aggregate_context)(sqlite3_context*,int nBytes);
75747  int  (*aggregate_count)(sqlite3_context*);
75748  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
75749  int  (*bind_double)(sqlite3_stmt*,int,double);
75750  int  (*bind_int)(sqlite3_stmt*,int,int);
75751  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
75752  int  (*bind_null)(sqlite3_stmt*,int);
75753  int  (*bind_parameter_count)(sqlite3_stmt*);
75754  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
75755  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
75756  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
75757  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
75758  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
75759  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
75760  int  (*busy_timeout)(sqlite3*,int ms);
75761  int  (*changes)(sqlite3*);
75762  int  (*close)(sqlite3*);
75763  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
75764  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
75765  const void * (*column_blob)(sqlite3_stmt*,int iCol);
75766  int  (*column_bytes)(sqlite3_stmt*,int iCol);
75767  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
75768  int  (*column_count)(sqlite3_stmt*pStmt);
75769  const char * (*column_database_name)(sqlite3_stmt*,int);
75770  const void * (*column_database_name16)(sqlite3_stmt*,int);
75771  const char * (*column_decltype)(sqlite3_stmt*,int i);
75772  const void * (*column_decltype16)(sqlite3_stmt*,int);
75773  double  (*column_double)(sqlite3_stmt*,int iCol);
75774  int  (*column_int)(sqlite3_stmt*,int iCol);
75775  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
75776  const char * (*column_name)(sqlite3_stmt*,int);
75777  const void * (*column_name16)(sqlite3_stmt*,int);
75778  const char * (*column_origin_name)(sqlite3_stmt*,int);
75779  const void * (*column_origin_name16)(sqlite3_stmt*,int);
75780  const char * (*column_table_name)(sqlite3_stmt*,int);
75781  const void * (*column_table_name16)(sqlite3_stmt*,int);
75782  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
75783  const void * (*column_text16)(sqlite3_stmt*,int iCol);
75784  int  (*column_type)(sqlite3_stmt*,int iCol);
75785  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
75786  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
75787  int  (*complete)(const char*sql);
75788  int  (*complete16)(const void*sql);
75789  int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
75790  int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
75791  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*));
75792  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*));
75793  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
75794  int  (*data_count)(sqlite3_stmt*pStmt);
75795  sqlite3 * (*db_handle)(sqlite3_stmt*);
75796  int (*declare_vtab)(sqlite3*,const char*);
75797  int  (*enable_shared_cache)(int);
75798  int  (*errcode)(sqlite3*db);
75799  const char * (*errmsg)(sqlite3*);
75800  const void * (*errmsg16)(sqlite3*);
75801  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
75802  int  (*expired)(sqlite3_stmt*);
75803  int  (*finalize)(sqlite3_stmt*pStmt);
75804  void  (*free)(void*);
75805  void  (*free_table)(char**result);
75806  int  (*get_autocommit)(sqlite3*);
75807  void * (*get_auxdata)(sqlite3_context*,int);
75808  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
75809  int  (*global_recover)(void);
75810  void  (*interruptx)(sqlite3*);
75811  sqlite_int64  (*last_insert_rowid)(sqlite3*);
75812  const char * (*libversion)(void);
75813  int  (*libversion_number)(void);
75814  void *(*malloc)(int);
75815  char * (*mprintf)(const char*,...);
75816  int  (*open)(const char*,sqlite3**);
75817  int  (*open16)(const void*,sqlite3**);
75818  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
75819  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
75820  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
75821  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
75822  void *(*realloc)(void*,int);
75823  int  (*reset)(sqlite3_stmt*pStmt);
75824  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
75825  void  (*result_double)(sqlite3_context*,double);
75826  void  (*result_error)(sqlite3_context*,const char*,int);
75827  void  (*result_error16)(sqlite3_context*,const void*,int);
75828  void  (*result_int)(sqlite3_context*,int);
75829  void  (*result_int64)(sqlite3_context*,sqlite_int64);
75830  void  (*result_null)(sqlite3_context*);
75831  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
75832  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
75833  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
75834  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
75835  void  (*result_value)(sqlite3_context*,sqlite3_value*);
75836  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
75837  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
75838  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
75839  char * (*snprintf)(int,char*,const char*,...);
75840  int  (*step)(sqlite3_stmt*);
75841  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
75842  void  (*thread_cleanup)(void);
75843  int  (*total_changes)(sqlite3*);
75844  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
75845  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
75846  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
75847  void * (*user_data)(sqlite3_context*);
75848  const void * (*value_blob)(sqlite3_value*);
75849  int  (*value_bytes)(sqlite3_value*);
75850  int  (*value_bytes16)(sqlite3_value*);
75851  double  (*value_double)(sqlite3_value*);
75852  int  (*value_int)(sqlite3_value*);
75853  sqlite_int64  (*value_int64)(sqlite3_value*);
75854  int  (*value_numeric_type)(sqlite3_value*);
75855  const unsigned char * (*value_text)(sqlite3_value*);
75856  const void * (*value_text16)(sqlite3_value*);
75857  const void * (*value_text16be)(sqlite3_value*);
75858  const void * (*value_text16le)(sqlite3_value*);
75859  int  (*value_type)(sqlite3_value*);
75860  char *(*vmprintf)(const char*,va_list);
75861  /* Added ??? */
75862  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
75863  /* Added by 3.3.13 */
75864  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
75865  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
75866  int (*clear_bindings)(sqlite3_stmt*);
75867  /* Added by 3.4.1 */
75868  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
75869  /* Added by 3.5.0 */
75870  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
75871  int (*blob_bytes)(sqlite3_blob*);
75872  int (*blob_close)(sqlite3_blob*);
75873  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
75874  int (*blob_read)(sqlite3_blob*,void*,int,int);
75875  int (*blob_write)(sqlite3_blob*,const void*,int,int);
75876  int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
75877  int (*file_control)(sqlite3*,const char*,int,void*);
75878  sqlite3_int64 (*memory_highwater)(int);
75879  sqlite3_int64 (*memory_used)(void);
75880  sqlite3_mutex *(*mutex_alloc)(int);
75881  void (*mutex_enter)(sqlite3_mutex*);
75882  void (*mutex_free)(sqlite3_mutex*);
75883  void (*mutex_leave)(sqlite3_mutex*);
75884  int (*mutex_try)(sqlite3_mutex*);
75885  int (*open_v2)(const char*,sqlite3**,int,const char*);
75886  int (*release_memory)(int);
75887  void (*result_error_nomem)(sqlite3_context*);
75888  void (*result_error_toobig)(sqlite3_context*);
75889  int (*sleep)(int);
75890  void (*soft_heap_limit)(int);
75891  sqlite3_vfs *(*vfs_find)(const char*);
75892  int (*vfs_register)(sqlite3_vfs*,int);
75893  int (*vfs_unregister)(sqlite3_vfs*);
75894  int (*xthreadsafe)(void);
75895  void (*result_zeroblob)(sqlite3_context*,int);
75896  void (*result_error_code)(sqlite3_context*,int);
75897  int (*test_control)(int, ...);
75898  void (*randomness)(int,void*);
75899  sqlite3 *(*context_db_handle)(sqlite3_context*);
75900  int (*extended_result_codes)(sqlite3*,int);
75901  int (*limit)(sqlite3*,int,int);
75902  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
75903  const char *(*sql)(sqlite3_stmt*);
75904  int (*status)(int,int*,int*,int);
75905};
75906
75907/*
75908** The following macros redefine the API routines so that they are
75909** redirected throught the global sqlite3_api structure.
75910**
75911** This header file is also used by the loadext.c source file
75912** (part of the main SQLite library - not an extension) so that
75913** it can get access to the sqlite3_api_routines structure
75914** definition.  But the main library does not want to redefine
75915** the API.  So the redefinition macros are only valid if the
75916** SQLITE_CORE macros is undefined.
75917*/
75918#ifndef SQLITE_CORE
75919#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
75920#ifndef SQLITE_OMIT_DEPRECATED
75921#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
75922#endif
75923#define sqlite3_bind_blob              sqlite3_api->bind_blob
75924#define sqlite3_bind_double            sqlite3_api->bind_double
75925#define sqlite3_bind_int               sqlite3_api->bind_int
75926#define sqlite3_bind_int64             sqlite3_api->bind_int64
75927#define sqlite3_bind_null              sqlite3_api->bind_null
75928#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
75929#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
75930#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
75931#define sqlite3_bind_text              sqlite3_api->bind_text
75932#define sqlite3_bind_text16            sqlite3_api->bind_text16
75933#define sqlite3_bind_value             sqlite3_api->bind_value
75934#define sqlite3_busy_handler           sqlite3_api->busy_handler
75935#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
75936#define sqlite3_changes                sqlite3_api->changes
75937#define sqlite3_close                  sqlite3_api->close
75938#define sqlite3_collation_needed       sqlite3_api->collation_needed
75939#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
75940#define sqlite3_column_blob            sqlite3_api->column_blob
75941#define sqlite3_column_bytes           sqlite3_api->column_bytes
75942#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
75943#define sqlite3_column_count           sqlite3_api->column_count
75944#define sqlite3_column_database_name   sqlite3_api->column_database_name
75945#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
75946#define sqlite3_column_decltype        sqlite3_api->column_decltype
75947#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
75948#define sqlite3_column_double          sqlite3_api->column_double
75949#define sqlite3_column_int             sqlite3_api->column_int
75950#define sqlite3_column_int64           sqlite3_api->column_int64
75951#define sqlite3_column_name            sqlite3_api->column_name
75952#define sqlite3_column_name16          sqlite3_api->column_name16
75953#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
75954#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
75955#define sqlite3_column_table_name      sqlite3_api->column_table_name
75956#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
75957#define sqlite3_column_text            sqlite3_api->column_text
75958#define sqlite3_column_text16          sqlite3_api->column_text16
75959#define sqlite3_column_type            sqlite3_api->column_type
75960#define sqlite3_column_value           sqlite3_api->column_value
75961#define sqlite3_commit_hook            sqlite3_api->commit_hook
75962#define sqlite3_complete               sqlite3_api->complete
75963#define sqlite3_complete16             sqlite3_api->complete16
75964#define sqlite3_create_collation       sqlite3_api->create_collation
75965#define sqlite3_create_collation16     sqlite3_api->create_collation16
75966#define sqlite3_create_function        sqlite3_api->create_function
75967#define sqlite3_create_function16      sqlite3_api->create_function16
75968#define sqlite3_create_module          sqlite3_api->create_module
75969#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
75970#define sqlite3_data_count             sqlite3_api->data_count
75971#define sqlite3_db_handle              sqlite3_api->db_handle
75972#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
75973#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
75974#define sqlite3_errcode                sqlite3_api->errcode
75975#define sqlite3_errmsg                 sqlite3_api->errmsg
75976#define sqlite3_errmsg16               sqlite3_api->errmsg16
75977#define sqlite3_exec                   sqlite3_api->exec
75978#ifndef SQLITE_OMIT_DEPRECATED
75979#define sqlite3_expired                sqlite3_api->expired
75980#endif
75981#define sqlite3_finalize               sqlite3_api->finalize
75982#define sqlite3_free                   sqlite3_api->free
75983#define sqlite3_free_table             sqlite3_api->free_table
75984#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
75985#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
75986#define sqlite3_get_table              sqlite3_api->get_table
75987#ifndef SQLITE_OMIT_DEPRECATED
75988#define sqlite3_global_recover         sqlite3_api->global_recover
75989#endif
75990#define sqlite3_interrupt              sqlite3_api->interruptx
75991#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
75992#define sqlite3_libversion             sqlite3_api->libversion
75993#define sqlite3_libversion_number      sqlite3_api->libversion_number
75994#define sqlite3_malloc                 sqlite3_api->malloc
75995#define sqlite3_mprintf                sqlite3_api->mprintf
75996#define sqlite3_open                   sqlite3_api->open
75997#define sqlite3_open16                 sqlite3_api->open16
75998#define sqlite3_prepare                sqlite3_api->prepare
75999#define sqlite3_prepare16              sqlite3_api->prepare16
76000#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
76001#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
76002#define sqlite3_profile                sqlite3_api->profile
76003#define sqlite3_progress_handler       sqlite3_api->progress_handler
76004#define sqlite3_realloc                sqlite3_api->realloc
76005#define sqlite3_reset                  sqlite3_api->reset
76006#define sqlite3_result_blob            sqlite3_api->result_blob
76007#define sqlite3_result_double          sqlite3_api->result_double
76008#define sqlite3_result_error           sqlite3_api->result_error
76009#define sqlite3_result_error16         sqlite3_api->result_error16
76010#define sqlite3_result_int             sqlite3_api->result_int
76011#define sqlite3_result_int64           sqlite3_api->result_int64
76012#define sqlite3_result_null            sqlite3_api->result_null
76013#define sqlite3_result_text            sqlite3_api->result_text
76014#define sqlite3_result_text16          sqlite3_api->result_text16
76015#define sqlite3_result_text16be        sqlite3_api->result_text16be
76016#define sqlite3_result_text16le        sqlite3_api->result_text16le
76017#define sqlite3_result_value           sqlite3_api->result_value
76018#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
76019#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
76020#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
76021#define sqlite3_snprintf               sqlite3_api->snprintf
76022#define sqlite3_step                   sqlite3_api->step
76023#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
76024#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
76025#define sqlite3_total_changes          sqlite3_api->total_changes
76026#define sqlite3_trace                  sqlite3_api->trace
76027#ifndef SQLITE_OMIT_DEPRECATED
76028#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
76029#endif
76030#define sqlite3_update_hook            sqlite3_api->update_hook
76031#define sqlite3_user_data              sqlite3_api->user_data
76032#define sqlite3_value_blob             sqlite3_api->value_blob
76033#define sqlite3_value_bytes            sqlite3_api->value_bytes
76034#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
76035#define sqlite3_value_double           sqlite3_api->value_double
76036#define sqlite3_value_int              sqlite3_api->value_int
76037#define sqlite3_value_int64            sqlite3_api->value_int64
76038#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
76039#define sqlite3_value_text             sqlite3_api->value_text
76040#define sqlite3_value_text16           sqlite3_api->value_text16
76041#define sqlite3_value_text16be         sqlite3_api->value_text16be
76042#define sqlite3_value_text16le         sqlite3_api->value_text16le
76043#define sqlite3_value_type             sqlite3_api->value_type
76044#define sqlite3_vmprintf               sqlite3_api->vmprintf
76045#define sqlite3_overload_function      sqlite3_api->overload_function
76046#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
76047#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
76048#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
76049#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
76050#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
76051#define sqlite3_blob_close             sqlite3_api->blob_close
76052#define sqlite3_blob_open              sqlite3_api->blob_open
76053#define sqlite3_blob_read              sqlite3_api->blob_read
76054#define sqlite3_blob_write             sqlite3_api->blob_write
76055#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
76056#define sqlite3_file_control           sqlite3_api->file_control
76057#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
76058#define sqlite3_memory_used            sqlite3_api->memory_used
76059#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
76060#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
76061#define sqlite3_mutex_free             sqlite3_api->mutex_free
76062#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
76063#define sqlite3_mutex_try              sqlite3_api->mutex_try
76064#define sqlite3_open_v2                sqlite3_api->open_v2
76065#define sqlite3_release_memory         sqlite3_api->release_memory
76066#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
76067#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
76068#define sqlite3_sleep                  sqlite3_api->sleep
76069#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
76070#define sqlite3_vfs_find               sqlite3_api->vfs_find
76071#define sqlite3_vfs_register           sqlite3_api->vfs_register
76072#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
76073#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
76074#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
76075#define sqlite3_result_error_code      sqlite3_api->result_error_code
76076#define sqlite3_test_control           sqlite3_api->test_control
76077#define sqlite3_randomness             sqlite3_api->randomness
76078#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
76079#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
76080#define sqlite3_limit                  sqlite3_api->limit
76081#define sqlite3_next_stmt              sqlite3_api->next_stmt
76082#define sqlite3_sql                    sqlite3_api->sql
76083#define sqlite3_status                 sqlite3_api->status
76084#endif /* SQLITE_CORE */
76085
76086#define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
76087#define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
76088
76089#endif /* _SQLITE3EXT_H_ */
76090
76091/************** End of sqlite3ext.h ******************************************/
76092/************** Continuing where we left off in loadext.c ********************/
76093
76094#ifndef SQLITE_OMIT_LOAD_EXTENSION
76095
76096/*
76097** Some API routines are omitted when various features are
76098** excluded from a build of SQLite.  Substitute a NULL pointer
76099** for any missing APIs.
76100*/
76101#ifndef SQLITE_ENABLE_COLUMN_METADATA
76102# define sqlite3_column_database_name   0
76103# define sqlite3_column_database_name16 0
76104# define sqlite3_column_table_name      0
76105# define sqlite3_column_table_name16    0
76106# define sqlite3_column_origin_name     0
76107# define sqlite3_column_origin_name16   0
76108# define sqlite3_table_column_metadata  0
76109#endif
76110
76111#ifdef SQLITE_OMIT_AUTHORIZATION
76112# define sqlite3_set_authorizer         0
76113#endif
76114
76115#ifdef SQLITE_OMIT_UTF16
76116# define sqlite3_bind_text16            0
76117# define sqlite3_collation_needed16     0
76118# define sqlite3_column_decltype16      0
76119# define sqlite3_column_name16          0
76120# define sqlite3_column_text16          0
76121# define sqlite3_complete16             0
76122# define sqlite3_create_collation16     0
76123# define sqlite3_create_function16      0
76124# define sqlite3_errmsg16               0
76125# define sqlite3_open16                 0
76126# define sqlite3_prepare16              0
76127# define sqlite3_prepare16_v2           0
76128# define sqlite3_result_error16         0
76129# define sqlite3_result_text16          0
76130# define sqlite3_result_text16be        0
76131# define sqlite3_result_text16le        0
76132# define sqlite3_value_text16           0
76133# define sqlite3_value_text16be         0
76134# define sqlite3_value_text16le         0
76135# define sqlite3_column_database_name16 0
76136# define sqlite3_column_table_name16    0
76137# define sqlite3_column_origin_name16   0
76138#endif
76139
76140#ifdef SQLITE_OMIT_COMPLETE
76141# define sqlite3_complete 0
76142# define sqlite3_complete16 0
76143#endif
76144
76145#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
76146# define sqlite3_progress_handler 0
76147#endif
76148
76149#ifdef SQLITE_OMIT_VIRTUALTABLE
76150# define sqlite3_create_module 0
76151# define sqlite3_create_module_v2 0
76152# define sqlite3_declare_vtab 0
76153#endif
76154
76155#ifdef SQLITE_OMIT_SHARED_CACHE
76156# define sqlite3_enable_shared_cache 0
76157#endif
76158
76159#ifdef SQLITE_OMIT_TRACE
76160# define sqlite3_profile       0
76161# define sqlite3_trace         0
76162#endif
76163
76164#ifdef SQLITE_OMIT_GET_TABLE
76165# define sqlite3_free_table    0
76166# define sqlite3_get_table     0
76167#endif
76168
76169#ifdef SQLITE_OMIT_INCRBLOB
76170#define sqlite3_bind_zeroblob  0
76171#define sqlite3_blob_bytes     0
76172#define sqlite3_blob_close     0
76173#define sqlite3_blob_open      0
76174#define sqlite3_blob_read      0
76175#define sqlite3_blob_write     0
76176#endif
76177
76178/*
76179** The following structure contains pointers to all SQLite API routines.
76180** A pointer to this structure is passed into extensions when they are
76181** loaded so that the extension can make calls back into the SQLite
76182** library.
76183**
76184** When adding new APIs, add them to the bottom of this structure
76185** in order to preserve backwards compatibility.
76186**
76187** Extensions that use newer APIs should first call the
76188** sqlite3_libversion_number() to make sure that the API they
76189** intend to use is supported by the library.  Extensions should
76190** also check to make sure that the pointer to the function is
76191** not NULL before calling it.
76192*/
76193static const sqlite3_api_routines sqlite3Apis = {
76194  sqlite3_aggregate_context,
76195#ifndef SQLITE_OMIT_DEPRECATED
76196  sqlite3_aggregate_count,
76197#else
76198  0,
76199#endif
76200  sqlite3_bind_blob,
76201  sqlite3_bind_double,
76202  sqlite3_bind_int,
76203  sqlite3_bind_int64,
76204  sqlite3_bind_null,
76205  sqlite3_bind_parameter_count,
76206  sqlite3_bind_parameter_index,
76207  sqlite3_bind_parameter_name,
76208  sqlite3_bind_text,
76209  sqlite3_bind_text16,
76210  sqlite3_bind_value,
76211  sqlite3_busy_handler,
76212  sqlite3_busy_timeout,
76213  sqlite3_changes,
76214  sqlite3_close,
76215  sqlite3_collation_needed,
76216  sqlite3_collation_needed16,
76217  sqlite3_column_blob,
76218  sqlite3_column_bytes,
76219  sqlite3_column_bytes16,
76220  sqlite3_column_count,
76221  sqlite3_column_database_name,
76222  sqlite3_column_database_name16,
76223  sqlite3_column_decltype,
76224  sqlite3_column_decltype16,
76225  sqlite3_column_double,
76226  sqlite3_column_int,
76227  sqlite3_column_int64,
76228  sqlite3_column_name,
76229  sqlite3_column_name16,
76230  sqlite3_column_origin_name,
76231  sqlite3_column_origin_name16,
76232  sqlite3_column_table_name,
76233  sqlite3_column_table_name16,
76234  sqlite3_column_text,
76235  sqlite3_column_text16,
76236  sqlite3_column_type,
76237  sqlite3_column_value,
76238  sqlite3_commit_hook,
76239  sqlite3_complete,
76240  sqlite3_complete16,
76241  sqlite3_create_collation,
76242  sqlite3_create_collation16,
76243  sqlite3_create_function,
76244  sqlite3_create_function16,
76245  sqlite3_create_module,
76246  sqlite3_data_count,
76247  sqlite3_db_handle,
76248  sqlite3_declare_vtab,
76249  sqlite3_enable_shared_cache,
76250  sqlite3_errcode,
76251  sqlite3_errmsg,
76252  sqlite3_errmsg16,
76253  sqlite3_exec,
76254#ifndef SQLITE_OMIT_DEPRECATED
76255  sqlite3_expired,
76256#else
76257  0,
76258#endif
76259  sqlite3_finalize,
76260  sqlite3_free,
76261  sqlite3_free_table,
76262  sqlite3_get_autocommit,
76263  sqlite3_get_auxdata,
76264  sqlite3_get_table,
76265  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
76266  sqlite3_interrupt,
76267  sqlite3_last_insert_rowid,
76268  sqlite3_libversion,
76269  sqlite3_libversion_number,
76270  sqlite3_malloc,
76271  sqlite3_mprintf,
76272  sqlite3_open,
76273  sqlite3_open16,
76274  sqlite3_prepare,
76275  sqlite3_prepare16,
76276  sqlite3_profile,
76277  sqlite3_progress_handler,
76278  sqlite3_realloc,
76279  sqlite3_reset,
76280  sqlite3_result_blob,
76281  sqlite3_result_double,
76282  sqlite3_result_error,
76283  sqlite3_result_error16,
76284  sqlite3_result_int,
76285  sqlite3_result_int64,
76286  sqlite3_result_null,
76287  sqlite3_result_text,
76288  sqlite3_result_text16,
76289  sqlite3_result_text16be,
76290  sqlite3_result_text16le,
76291  sqlite3_result_value,
76292  sqlite3_rollback_hook,
76293  sqlite3_set_authorizer,
76294  sqlite3_set_auxdata,
76295  sqlite3_snprintf,
76296  sqlite3_step,
76297  sqlite3_table_column_metadata,
76298#ifndef SQLITE_OMIT_DEPRECATED
76299  sqlite3_thread_cleanup,
76300#else
76301  0,
76302#endif
76303  sqlite3_total_changes,
76304  sqlite3_trace,
76305#ifndef SQLITE_OMIT_DEPRECATED
76306  sqlite3_transfer_bindings,
76307#else
76308  0,
76309#endif
76310  sqlite3_update_hook,
76311  sqlite3_user_data,
76312  sqlite3_value_blob,
76313  sqlite3_value_bytes,
76314  sqlite3_value_bytes16,
76315  sqlite3_value_double,
76316  sqlite3_value_int,
76317  sqlite3_value_int64,
76318  sqlite3_value_numeric_type,
76319  sqlite3_value_text,
76320  sqlite3_value_text16,
76321  sqlite3_value_text16be,
76322  sqlite3_value_text16le,
76323  sqlite3_value_type,
76324  sqlite3_vmprintf,
76325  /*
76326  ** The original API set ends here.  All extensions can call any
76327  ** of the APIs above provided that the pointer is not NULL.  But
76328  ** before calling APIs that follow, extension should check the
76329  ** sqlite3_libversion_number() to make sure they are dealing with
76330  ** a library that is new enough to support that API.
76331  *************************************************************************
76332  */
76333  sqlite3_overload_function,
76334
76335  /*
76336  ** Added after 3.3.13
76337  */
76338  sqlite3_prepare_v2,
76339  sqlite3_prepare16_v2,
76340  sqlite3_clear_bindings,
76341
76342  /*
76343  ** Added for 3.4.1
76344  */
76345  sqlite3_create_module_v2,
76346
76347  /*
76348  ** Added for 3.5.0
76349  */
76350  sqlite3_bind_zeroblob,
76351  sqlite3_blob_bytes,
76352  sqlite3_blob_close,
76353  sqlite3_blob_open,
76354  sqlite3_blob_read,
76355  sqlite3_blob_write,
76356  sqlite3_create_collation_v2,
76357  sqlite3_file_control,
76358  sqlite3_memory_highwater,
76359  sqlite3_memory_used,
76360#ifdef SQLITE_MUTEX_OMIT
76361  0,
76362  0,
76363  0,
76364  0,
76365  0,
76366#else
76367  sqlite3_mutex_alloc,
76368  sqlite3_mutex_enter,
76369  sqlite3_mutex_free,
76370  sqlite3_mutex_leave,
76371  sqlite3_mutex_try,
76372#endif
76373  sqlite3_open_v2,
76374  sqlite3_release_memory,
76375  sqlite3_result_error_nomem,
76376  sqlite3_result_error_toobig,
76377  sqlite3_sleep,
76378  sqlite3_soft_heap_limit,
76379  sqlite3_vfs_find,
76380  sqlite3_vfs_register,
76381  sqlite3_vfs_unregister,
76382
76383  /*
76384  ** Added for 3.5.8
76385  */
76386  sqlite3_threadsafe,
76387  sqlite3_result_zeroblob,
76388  sqlite3_result_error_code,
76389  sqlite3_test_control,
76390  sqlite3_randomness,
76391  sqlite3_context_db_handle,
76392
76393  /*
76394  ** Added for 3.6.0
76395  */
76396  sqlite3_extended_result_codes,
76397  sqlite3_limit,
76398  sqlite3_next_stmt,
76399  sqlite3_sql,
76400  sqlite3_status,
76401};
76402
76403/*
76404** Attempt to load an SQLite extension library contained in the file
76405** zFile.  The entry point is zProc.  zProc may be 0 in which case a
76406** default entry point name (sqlite3_extension_init) is used.  Use
76407** of the default name is recommended.
76408**
76409** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
76410**
76411** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
76412** error message text.  The calling function should free this memory
76413** by calling sqlite3DbFree(db, ).
76414*/
76415static int sqlite3LoadExtension(
76416  sqlite3 *db,          /* Load the extension into this database connection */
76417  const char *zFile,    /* Name of the shared library containing extension */
76418  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
76419  char **pzErrMsg       /* Put error message here if not 0 */
76420){
76421  sqlite3_vfs *pVfs = db->pVfs;
76422  void *handle;
76423  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
76424  char *zErrmsg = 0;
76425  void **aHandle;
76426  const int nMsg = 300;
76427
76428  if( pzErrMsg ) *pzErrMsg = 0;
76429
76430  /* Ticket #1863.  To avoid a creating security problems for older
76431  ** applications that relink against newer versions of SQLite, the
76432  ** ability to run load_extension is turned off by default.  One
76433  ** must call sqlite3_enable_load_extension() to turn on extension
76434  ** loading.  Otherwise you get the following error.
76435  */
76436  if( (db->flags & SQLITE_LoadExtension)==0 ){
76437    if( pzErrMsg ){
76438      *pzErrMsg = sqlite3_mprintf("not authorized");
76439    }
76440    return SQLITE_ERROR;
76441  }
76442
76443  if( zProc==0 ){
76444    zProc = "sqlite3_extension_init";
76445  }
76446
76447  handle = sqlite3OsDlOpen(pVfs, zFile);
76448  if( handle==0 ){
76449    if( pzErrMsg ){
76450      zErrmsg = sqlite3StackAllocZero(db, nMsg);
76451      if( zErrmsg ){
76452        sqlite3_snprintf(nMsg, zErrmsg,
76453            "unable to open shared library [%s]", zFile);
76454        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
76455        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
76456        sqlite3StackFree(db, zErrmsg);
76457      }
76458    }
76459    return SQLITE_ERROR;
76460  }
76461  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
76462                   sqlite3OsDlSym(pVfs, handle, zProc);
76463  if( xInit==0 ){
76464    if( pzErrMsg ){
76465      zErrmsg = sqlite3StackAllocZero(db, nMsg);
76466      if( zErrmsg ){
76467        sqlite3_snprintf(nMsg, zErrmsg,
76468            "no entry point [%s] in shared library [%s]", zProc,zFile);
76469        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
76470        *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
76471        sqlite3StackFree(db, zErrmsg);
76472      }
76473      sqlite3OsDlClose(pVfs, handle);
76474    }
76475    return SQLITE_ERROR;
76476  }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
76477    if( pzErrMsg ){
76478      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
76479    }
76480    sqlite3_free(zErrmsg);
76481    sqlite3OsDlClose(pVfs, handle);
76482    return SQLITE_ERROR;
76483  }
76484
76485  /* Append the new shared library handle to the db->aExtension array. */
76486  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
76487  if( aHandle==0 ){
76488    return SQLITE_NOMEM;
76489  }
76490  if( db->nExtension>0 ){
76491    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
76492  }
76493  sqlite3DbFree(db, db->aExtension);
76494  db->aExtension = aHandle;
76495
76496  db->aExtension[db->nExtension++] = handle;
76497  return SQLITE_OK;
76498}
76499SQLITE_API int sqlite3_load_extension(
76500  sqlite3 *db,          /* Load the extension into this database connection */
76501  const char *zFile,    /* Name of the shared library containing extension */
76502  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
76503  char **pzErrMsg       /* Put error message here if not 0 */
76504){
76505  int rc;
76506  sqlite3_mutex_enter(db->mutex);
76507  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
76508  rc = sqlite3ApiExit(db, rc);
76509  sqlite3_mutex_leave(db->mutex);
76510  return rc;
76511}
76512
76513/*
76514** Call this routine when the database connection is closing in order
76515** to clean up loaded extensions
76516*/
76517SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
76518  int i;
76519  assert( sqlite3_mutex_held(db->mutex) );
76520  for(i=0; i<db->nExtension; i++){
76521    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
76522  }
76523  sqlite3DbFree(db, db->aExtension);
76524}
76525
76526/*
76527** Enable or disable extension loading.  Extension loading is disabled by
76528** default so as not to open security holes in older applications.
76529*/
76530SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
76531  sqlite3_mutex_enter(db->mutex);
76532  if( onoff ){
76533    db->flags |= SQLITE_LoadExtension;
76534  }else{
76535    db->flags &= ~SQLITE_LoadExtension;
76536  }
76537  sqlite3_mutex_leave(db->mutex);
76538  return SQLITE_OK;
76539}
76540
76541#endif /* SQLITE_OMIT_LOAD_EXTENSION */
76542
76543/*
76544** The auto-extension code added regardless of whether or not extension
76545** loading is supported.  We need a dummy sqlite3Apis pointer for that
76546** code if regular extension loading is not available.  This is that
76547** dummy pointer.
76548*/
76549#ifdef SQLITE_OMIT_LOAD_EXTENSION
76550static const sqlite3_api_routines sqlite3Apis = { 0 };
76551#endif
76552
76553
76554/*
76555** The following object holds the list of automatically loaded
76556** extensions.
76557**
76558** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
76559** mutex must be held while accessing this list.
76560*/
76561typedef struct sqlite3AutoExtList sqlite3AutoExtList;
76562static SQLITE_WSD struct sqlite3AutoExtList {
76563  int nExt;              /* Number of entries in aExt[] */
76564  void (**aExt)(void);   /* Pointers to the extension init functions */
76565} sqlite3Autoext = { 0, 0 };
76566
76567/* The "wsdAutoext" macro will resolve to the autoextension
76568** state vector.  If writable static data is unsupported on the target,
76569** we have to locate the state vector at run-time.  In the more common
76570** case where writable static data is supported, wsdStat can refer directly
76571** to the "sqlite3Autoext" state vector declared above.
76572*/
76573#ifdef SQLITE_OMIT_WSD
76574# define wsdAutoextInit \
76575  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
76576# define wsdAutoext x[0]
76577#else
76578# define wsdAutoextInit
76579# define wsdAutoext sqlite3Autoext
76580#endif
76581
76582
76583/*
76584** Register a statically linked extension that is automatically
76585** loaded by every new database connection.
76586*/
76587SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
76588  int rc = SQLITE_OK;
76589#ifndef SQLITE_OMIT_AUTOINIT
76590  rc = sqlite3_initialize();
76591  if( rc ){
76592    return rc;
76593  }else
76594#endif
76595  {
76596    int i;
76597#if SQLITE_THREADSAFE
76598    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76599#endif
76600    wsdAutoextInit;
76601    sqlite3_mutex_enter(mutex);
76602    for(i=0; i<wsdAutoext.nExt; i++){
76603      if( wsdAutoext.aExt[i]==xInit ) break;
76604    }
76605    if( i==wsdAutoext.nExt ){
76606      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
76607      void (**aNew)(void);
76608      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
76609      if( aNew==0 ){
76610        rc = SQLITE_NOMEM;
76611      }else{
76612        wsdAutoext.aExt = aNew;
76613        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
76614        wsdAutoext.nExt++;
76615      }
76616    }
76617    sqlite3_mutex_leave(mutex);
76618    assert( (rc&0xff)==rc );
76619    return rc;
76620  }
76621}
76622
76623/*
76624** Reset the automatic extension loading mechanism.
76625*/
76626SQLITE_API void sqlite3_reset_auto_extension(void){
76627#ifndef SQLITE_OMIT_AUTOINIT
76628  if( sqlite3_initialize()==SQLITE_OK )
76629#endif
76630  {
76631#if SQLITE_THREADSAFE
76632    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76633#endif
76634    wsdAutoextInit;
76635    sqlite3_mutex_enter(mutex);
76636    sqlite3_free(wsdAutoext.aExt);
76637    wsdAutoext.aExt = 0;
76638    wsdAutoext.nExt = 0;
76639    sqlite3_mutex_leave(mutex);
76640  }
76641}
76642
76643/*
76644** Load all automatic extensions.
76645**
76646** If anything goes wrong, set an error in the database connection.
76647*/
76648SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
76649  int i;
76650  int go = 1;
76651  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
76652
76653  wsdAutoextInit;
76654  if( wsdAutoext.nExt==0 ){
76655    /* Common case: early out without every having to acquire a mutex */
76656    return;
76657  }
76658  for(i=0; go; i++){
76659    char *zErrmsg;
76660#if SQLITE_THREADSAFE
76661    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
76662#endif
76663    sqlite3_mutex_enter(mutex);
76664    if( i>=wsdAutoext.nExt ){
76665      xInit = 0;
76666      go = 0;
76667    }else{
76668      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
76669              wsdAutoext.aExt[i];
76670    }
76671    sqlite3_mutex_leave(mutex);
76672    zErrmsg = 0;
76673    if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
76674      sqlite3Error(db, SQLITE_ERROR,
76675            "automatic extension loading failed: %s", zErrmsg);
76676      go = 0;
76677    }
76678    sqlite3_free(zErrmsg);
76679  }
76680}
76681
76682/************** End of loadext.c *********************************************/
76683/************** Begin file pragma.c ******************************************/
76684/*
76685** 2003 April 6
76686**
76687** The author disclaims copyright to this source code.  In place of
76688** a legal notice, here is a blessing:
76689**
76690**    May you do good and not evil.
76691**    May you find forgiveness for yourself and forgive others.
76692**    May you share freely, never taking more than you give.
76693**
76694*************************************************************************
76695** This file contains code used to implement the PRAGMA command.
76696*/
76697
76698/* Ignore this whole file if pragmas are disabled
76699*/
76700#if !defined(SQLITE_OMIT_PRAGMA)
76701
76702/*
76703** Interpret the given string as a safety level.  Return 0 for OFF,
76704** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
76705** unrecognized string argument.
76706**
76707** Note that the values returned are one less that the values that
76708** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
76709** to support legacy SQL code.  The safety level used to be boolean
76710** and older scripts may have used numbers 0 for OFF and 1 for ON.
76711*/
76712static u8 getSafetyLevel(const char *z){
76713                             /* 123456789 123456789 */
76714  static const char zText[] = "onoffalseyestruefull";
76715  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
76716  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
76717  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
76718  int i, n;
76719  if( sqlite3Isdigit(*z) ){
76720    return (u8)atoi(z);
76721  }
76722  n = sqlite3Strlen30(z);
76723  for(i=0; i<ArraySize(iLength); i++){
76724    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
76725      return iValue[i];
76726    }
76727  }
76728  return 1;
76729}
76730
76731/*
76732** Interpret the given string as a boolean value.
76733*/
76734static u8 getBoolean(const char *z){
76735  return getSafetyLevel(z)&1;
76736}
76737
76738/*
76739** Interpret the given string as a locking mode value.
76740*/
76741static int getLockingMode(const char *z){
76742  if( z ){
76743    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
76744    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
76745  }
76746  return PAGER_LOCKINGMODE_QUERY;
76747}
76748
76749#ifndef SQLITE_OMIT_AUTOVACUUM
76750/*
76751** Interpret the given string as an auto-vacuum mode value.
76752**
76753** The following strings, "none", "full" and "incremental" are
76754** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
76755*/
76756static int getAutoVacuum(const char *z){
76757  int i;
76758  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
76759  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
76760  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
76761  i = atoi(z);
76762  return (u8)((i>=0&&i<=2)?i:0);
76763}
76764#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
76765
76766#ifndef SQLITE_OMIT_PAGER_PRAGMAS
76767/*
76768** Interpret the given string as a temp db location. Return 1 for file
76769** backed temporary databases, 2 for the Red-Black tree in memory database
76770** and 0 to use the compile-time default.
76771*/
76772static int getTempStore(const char *z){
76773  if( z[0]>='0' && z[0]<='2' ){
76774    return z[0] - '0';
76775  }else if( sqlite3StrICmp(z, "file")==0 ){
76776    return 1;
76777  }else if( sqlite3StrICmp(z, "memory")==0 ){
76778    return 2;
76779  }else{
76780    return 0;
76781  }
76782}
76783#endif /* SQLITE_PAGER_PRAGMAS */
76784
76785#ifndef SQLITE_OMIT_PAGER_PRAGMAS
76786/*
76787** Invalidate temp storage, either when the temp storage is changed
76788** from default, or when 'file' and the temp_store_directory has changed
76789*/
76790static int invalidateTempStorage(Parse *pParse){
76791  sqlite3 *db = pParse->db;
76792  if( db->aDb[1].pBt!=0 ){
76793    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
76794      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
76795        "from within a transaction");
76796      return SQLITE_ERROR;
76797    }
76798    sqlite3BtreeClose(db->aDb[1].pBt);
76799    db->aDb[1].pBt = 0;
76800    sqlite3ResetInternalSchema(db, 0);
76801  }
76802  return SQLITE_OK;
76803}
76804#endif /* SQLITE_PAGER_PRAGMAS */
76805
76806#ifndef SQLITE_OMIT_PAGER_PRAGMAS
76807/*
76808** If the TEMP database is open, close it and mark the database schema
76809** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
76810** or DEFAULT_TEMP_STORE pragmas.
76811*/
76812static int changeTempStorage(Parse *pParse, const char *zStorageType){
76813  int ts = getTempStore(zStorageType);
76814  sqlite3 *db = pParse->db;
76815  if( db->temp_store==ts ) return SQLITE_OK;
76816  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
76817    return SQLITE_ERROR;
76818  }
76819  db->temp_store = (u8)ts;
76820  return SQLITE_OK;
76821}
76822#endif /* SQLITE_PAGER_PRAGMAS */
76823
76824/*
76825** Generate code to return a single integer value.
76826*/
76827static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
76828  Vdbe *v = sqlite3GetVdbe(pParse);
76829  int mem = ++pParse->nMem;
76830  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
76831  if( pI64 ){
76832    memcpy(pI64, &value, sizeof(value));
76833  }
76834  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
76835  sqlite3VdbeSetNumCols(v, 1);
76836  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
76837  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
76838}
76839
76840#ifndef SQLITE_OMIT_FLAG_PRAGMAS
76841/*
76842** Check to see if zRight and zLeft refer to a pragma that queries
76843** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
76844** Also, implement the pragma.
76845*/
76846static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
76847  static const struct sPragmaType {
76848    const char *zName;  /* Name of the pragma */
76849    int mask;           /* Mask for the db->flags value */
76850  } aPragma[] = {
76851    { "full_column_names",        SQLITE_FullColNames  },
76852    { "short_column_names",       SQLITE_ShortColNames },
76853    { "count_changes",            SQLITE_CountRows     },
76854    { "empty_result_callbacks",   SQLITE_NullCallback  },
76855    { "legacy_file_format",       SQLITE_LegacyFileFmt },
76856    { "fullfsync",                SQLITE_FullFSync     },
76857    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
76858#ifdef SQLITE_DEBUG
76859    { "sql_trace",                SQLITE_SqlTrace      },
76860    { "vdbe_listing",             SQLITE_VdbeListing   },
76861    { "vdbe_trace",               SQLITE_VdbeTrace     },
76862#endif
76863#ifndef SQLITE_OMIT_CHECK
76864    { "ignore_check_constraints", SQLITE_IgnoreChecks  },
76865#endif
76866    /* The following is VERY experimental */
76867    { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
76868    { "omit_readlock",            SQLITE_NoReadlock    },
76869
76870    /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
76871    ** flag if there are any active statements. */
76872    { "read_uncommitted",         SQLITE_ReadUncommitted },
76873    { "recursive_triggers",       SQLITE_RecTriggers },
76874
76875    /* This flag may only be set if both foreign-key and trigger support
76876    ** are present in the build.  */
76877#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
76878    { "foreign_keys",             SQLITE_ForeignKeys },
76879#endif
76880  };
76881  int i;
76882  const struct sPragmaType *p;
76883  for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
76884    if( sqlite3StrICmp(zLeft, p->zName)==0 ){
76885      sqlite3 *db = pParse->db;
76886      Vdbe *v;
76887      v = sqlite3GetVdbe(pParse);
76888      assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
76889      if( ALWAYS(v) ){
76890        if( zRight==0 ){
76891          returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
76892        }else{
76893          int mask = p->mask;          /* Mask of bits to set or clear. */
76894          if( db->autoCommit==0 ){
76895            /* Foreign key support may not be enabled or disabled while not
76896            ** in auto-commit mode.  */
76897            mask &= ~(SQLITE_ForeignKeys);
76898          }
76899
76900          if( getBoolean(zRight) ){
76901            db->flags |= mask;
76902          }else{
76903            db->flags &= ~mask;
76904          }
76905
76906          /* Many of the flag-pragmas modify the code generated by the SQL
76907          ** compiler (eg. count_changes). So add an opcode to expire all
76908          ** compiled SQL statements after modifying a pragma value.
76909          */
76910          sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
76911        }
76912      }
76913
76914      return 1;
76915    }
76916  }
76917  return 0;
76918}
76919#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
76920
76921/*
76922** Return a human-readable name for a constraint resolution action.
76923*/
76924#ifndef SQLITE_OMIT_FOREIGN_KEY
76925static const char *actionName(u8 action){
76926  const char *zName;
76927  switch( action ){
76928    case OE_SetNull:  zName = "SET NULL";        break;
76929    case OE_SetDflt:  zName = "SET DEFAULT";     break;
76930    case OE_Cascade:  zName = "CASCADE";         break;
76931    case OE_Restrict: zName = "RESTRICT";        break;
76932    default:          zName = "NO ACTION";
76933                      assert( action==OE_None ); break;
76934  }
76935  return zName;
76936}
76937#endif
76938
76939/*
76940** Process a pragma statement.
76941**
76942** Pragmas are of this form:
76943**
76944**      PRAGMA [database.]id [= value]
76945**
76946** The identifier might also be a string.  The value is a string, and
76947** identifier, or a number.  If minusFlag is true, then the value is
76948** a number that was preceded by a minus sign.
76949**
76950** If the left side is "database.id" then pId1 is the database name
76951** and pId2 is the id.  If the left side is just "id" then pId1 is the
76952** id and pId2 is any empty string.
76953*/
76954SQLITE_PRIVATE void sqlite3Pragma(
76955  Parse *pParse,
76956  Token *pId1,        /* First part of [database.]id field */
76957  Token *pId2,        /* Second part of [database.]id field, or NULL */
76958  Token *pValue,      /* Token for <value>, or NULL */
76959  int minusFlag       /* True if a '-' sign preceded <value> */
76960){
76961  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
76962  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
76963  const char *zDb = 0;   /* The database name */
76964  Token *pId;            /* Pointer to <id> token */
76965  int iDb;               /* Database index for <database> */
76966  sqlite3 *db = pParse->db;
76967  Db *pDb;
76968  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
76969  if( v==0 ) return;
76970  pParse->nMem = 2;
76971
76972  /* Interpret the [database.] part of the pragma statement. iDb is the
76973  ** index of the database this pragma is being applied to in db.aDb[]. */
76974  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
76975  if( iDb<0 ) return;
76976  pDb = &db->aDb[iDb];
76977
76978  /* If the temp database has been explicitly named as part of the
76979  ** pragma, make sure it is open.
76980  */
76981  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
76982    return;
76983  }
76984
76985  zLeft = sqlite3NameFromToken(db, pId);
76986  if( !zLeft ) return;
76987  if( minusFlag ){
76988    zRight = sqlite3MPrintf(db, "-%T", pValue);
76989  }else{
76990    zRight = sqlite3NameFromToken(db, pValue);
76991  }
76992
76993  assert( pId2 );
76994  zDb = pId2->n>0 ? pDb->zName : 0;
76995  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
76996    goto pragma_out;
76997  }
76998
76999#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77000  /*
77001  **  PRAGMA [database.]default_cache_size
77002  **  PRAGMA [database.]default_cache_size=N
77003  **
77004  ** The first form reports the current persistent setting for the
77005  ** page cache size.  The value returned is the maximum number of
77006  ** pages in the page cache.  The second form sets both the current
77007  ** page cache size value and the persistent page cache size value
77008  ** stored in the database file.
77009  **
77010  ** The default cache size is stored in meta-value 2 of page 1 of the
77011  ** database file.  The cache size is actually the absolute value of
77012  ** this memory location.  The sign of meta-value 2 determines the
77013  ** synchronous setting.  A negative value means synchronous is off
77014  ** and a positive value means synchronous is on.
77015  */
77016  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
77017    static const VdbeOpList getCacheSize[] = {
77018      { OP_Transaction, 0, 0,        0},                         /* 0 */
77019      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
77020      { OP_IfPos,       1, 7,        0},
77021      { OP_Integer,     0, 2,        0},
77022      { OP_Subtract,    1, 2,        1},
77023      { OP_IfPos,       1, 7,        0},
77024      { OP_Integer,     0, 1,        0},                         /* 6 */
77025      { OP_ResultRow,   1, 1,        0},
77026    };
77027    int addr;
77028    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77029    sqlite3VdbeUsesBtree(v, iDb);
77030    if( !zRight ){
77031      sqlite3VdbeSetNumCols(v, 1);
77032      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
77033      pParse->nMem += 2;
77034      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
77035      sqlite3VdbeChangeP1(v, addr, iDb);
77036      sqlite3VdbeChangeP1(v, addr+1, iDb);
77037      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
77038    }else{
77039      int size = atoi(zRight);
77040      if( size<0 ) size = -size;
77041      sqlite3BeginWriteOperation(pParse, 0, iDb);
77042      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
77043      sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, BTREE_DEFAULT_CACHE_SIZE);
77044      addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
77045      sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
77046      sqlite3VdbeJumpHere(v, addr);
77047      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
77048      pDb->pSchema->cache_size = size;
77049      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
77050    }
77051  }else
77052
77053  /*
77054  **  PRAGMA [database.]page_size
77055  **  PRAGMA [database.]page_size=N
77056  **
77057  ** The first form reports the current setting for the
77058  ** database page size in bytes.  The second form sets the
77059  ** database page size value.  The value can only be set if
77060  ** the database has not yet been created.
77061  */
77062  if( sqlite3StrICmp(zLeft,"page_size")==0 ){
77063    Btree *pBt = pDb->pBt;
77064    assert( pBt!=0 );
77065    if( !zRight ){
77066      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
77067      returnSingleInt(pParse, "page_size", size);
77068    }else{
77069      /* Malloc may fail when setting the page-size, as there is an internal
77070      ** buffer that the pager module resizes using sqlite3_realloc().
77071      */
77072      db->nextPagesize = atoi(zRight);
77073      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
77074        db->mallocFailed = 1;
77075      }
77076    }
77077  }else
77078
77079  /*
77080  **  PRAGMA [database.]max_page_count
77081  **  PRAGMA [database.]max_page_count=N
77082  **
77083  ** The first form reports the current setting for the
77084  ** maximum number of pages in the database file.  The
77085  ** second form attempts to change this setting.  Both
77086  ** forms return the current setting.
77087  */
77088  if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
77089    Btree *pBt = pDb->pBt;
77090    int newMax = 0;
77091    assert( pBt!=0 );
77092    if( zRight ){
77093      newMax = atoi(zRight);
77094    }
77095    if( ALWAYS(pBt) ){
77096      newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
77097    }
77098    returnSingleInt(pParse, "max_page_count", newMax);
77099  }else
77100
77101  /*
77102  **  PRAGMA [database.]page_count
77103  **
77104  ** Return the number of pages in the specified database.
77105  */
77106  if( sqlite3StrICmp(zLeft,"page_count")==0 ){
77107    int iReg;
77108    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77109    sqlite3CodeVerifySchema(pParse, iDb);
77110    iReg = ++pParse->nMem;
77111    sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
77112    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
77113    sqlite3VdbeSetNumCols(v, 1);
77114    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
77115  }else
77116
77117  /*
77118  **  PRAGMA [database.]locking_mode
77119  **  PRAGMA [database.]locking_mode = (normal|exclusive)
77120  */
77121  if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
77122    const char *zRet = "normal";
77123    int eMode = getLockingMode(zRight);
77124
77125    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
77126      /* Simple "PRAGMA locking_mode;" statement. This is a query for
77127      ** the current default locking mode (which may be different to
77128      ** the locking-mode of the main database).
77129      */
77130      eMode = db->dfltLockMode;
77131    }else{
77132      Pager *pPager;
77133      if( pId2->n==0 ){
77134        /* This indicates that no database name was specified as part
77135        ** of the PRAGMA command. In this case the locking-mode must be
77136        ** set on all attached databases, as well as the main db file.
77137        **
77138        ** Also, the sqlite3.dfltLockMode variable is set so that
77139        ** any subsequently attached databases also use the specified
77140        ** locking mode.
77141        */
77142        int ii;
77143        assert(pDb==&db->aDb[0]);
77144        for(ii=2; ii<db->nDb; ii++){
77145          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
77146          sqlite3PagerLockingMode(pPager, eMode);
77147        }
77148        db->dfltLockMode = (u8)eMode;
77149      }
77150      pPager = sqlite3BtreePager(pDb->pBt);
77151      eMode = sqlite3PagerLockingMode(pPager, eMode);
77152    }
77153
77154    assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
77155    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
77156      zRet = "exclusive";
77157    }
77158    sqlite3VdbeSetNumCols(v, 1);
77159    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
77160    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
77161    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77162  }else
77163
77164  /*
77165  **  PRAGMA [database.]journal_mode
77166  **  PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory)
77167  */
77168  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
77169    int eMode;
77170    static char * const azModeName[] = {
77171      "delete", "persist", "off", "truncate", "memory"
77172    };
77173
77174    if( zRight==0 ){
77175      eMode = PAGER_JOURNALMODE_QUERY;
77176    }else{
77177      int n = sqlite3Strlen30(zRight);
77178      eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
77179      while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
77180        eMode--;
77181      }
77182    }
77183    if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
77184      /* Simple "PRAGMA journal_mode;" statement. This is a query for
77185      ** the current default journal mode (which may be different to
77186      ** the journal-mode of the main database).
77187      */
77188      eMode = db->dfltJournalMode;
77189    }else{
77190      Pager *pPager;
77191      if( pId2->n==0 ){
77192        /* This indicates that no database name was specified as part
77193        ** of the PRAGMA command. In this case the journal-mode must be
77194        ** set on all attached databases, as well as the main db file.
77195        **
77196        ** Also, the sqlite3.dfltJournalMode variable is set so that
77197        ** any subsequently attached databases also use the specified
77198        ** journal mode.
77199        */
77200        int ii;
77201        assert(pDb==&db->aDb[0]);
77202        for(ii=1; ii<db->nDb; ii++){
77203          if( db->aDb[ii].pBt ){
77204            pPager = sqlite3BtreePager(db->aDb[ii].pBt);
77205            sqlite3PagerJournalMode(pPager, eMode);
77206          }
77207        }
77208        db->dfltJournalMode = (u8)eMode;
77209      }
77210      pPager = sqlite3BtreePager(pDb->pBt);
77211      eMode = sqlite3PagerJournalMode(pPager, eMode);
77212    }
77213    assert( eMode==PAGER_JOURNALMODE_DELETE
77214              || eMode==PAGER_JOURNALMODE_TRUNCATE
77215              || eMode==PAGER_JOURNALMODE_PERSIST
77216              || eMode==PAGER_JOURNALMODE_OFF
77217              || eMode==PAGER_JOURNALMODE_MEMORY );
77218    sqlite3VdbeSetNumCols(v, 1);
77219    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
77220    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0,
77221           azModeName[eMode], P4_STATIC);
77222    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77223  }else
77224
77225  /*
77226  **  PRAGMA [database.]journal_size_limit
77227  **  PRAGMA [database.]journal_size_limit=N
77228  **
77229  ** Get or set the size limit on rollback journal files.
77230  */
77231  if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
77232    Pager *pPager = sqlite3BtreePager(pDb->pBt);
77233    i64 iLimit = -2;
77234    if( zRight ){
77235      sqlite3Atoi64(zRight, &iLimit);
77236      if( iLimit<-1 ) iLimit = -1;
77237    }
77238    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
77239    returnSingleInt(pParse, "journal_size_limit", iLimit);
77240  }else
77241
77242#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
77243
77244  /*
77245  **  PRAGMA [database.]auto_vacuum
77246  **  PRAGMA [database.]auto_vacuum=N
77247  **
77248  ** Get or set the value of the database 'auto-vacuum' parameter.
77249  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
77250  */
77251#ifndef SQLITE_OMIT_AUTOVACUUM
77252  if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
77253    Btree *pBt = pDb->pBt;
77254    assert( pBt!=0 );
77255    if( sqlite3ReadSchema(pParse) ){
77256      goto pragma_out;
77257    }
77258    if( !zRight ){
77259      int auto_vacuum;
77260      if( ALWAYS(pBt) ){
77261         auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
77262      }else{
77263         auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
77264      }
77265      returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
77266    }else{
77267      int eAuto = getAutoVacuum(zRight);
77268      assert( eAuto>=0 && eAuto<=2 );
77269      db->nextAutovac = (u8)eAuto;
77270      if( ALWAYS(eAuto>=0) ){
77271        /* Call SetAutoVacuum() to set initialize the internal auto and
77272        ** incr-vacuum flags. This is required in case this connection
77273        ** creates the database file. It is important that it is created
77274        ** as an auto-vacuum capable db.
77275        */
77276        int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
77277        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
77278          /* When setting the auto_vacuum mode to either "full" or
77279          ** "incremental", write the value of meta[6] in the database
77280          ** file. Before writing to meta[6], check that meta[3] indicates
77281          ** that this really is an auto-vacuum capable database.
77282          */
77283          static const VdbeOpList setMeta6[] = {
77284            { OP_Transaction,    0,         1,                 0},    /* 0 */
77285            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
77286            { OP_If,             1,         0,                 0},    /* 2 */
77287            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
77288            { OP_Integer,        0,         1,                 0},    /* 4 */
77289            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
77290          };
77291          int iAddr;
77292          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
77293          sqlite3VdbeChangeP1(v, iAddr, iDb);
77294          sqlite3VdbeChangeP1(v, iAddr+1, iDb);
77295          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
77296          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
77297          sqlite3VdbeChangeP1(v, iAddr+5, iDb);
77298          sqlite3VdbeUsesBtree(v, iDb);
77299        }
77300      }
77301    }
77302  }else
77303#endif
77304
77305  /*
77306  **  PRAGMA [database.]incremental_vacuum(N)
77307  **
77308  ** Do N steps of incremental vacuuming on a database.
77309  */
77310#ifndef SQLITE_OMIT_AUTOVACUUM
77311  if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
77312    int iLimit, addr;
77313    if( sqlite3ReadSchema(pParse) ){
77314      goto pragma_out;
77315    }
77316    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
77317      iLimit = 0x7fffffff;
77318    }
77319    sqlite3BeginWriteOperation(pParse, 0, iDb);
77320    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
77321    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
77322    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
77323    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
77324    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
77325    sqlite3VdbeJumpHere(v, addr);
77326  }else
77327#endif
77328
77329#ifndef SQLITE_OMIT_PAGER_PRAGMAS
77330  /*
77331  **  PRAGMA [database.]cache_size
77332  **  PRAGMA [database.]cache_size=N
77333  **
77334  ** The first form reports the current local setting for the
77335  ** page cache size.  The local setting can be different from
77336  ** the persistent cache size value that is stored in the database
77337  ** file itself.  The value returned is the maximum number of
77338  ** pages in the page cache.  The second form sets the local
77339  ** page cache size value.  It does not change the persistent
77340  ** cache size stored on the disk so the cache size will revert
77341  ** to its default value when the database is closed and reopened.
77342  ** N should be a positive integer.
77343  */
77344  if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
77345    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77346    if( !zRight ){
77347      returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
77348    }else{
77349      int size = atoi(zRight);
77350      if( size<0 ) size = -size;
77351      pDb->pSchema->cache_size = size;
77352      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
77353    }
77354  }else
77355
77356  /*
77357  **   PRAGMA temp_store
77358  **   PRAGMA temp_store = "default"|"memory"|"file"
77359  **
77360  ** Return or set the local value of the temp_store flag.  Changing
77361  ** the local value does not make changes to the disk file and the default
77362  ** value will be restored the next time the database is opened.
77363  **
77364  ** Note that it is possible for the library compile-time options to
77365  ** override this setting
77366  */
77367  if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
77368    if( !zRight ){
77369      returnSingleInt(pParse, "temp_store", db->temp_store);
77370    }else{
77371      changeTempStorage(pParse, zRight);
77372    }
77373  }else
77374
77375  /*
77376  **   PRAGMA temp_store_directory
77377  **   PRAGMA temp_store_directory = ""|"directory_name"
77378  **
77379  ** Return or set the local value of the temp_store_directory flag.  Changing
77380  ** the value sets a specific directory to be used for temporary files.
77381  ** Setting to a null string reverts to the default temporary directory search.
77382  ** If temporary directory is changed, then invalidateTempStorage.
77383  **
77384  */
77385  if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
77386    if( !zRight ){
77387      if( sqlite3_temp_directory ){
77388        sqlite3VdbeSetNumCols(v, 1);
77389        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
77390            "temp_store_directory", SQLITE_STATIC);
77391        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
77392        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77393      }
77394    }else{
77395#ifndef SQLITE_OMIT_WSD
77396      if( zRight[0] ){
77397        int rc;
77398        int res;
77399        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
77400        if( rc!=SQLITE_OK || res==0 ){
77401          sqlite3ErrorMsg(pParse, "not a writable directory");
77402          goto pragma_out;
77403        }
77404      }
77405      if( SQLITE_TEMP_STORE==0
77406       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
77407       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
77408      ){
77409        invalidateTempStorage(pParse);
77410      }
77411      sqlite3_free(sqlite3_temp_directory);
77412      if( zRight[0] ){
77413        sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
77414      }else{
77415        sqlite3_temp_directory = 0;
77416      }
77417#endif /* SQLITE_OMIT_WSD */
77418    }
77419  }else
77420
77421#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
77422#  if defined(__APPLE__)
77423#    define SQLITE_ENABLE_LOCKING_STYLE 1
77424#  else
77425#    define SQLITE_ENABLE_LOCKING_STYLE 0
77426#  endif
77427#endif
77428#if SQLITE_ENABLE_LOCKING_STYLE
77429  /*
77430   **   PRAGMA [database.]lock_proxy_file
77431   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
77432   **
77433   ** Return or set the value of the lock_proxy_file flag.  Changing
77434   ** the value sets a specific file to be used for database access locks.
77435   **
77436   */
77437  if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
77438    if( !zRight ){
77439      Pager *pPager = sqlite3BtreePager(pDb->pBt);
77440      char *proxy_file_path = NULL;
77441      sqlite3_file *pFile = sqlite3PagerFile(pPager);
77442      sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE,
77443                           &proxy_file_path);
77444
77445      if( proxy_file_path ){
77446        sqlite3VdbeSetNumCols(v, 1);
77447        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
77448                              "lock_proxy_file", SQLITE_STATIC);
77449        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
77450        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77451      }
77452    }else{
77453      Pager *pPager = sqlite3BtreePager(pDb->pBt);
77454      sqlite3_file *pFile = sqlite3PagerFile(pPager);
77455      int res;
77456      if( zRight[0] ){
77457        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
77458                                     zRight);
77459      } else {
77460        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
77461                                     NULL);
77462      }
77463      if( res!=SQLITE_OK ){
77464        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
77465        goto pragma_out;
77466      }
77467    }
77468  }else
77469#endif /* SQLITE_ENABLE_LOCKING_STYLE */
77470
77471  /*
77472  **   PRAGMA [database.]synchronous
77473  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
77474  **
77475  ** Return or set the local value of the synchronous flag.  Changing
77476  ** the local value does not make changes to the disk file and the
77477  ** default value will be restored the next time the database is
77478  ** opened.
77479  */
77480  if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
77481    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77482    if( !zRight ){
77483      returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
77484    }else{
77485      if( !db->autoCommit ){
77486        sqlite3ErrorMsg(pParse,
77487            "Safety level may not be changed inside a transaction");
77488      }else{
77489        pDb->safety_level = getSafetyLevel(zRight)+1;
77490      }
77491    }
77492  }else
77493#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
77494
77495#ifndef SQLITE_OMIT_FLAG_PRAGMAS
77496  if( flagPragma(pParse, zLeft, zRight) ){
77497    /* The flagPragma() subroutine also generates any necessary code
77498    ** there is nothing more to do here */
77499  }else
77500#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
77501
77502#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
77503  /*
77504  **   PRAGMA table_info(<table>)
77505  **
77506  ** Return a single row for each column of the named table. The columns of
77507  ** the returned data set are:
77508  **
77509  ** cid:        Column id (numbered from left to right, starting at 0)
77510  ** name:       Column name
77511  ** type:       Column declaration type.
77512  ** notnull:    True if 'NOT NULL' is part of column declaration
77513  ** dflt_value: The default value for the column, if any.
77514  */
77515  if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
77516    Table *pTab;
77517    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77518    pTab = sqlite3FindTable(db, zRight, zDb);
77519    if( pTab ){
77520      int i;
77521      int nHidden = 0;
77522      Column *pCol;
77523      sqlite3VdbeSetNumCols(v, 6);
77524      pParse->nMem = 6;
77525      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
77526      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77527      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
77528      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
77529      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
77530      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
77531      sqlite3ViewGetColumnNames(pParse, pTab);
77532      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
77533        if( IsHiddenColumn(pCol) ){
77534          nHidden++;
77535          continue;
77536        }
77537        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
77538        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
77539        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
77540           pCol->zType ? pCol->zType : "", 0);
77541        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
77542        if( pCol->zDflt ){
77543          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
77544        }else{
77545          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
77546        }
77547        sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
77548        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
77549      }
77550    }
77551  }else
77552
77553  if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
77554    Index *pIdx;
77555    Table *pTab;
77556    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77557    pIdx = sqlite3FindIndex(db, zRight, zDb);
77558    if( pIdx ){
77559      int i;
77560      pTab = pIdx->pTable;
77561      sqlite3VdbeSetNumCols(v, 3);
77562      pParse->nMem = 3;
77563      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
77564      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
77565      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
77566      for(i=0; i<pIdx->nColumn; i++){
77567        int cnum = pIdx->aiColumn[i];
77568        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77569        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
77570        assert( pTab->nCol>cnum );
77571        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
77572        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77573      }
77574    }
77575  }else
77576
77577  if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
77578    Index *pIdx;
77579    Table *pTab;
77580    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77581    pTab = sqlite3FindTable(db, zRight, zDb);
77582    if( pTab ){
77583      v = sqlite3GetVdbe(pParse);
77584      pIdx = pTab->pIndex;
77585      if( pIdx ){
77586        int i = 0;
77587        sqlite3VdbeSetNumCols(v, 3);
77588        pParse->nMem = 3;
77589        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77590        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77591        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
77592        while(pIdx){
77593          sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77594          sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
77595          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
77596          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77597          ++i;
77598          pIdx = pIdx->pNext;
77599        }
77600      }
77601    }
77602  }else
77603
77604  if( sqlite3StrICmp(zLeft, "database_list")==0 ){
77605    int i;
77606    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77607    sqlite3VdbeSetNumCols(v, 3);
77608    pParse->nMem = 3;
77609    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77610    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77611    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
77612    for(i=0; i<db->nDb; i++){
77613      if( db->aDb[i].pBt==0 ) continue;
77614      assert( db->aDb[i].zName!=0 );
77615      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77616      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
77617      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
77618           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
77619      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
77620    }
77621  }else
77622
77623  if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
77624    int i = 0;
77625    HashElem *p;
77626    sqlite3VdbeSetNumCols(v, 2);
77627    pParse->nMem = 2;
77628    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
77629    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
77630    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
77631      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
77632      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
77633      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
77634      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
77635    }
77636  }else
77637#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
77638
77639#ifndef SQLITE_OMIT_FOREIGN_KEY
77640  if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
77641    FKey *pFK;
77642    Table *pTab;
77643    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77644    pTab = sqlite3FindTable(db, zRight, zDb);
77645    if( pTab ){
77646      v = sqlite3GetVdbe(pParse);
77647      pFK = pTab->pFKey;
77648      if( pFK ){
77649        int i = 0;
77650        sqlite3VdbeSetNumCols(v, 8);
77651        pParse->nMem = 8;
77652        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
77653        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
77654        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
77655        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
77656        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
77657        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
77658        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
77659        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
77660        while(pFK){
77661          int j;
77662          for(j=0; j<pFK->nCol; j++){
77663            char *zCol = pFK->aCol[j].zCol;
77664            char *zOnDelete = (char *)actionName(pFK->aAction[0]);
77665            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
77666            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
77667            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
77668            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
77669            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
77670                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
77671            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
77672            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
77673            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
77674            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
77675            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
77676          }
77677          ++i;
77678          pFK = pFK->pNextFrom;
77679        }
77680      }
77681    }
77682  }else
77683#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
77684
77685#ifndef NDEBUG
77686  if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
77687    if( zRight ){
77688      if( getBoolean(zRight) ){
77689        sqlite3ParserTrace(stderr, "parser: ");
77690      }else{
77691        sqlite3ParserTrace(0, 0);
77692      }
77693    }
77694  }else
77695#endif
77696
77697  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
77698  ** used will be case sensitive or not depending on the RHS.
77699  */
77700  if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
77701    if( zRight ){
77702      sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
77703    }
77704  }else
77705
77706#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
77707# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
77708#endif
77709
77710#ifndef SQLITE_OMIT_INTEGRITY_CHECK
77711  /* Pragma "quick_check" is an experimental reduced version of
77712  ** integrity_check designed to detect most database corruption
77713  ** without most of the overhead of a full integrity-check.
77714  */
77715  if( sqlite3StrICmp(zLeft, "integrity_check")==0
77716   || sqlite3StrICmp(zLeft, "quick_check")==0
77717  ){
77718    int i, j, addr, mxErr;
77719
77720    /* Code that appears at the end of the integrity check.  If no error
77721    ** messages have been generated, output OK.  Otherwise output the
77722    ** error message
77723    */
77724    static const VdbeOpList endCode[] = {
77725      { OP_AddImm,      1, 0,        0},    /* 0 */
77726      { OP_IfNeg,       1, 0,        0},    /* 1 */
77727      { OP_String8,     0, 3,        0},    /* 2 */
77728      { OP_ResultRow,   3, 1,        0},
77729    };
77730
77731    int isQuick = (zLeft[0]=='q');
77732
77733    /* Initialize the VDBE program */
77734    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77735    pParse->nMem = 6;
77736    sqlite3VdbeSetNumCols(v, 1);
77737    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
77738
77739    /* Set the maximum error count */
77740    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
77741    if( zRight ){
77742      mxErr = atoi(zRight);
77743      if( mxErr<=0 ){
77744        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
77745      }
77746    }
77747    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
77748
77749    /* Do an integrity check on each database file */
77750    for(i=0; i<db->nDb; i++){
77751      HashElem *x;
77752      Hash *pTbls;
77753      int cnt = 0;
77754
77755      if( OMIT_TEMPDB && i==1 ) continue;
77756
77757      sqlite3CodeVerifySchema(pParse, i);
77758      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
77759      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
77760      sqlite3VdbeJumpHere(v, addr);
77761
77762      /* Do an integrity check of the B-Tree
77763      **
77764      ** Begin by filling registers 2, 3, ... with the root pages numbers
77765      ** for all tables and indices in the database.
77766      */
77767      pTbls = &db->aDb[i].pSchema->tblHash;
77768      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
77769        Table *pTab = sqliteHashData(x);
77770        Index *pIdx;
77771        sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
77772        cnt++;
77773        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
77774          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
77775          cnt++;
77776        }
77777      }
77778
77779      /* Make sure sufficient number of registers have been allocated */
77780      if( pParse->nMem < cnt+4 ){
77781        pParse->nMem = cnt+4;
77782      }
77783
77784      /* Do the b-tree integrity checks */
77785      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
77786      sqlite3VdbeChangeP5(v, (u8)i);
77787      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
77788      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
77789         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
77790         P4_DYNAMIC);
77791      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
77792      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
77793      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
77794      sqlite3VdbeJumpHere(v, addr);
77795
77796      /* Make sure all the indices are constructed correctly.
77797      */
77798      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
77799        Table *pTab = sqliteHashData(x);
77800        Index *pIdx;
77801        int loopTop;
77802
77803        if( pTab->pIndex==0 ) continue;
77804        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
77805        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
77806        sqlite3VdbeJumpHere(v, addr);
77807        sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
77808        sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
77809        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
77810        sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
77811        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
77812          int jmp2;
77813          int r1;
77814          static const VdbeOpList idxErr[] = {
77815            { OP_AddImm,      1, -1,  0},
77816            { OP_String8,     0,  3,  0},    /* 1 */
77817            { OP_Rowid,       1,  4,  0},
77818            { OP_String8,     0,  5,  0},    /* 3 */
77819            { OP_String8,     0,  6,  0},    /* 4 */
77820            { OP_Concat,      4,  3,  3},
77821            { OP_Concat,      5,  3,  3},
77822            { OP_Concat,      6,  3,  3},
77823            { OP_ResultRow,   3,  1,  0},
77824            { OP_IfPos,       1,  0,  0},    /* 9 */
77825            { OP_Halt,        0,  0,  0},
77826          };
77827          r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
77828          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
77829          addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
77830          sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
77831          sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
77832          sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
77833          sqlite3VdbeJumpHere(v, addr+9);
77834          sqlite3VdbeJumpHere(v, jmp2);
77835        }
77836        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
77837        sqlite3VdbeJumpHere(v, loopTop);
77838        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
77839          static const VdbeOpList cntIdx[] = {
77840             { OP_Integer,      0,  3,  0},
77841             { OP_Rewind,       0,  0,  0},  /* 1 */
77842             { OP_AddImm,       3,  1,  0},
77843             { OP_Next,         0,  0,  0},  /* 3 */
77844             { OP_Eq,           2,  0,  3},  /* 4 */
77845             { OP_AddImm,       1, -1,  0},
77846             { OP_String8,      0,  2,  0},  /* 6 */
77847             { OP_String8,      0,  3,  0},  /* 7 */
77848             { OP_Concat,       3,  2,  2},
77849             { OP_ResultRow,    2,  1,  0},
77850          };
77851          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
77852          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
77853          sqlite3VdbeJumpHere(v, addr);
77854          addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
77855          sqlite3VdbeChangeP1(v, addr+1, j+2);
77856          sqlite3VdbeChangeP2(v, addr+1, addr+4);
77857          sqlite3VdbeChangeP1(v, addr+3, j+2);
77858          sqlite3VdbeChangeP2(v, addr+3, addr+2);
77859          sqlite3VdbeJumpHere(v, addr+4);
77860          sqlite3VdbeChangeP4(v, addr+6,
77861                     "wrong # of entries in index ", P4_STATIC);
77862          sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
77863        }
77864      }
77865    }
77866    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
77867    sqlite3VdbeChangeP2(v, addr, -mxErr);
77868    sqlite3VdbeJumpHere(v, addr+1);
77869    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
77870  }else
77871#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
77872
77873#ifndef SQLITE_OMIT_UTF16
77874  /*
77875  **   PRAGMA encoding
77876  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
77877  **
77878  ** In its first form, this pragma returns the encoding of the main
77879  ** database. If the database is not initialized, it is initialized now.
77880  **
77881  ** The second form of this pragma is a no-op if the main database file
77882  ** has not already been initialized. In this case it sets the default
77883  ** encoding that will be used for the main database file if a new file
77884  ** is created. If an existing main database file is opened, then the
77885  ** default text encoding for the existing database is used.
77886  **
77887  ** In all cases new databases created using the ATTACH command are
77888  ** created to use the same default text encoding as the main database. If
77889  ** the main database has not been initialized and/or created when ATTACH
77890  ** is executed, this is done before the ATTACH operation.
77891  **
77892  ** In the second form this pragma sets the text encoding to be used in
77893  ** new database files created using this database handle. It is only
77894  ** useful if invoked immediately after the main database i
77895  */
77896  if( sqlite3StrICmp(zLeft, "encoding")==0 ){
77897    static const struct EncName {
77898      char *zName;
77899      u8 enc;
77900    } encnames[] = {
77901      { "UTF8",     SQLITE_UTF8        },
77902      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
77903      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
77904      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
77905      { "UTF16le",  SQLITE_UTF16LE     },
77906      { "UTF16be",  SQLITE_UTF16BE     },
77907      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
77908      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
77909      { 0, 0 }
77910    };
77911    const struct EncName *pEnc;
77912    if( !zRight ){    /* "PRAGMA encoding" */
77913      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
77914      sqlite3VdbeSetNumCols(v, 1);
77915      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
77916      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
77917      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
77918      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
77919      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
77920      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
77921      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
77922    }else{                        /* "PRAGMA encoding = XXX" */
77923      /* Only change the value of sqlite.enc if the database handle is not
77924      ** initialized. If the main database exists, the new sqlite.enc value
77925      ** will be overwritten when the schema is next loaded. If it does not
77926      ** already exists, it will be created to use the new encoding value.
77927      */
77928      if(
77929        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
77930        DbHasProperty(db, 0, DB_Empty)
77931      ){
77932        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
77933          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
77934            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
77935            break;
77936          }
77937        }
77938        if( !pEnc->zName ){
77939          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
77940        }
77941      }
77942    }
77943  }else
77944#endif /* SQLITE_OMIT_UTF16 */
77945
77946#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
77947  /*
77948  **   PRAGMA [database.]schema_version
77949  **   PRAGMA [database.]schema_version = <integer>
77950  **
77951  **   PRAGMA [database.]user_version
77952  **   PRAGMA [database.]user_version = <integer>
77953  **
77954  ** The pragma's schema_version and user_version are used to set or get
77955  ** the value of the schema-version and user-version, respectively. Both
77956  ** the schema-version and the user-version are 32-bit signed integers
77957  ** stored in the database header.
77958  **
77959  ** The schema-cookie is usually only manipulated internally by SQLite. It
77960  ** is incremented by SQLite whenever the database schema is modified (by
77961  ** creating or dropping a table or index). The schema version is used by
77962  ** SQLite each time a query is executed to ensure that the internal cache
77963  ** of the schema used when compiling the SQL query matches the schema of
77964  ** the database against which the compiled query is actually executed.
77965  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
77966  ** the schema-version is potentially dangerous and may lead to program
77967  ** crashes or database corruption. Use with caution!
77968  **
77969  ** The user-version is not used internally by SQLite. It may be used by
77970  ** applications for any purpose.
77971  */
77972  if( sqlite3StrICmp(zLeft, "schema_version")==0
77973   || sqlite3StrICmp(zLeft, "user_version")==0
77974   || sqlite3StrICmp(zLeft, "freelist_count")==0
77975  ){
77976    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
77977    sqlite3VdbeUsesBtree(v, iDb);
77978    switch( zLeft[0] ){
77979      case 'f': case 'F':
77980        iCookie = BTREE_FREE_PAGE_COUNT;
77981        break;
77982      case 's': case 'S':
77983        iCookie = BTREE_SCHEMA_VERSION;
77984        break;
77985      default:
77986        iCookie = BTREE_USER_VERSION;
77987        break;
77988    }
77989
77990    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
77991      /* Write the specified cookie value */
77992      static const VdbeOpList setCookie[] = {
77993        { OP_Transaction,    0,  1,  0},    /* 0 */
77994        { OP_Integer,        0,  1,  0},    /* 1 */
77995        { OP_SetCookie,      0,  0,  1},    /* 2 */
77996      };
77997      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
77998      sqlite3VdbeChangeP1(v, addr, iDb);
77999      sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
78000      sqlite3VdbeChangeP1(v, addr+2, iDb);
78001      sqlite3VdbeChangeP2(v, addr+2, iCookie);
78002    }else{
78003      /* Read the specified cookie value */
78004      static const VdbeOpList readCookie[] = {
78005        { OP_Transaction,     0,  0,  0},    /* 0 */
78006        { OP_ReadCookie,      0,  1,  0},    /* 1 */
78007        { OP_ResultRow,       1,  1,  0}
78008      };
78009      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
78010      sqlite3VdbeChangeP1(v, addr, iDb);
78011      sqlite3VdbeChangeP1(v, addr+1, iDb);
78012      sqlite3VdbeChangeP3(v, addr+1, iCookie);
78013      sqlite3VdbeSetNumCols(v, 1);
78014      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
78015    }
78016  }else
78017#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
78018
78019#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
78020  /*
78021  ** Report the current state of file logs for all databases
78022  */
78023  if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
78024    static const char *const azLockName[] = {
78025      "unlocked", "shared", "reserved", "pending", "exclusive"
78026    };
78027    int i;
78028    sqlite3VdbeSetNumCols(v, 2);
78029    pParse->nMem = 2;
78030    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
78031    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
78032    for(i=0; i<db->nDb; i++){
78033      Btree *pBt;
78034      Pager *pPager;
78035      const char *zState = "unknown";
78036      int j;
78037      if( db->aDb[i].zName==0 ) continue;
78038      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
78039      pBt = db->aDb[i].pBt;
78040      if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
78041        zState = "closed";
78042      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
78043                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
78044         zState = azLockName[j];
78045      }
78046      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
78047      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
78048    }
78049
78050  }else
78051#endif
78052
78053#if SQLITE_HAS_CODEC
78054  if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
78055    sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
78056  }else
78057  if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
78058    sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
78059  }else
78060  if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
78061                 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
78062    int i, h1, h2;
78063    char zKey[40];
78064    for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
78065      h1 += 9*(1&(h1>>6));
78066      h2 += 9*(1&(h2>>6));
78067      zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
78068    }
78069    if( (zLeft[3] & 0xf)==0xb ){
78070      sqlite3_key(db, zKey, i/2);
78071    }else{
78072      sqlite3_rekey(db, zKey, i/2);
78073    }
78074  }else
78075#endif
78076#if SQLITE_HAS_CODEC || defined(SQLITE_ENABLE_CEROD)
78077  if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
78078#if SQLITE_HAS_CODEC
78079    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
78080      extern void sqlite3_activate_see(const char*);
78081      sqlite3_activate_see(&zRight[4]);
78082    }
78083#endif
78084#ifdef SQLITE_ENABLE_CEROD
78085    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
78086      extern void sqlite3_activate_cerod(const char*);
78087      sqlite3_activate_cerod(&zRight[6]);
78088    }
78089#endif
78090  }else
78091#endif
78092
78093
78094  {/* Empty ELSE clause */}
78095
78096  /* Code an OP_Expire at the end of each PRAGMA program to cause
78097  ** the VDBE implementing the pragma to expire. Most (all?) pragmas
78098  ** are only valid for a single execution.
78099  */
78100  sqlite3VdbeAddOp2(v, OP_Expire, 1, 0);
78101
78102  /*
78103  ** Reset the safety level, in case the fullfsync flag or synchronous
78104  ** setting changed.
78105  */
78106#ifndef SQLITE_OMIT_PAGER_PRAGMAS
78107  if( db->autoCommit ){
78108    sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
78109               (db->flags&SQLITE_FullFSync)!=0);
78110  }
78111#endif
78112pragma_out:
78113  sqlite3DbFree(db, zLeft);
78114  sqlite3DbFree(db, zRight);
78115}
78116
78117#endif /* SQLITE_OMIT_PRAGMA */
78118
78119/************** End of pragma.c **********************************************/
78120/************** Begin file prepare.c *****************************************/
78121/*
78122** 2005 May 25
78123**
78124** The author disclaims copyright to this source code.  In place of
78125** a legal notice, here is a blessing:
78126**
78127**    May you do good and not evil.
78128**    May you find forgiveness for yourself and forgive others.
78129**    May you share freely, never taking more than you give.
78130**
78131*************************************************************************
78132** This file contains the implementation of the sqlite3_prepare()
78133** interface, and routines that contribute to loading the database schema
78134** from disk.
78135*/
78136
78137/*
78138** Fill the InitData structure with an error message that indicates
78139** that the database is corrupt.
78140*/
78141static void corruptSchema(
78142  InitData *pData,     /* Initialization context */
78143  const char *zObj,    /* Object being parsed at the point of error */
78144  const char *zExtra   /* Error information */
78145){
78146  sqlite3 *db = pData->db;
78147  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
78148    if( zObj==0 ) zObj = "?";
78149    sqlite3SetString(pData->pzErrMsg, db,
78150      "malformed database schema (%s)", zObj);
78151    if( zExtra ){
78152      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
78153                                 "%s - %s", *pData->pzErrMsg, zExtra);
78154    }
78155  }
78156  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
78157}
78158
78159/*
78160** This is the callback routine for the code that initializes the
78161** database.  See sqlite3Init() below for additional information.
78162** This routine is also called from the OP_ParseSchema opcode of the VDBE.
78163**
78164** Each callback contains the following information:
78165**
78166**     argv[0] = name of thing being created
78167**     argv[1] = root page number for table or index. 0 for trigger or view.
78168**     argv[2] = SQL text for the CREATE statement.
78169**
78170*/
78171SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
78172  InitData *pData = (InitData*)pInit;
78173  sqlite3 *db = pData->db;
78174  int iDb = pData->iDb;
78175
78176  assert( argc==3 );
78177  UNUSED_PARAMETER2(NotUsed, argc);
78178  assert( sqlite3_mutex_held(db->mutex) );
78179  DbClearProperty(db, iDb, DB_Empty);
78180  if( db->mallocFailed ){
78181    corruptSchema(pData, argv[0], 0);
78182    return 1;
78183  }
78184
78185  assert( iDb>=0 && iDb<db->nDb );
78186  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
78187  if( argv[1]==0 ){
78188    corruptSchema(pData, argv[0], 0);
78189  }else if( argv[2] && argv[2][0] ){
78190    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
78191    ** But because db->init.busy is set to 1, no VDBE code is generated
78192    ** or executed.  All the parser does is build the internal data
78193    ** structures that describe the table, index, or view.
78194    */
78195    char *zErr;
78196    int rc;
78197    assert( db->init.busy );
78198    db->init.iDb = iDb;
78199    db->init.newTnum = atoi(argv[1]);
78200    db->init.orphanTrigger = 0;
78201    rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
78202    db->init.iDb = 0;
78203    assert( rc!=SQLITE_OK || zErr==0 );
78204    if( SQLITE_OK!=rc ){
78205      if( db->init.orphanTrigger ){
78206        assert( iDb==1 );
78207      }else{
78208        pData->rc = rc;
78209        if( rc==SQLITE_NOMEM ){
78210          db->mallocFailed = 1;
78211        }else if( rc!=SQLITE_INTERRUPT && rc!=SQLITE_LOCKED ){
78212          corruptSchema(pData, argv[0], zErr);
78213        }
78214      }
78215      sqlite3DbFree(db, zErr);
78216    }
78217  }else if( argv[0]==0 ){
78218    corruptSchema(pData, 0, 0);
78219  }else{
78220    /* If the SQL column is blank it means this is an index that
78221    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
78222    ** constraint for a CREATE TABLE.  The index should have already
78223    ** been created when we processed the CREATE TABLE.  All we have
78224    ** to do here is record the root page number for that index.
78225    */
78226    Index *pIndex;
78227    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
78228    if( pIndex==0 ){
78229      /* This can occur if there exists an index on a TEMP table which
78230      ** has the same name as another index on a permanent index.  Since
78231      ** the permanent table is hidden by the TEMP table, we can also
78232      ** safely ignore the index on the permanent table.
78233      */
78234      /* Do Nothing */;
78235    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
78236      corruptSchema(pData, argv[0], "invalid rootpage");
78237    }
78238  }
78239  return 0;
78240}
78241
78242/*
78243** Attempt to read the database schema and initialize internal
78244** data structures for a single database file.  The index of the
78245** database file is given by iDb.  iDb==0 is used for the main
78246** database.  iDb==1 should never be used.  iDb>=2 is used for
78247** auxiliary databases.  Return one of the SQLITE_ error codes to
78248** indicate success or failure.
78249*/
78250static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
78251  int rc;
78252  int i;
78253  int size;
78254  Table *pTab;
78255  Db *pDb;
78256  char const *azArg[4];
78257  int meta[5];
78258  InitData initData;
78259  char const *zMasterSchema;
78260  char const *zMasterName = SCHEMA_TABLE(iDb);
78261  int openedTransaction = 0;
78262
78263  /*
78264  ** The master database table has a structure like this
78265  */
78266  static const char master_schema[] =
78267     "CREATE TABLE sqlite_master(\n"
78268     "  type text,\n"
78269     "  name text,\n"
78270     "  tbl_name text,\n"
78271     "  rootpage integer,\n"
78272     "  sql text\n"
78273     ")"
78274  ;
78275#ifndef SQLITE_OMIT_TEMPDB
78276  static const char temp_master_schema[] =
78277     "CREATE TEMP TABLE sqlite_temp_master(\n"
78278     "  type text,\n"
78279     "  name text,\n"
78280     "  tbl_name text,\n"
78281     "  rootpage integer,\n"
78282     "  sql text\n"
78283     ")"
78284  ;
78285#else
78286  #define temp_master_schema 0
78287#endif
78288
78289  assert( iDb>=0 && iDb<db->nDb );
78290  assert( db->aDb[iDb].pSchema );
78291  assert( sqlite3_mutex_held(db->mutex) );
78292  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
78293
78294  /* zMasterSchema and zInitScript are set to point at the master schema
78295  ** and initialisation script appropriate for the database being
78296  ** initialised. zMasterName is the name of the master table.
78297  */
78298  if( !OMIT_TEMPDB && iDb==1 ){
78299    zMasterSchema = temp_master_schema;
78300  }else{
78301    zMasterSchema = master_schema;
78302  }
78303  zMasterName = SCHEMA_TABLE(iDb);
78304
78305  /* Construct the schema tables.  */
78306  azArg[0] = zMasterName;
78307  azArg[1] = "1";
78308  azArg[2] = zMasterSchema;
78309  azArg[3] = 0;
78310  initData.db = db;
78311  initData.iDb = iDb;
78312  initData.rc = SQLITE_OK;
78313  initData.pzErrMsg = pzErrMsg;
78314  (void)sqlite3SafetyOff(db);
78315  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
78316  (void)sqlite3SafetyOn(db);
78317  if( initData.rc ){
78318    rc = initData.rc;
78319    goto error_out;
78320  }
78321  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
78322  if( ALWAYS(pTab) ){
78323    pTab->tabFlags |= TF_Readonly;
78324  }
78325
78326  /* Create a cursor to hold the database open
78327  */
78328  pDb = &db->aDb[iDb];
78329  if( pDb->pBt==0 ){
78330    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
78331      DbSetProperty(db, 1, DB_SchemaLoaded);
78332    }
78333    return SQLITE_OK;
78334  }
78335
78336  /* If there is not already a read-only (or read-write) transaction opened
78337  ** on the b-tree database, open one now. If a transaction is opened, it
78338  ** will be closed before this function returns.  */
78339  sqlite3BtreeEnter(pDb->pBt);
78340  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
78341    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
78342    if( rc!=SQLITE_OK ){
78343      sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
78344      goto initone_error_out;
78345    }
78346    openedTransaction = 1;
78347  }
78348
78349  /* Get the database meta information.
78350  **
78351  ** Meta values are as follows:
78352  **    meta[0]   Schema cookie.  Changes with each schema change.
78353  **    meta[1]   File format of schema layer.
78354  **    meta[2]   Size of the page cache.
78355  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
78356  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
78357  **    meta[5]   User version
78358  **    meta[6]   Incremental vacuum mode
78359  **    meta[7]   unused
78360  **    meta[8]   unused
78361  **    meta[9]   unused
78362  **
78363  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
78364  ** the possible values of meta[4].
78365  */
78366  for(i=0; i<ArraySize(meta); i++){
78367    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
78368  }
78369  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
78370
78371  /* If opening a non-empty database, check the text encoding. For the
78372  ** main database, set sqlite3.enc to the encoding of the main database.
78373  ** For an attached db, it is an error if the encoding is not the same
78374  ** as sqlite3.enc.
78375  */
78376  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
78377    if( iDb==0 ){
78378      u8 encoding;
78379      /* If opening the main database, set ENC(db). */
78380      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
78381      if( encoding==0 ) encoding = SQLITE_UTF8;
78382      ENC(db) = encoding;
78383      db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
78384    }else{
78385      /* If opening an attached database, the encoding much match ENC(db) */
78386      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
78387        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
78388            " text encoding as main database");
78389        rc = SQLITE_ERROR;
78390        goto initone_error_out;
78391      }
78392    }
78393  }else{
78394    DbSetProperty(db, iDb, DB_Empty);
78395  }
78396  pDb->pSchema->enc = ENC(db);
78397
78398  if( pDb->pSchema->cache_size==0 ){
78399    size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
78400    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
78401    if( size<0 ) size = -size;
78402    pDb->pSchema->cache_size = size;
78403    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
78404  }
78405
78406  /*
78407  ** file_format==1    Version 3.0.0.
78408  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
78409  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
78410  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
78411  */
78412  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
78413  if( pDb->pSchema->file_format==0 ){
78414    pDb->pSchema->file_format = 1;
78415  }
78416  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
78417    sqlite3SetString(pzErrMsg, db, "unsupported file format");
78418    rc = SQLITE_ERROR;
78419    goto initone_error_out;
78420  }
78421
78422  /* Ticket #2804:  When we open a database in the newer file format,
78423  ** clear the legacy_file_format pragma flag so that a VACUUM will
78424  ** not downgrade the database and thus invalidate any descending
78425  ** indices that the user might have created.
78426  */
78427  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
78428    db->flags &= ~SQLITE_LegacyFileFmt;
78429  }
78430
78431  /* Read the schema information out of the schema tables
78432  */
78433  assert( db->init.busy );
78434  {
78435    char *zSql;
78436    zSql = sqlite3MPrintf(db,
78437        "SELECT name, rootpage, sql FROM '%q'.%s",
78438        db->aDb[iDb].zName, zMasterName);
78439    (void)sqlite3SafetyOff(db);
78440#ifndef SQLITE_OMIT_AUTHORIZATION
78441    {
78442      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
78443      xAuth = db->xAuth;
78444      db->xAuth = 0;
78445#endif
78446      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
78447#ifndef SQLITE_OMIT_AUTHORIZATION
78448      db->xAuth = xAuth;
78449    }
78450#endif
78451    if( rc==SQLITE_OK ) rc = initData.rc;
78452    (void)sqlite3SafetyOn(db);
78453    sqlite3DbFree(db, zSql);
78454#ifndef SQLITE_OMIT_ANALYZE
78455    if( rc==SQLITE_OK ){
78456      sqlite3AnalysisLoad(db, iDb);
78457    }
78458#endif
78459  }
78460  if( db->mallocFailed ){
78461    rc = SQLITE_NOMEM;
78462    sqlite3ResetInternalSchema(db, 0);
78463  }
78464  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
78465    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
78466    ** the schema loaded, even if errors occurred. In this situation the
78467    ** current sqlite3_prepare() operation will fail, but the following one
78468    ** will attempt to compile the supplied statement against whatever subset
78469    ** of the schema was loaded before the error occurred. The primary
78470    ** purpose of this is to allow access to the sqlite_master table
78471    ** even when its contents have been corrupted.
78472    */
78473    DbSetProperty(db, iDb, DB_SchemaLoaded);
78474    rc = SQLITE_OK;
78475  }
78476
78477  /* Jump here for an error that occurs after successfully allocating
78478  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
78479  ** before that point, jump to error_out.
78480  */
78481initone_error_out:
78482  if( openedTransaction ){
78483    sqlite3BtreeCommit(pDb->pBt);
78484  }
78485  sqlite3BtreeLeave(pDb->pBt);
78486
78487error_out:
78488  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
78489    db->mallocFailed = 1;
78490  }
78491  return rc;
78492}
78493
78494/*
78495** Initialize all database files - the main database file, the file
78496** used to store temporary tables, and any additional database files
78497** created using ATTACH statements.  Return a success code.  If an
78498** error occurs, write an error message into *pzErrMsg.
78499**
78500** After a database is initialized, the DB_SchemaLoaded bit is set
78501** bit is set in the flags field of the Db structure. If the database
78502** file was of zero-length, then the DB_Empty flag is also set.
78503*/
78504SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
78505  int i, rc;
78506  int commit_internal = !(db->flags&SQLITE_InternChanges);
78507
78508  assert( sqlite3_mutex_held(db->mutex) );
78509  rc = SQLITE_OK;
78510  db->init.busy = 1;
78511  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
78512    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
78513    rc = sqlite3InitOne(db, i, pzErrMsg);
78514    if( rc ){
78515      sqlite3ResetInternalSchema(db, i);
78516    }
78517  }
78518
78519  /* Once all the other databases have been initialised, load the schema
78520  ** for the TEMP database. This is loaded last, as the TEMP database
78521  ** schema may contain references to objects in other databases.
78522  */
78523#ifndef SQLITE_OMIT_TEMPDB
78524  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
78525                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
78526    rc = sqlite3InitOne(db, 1, pzErrMsg);
78527    if( rc ){
78528      sqlite3ResetInternalSchema(db, 1);
78529    }
78530  }
78531#endif
78532
78533  db->init.busy = 0;
78534  if( rc==SQLITE_OK && commit_internal ){
78535    sqlite3CommitInternalChanges(db);
78536  }
78537
78538  return rc;
78539}
78540
78541/*
78542** This routine is a no-op if the database schema is already initialised.
78543** Otherwise, the schema is loaded. An error code is returned.
78544*/
78545SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
78546  int rc = SQLITE_OK;
78547  sqlite3 *db = pParse->db;
78548  assert( sqlite3_mutex_held(db->mutex) );
78549  if( !db->init.busy ){
78550    rc = sqlite3Init(db, &pParse->zErrMsg);
78551  }
78552  if( rc!=SQLITE_OK ){
78553    pParse->rc = rc;
78554    pParse->nErr++;
78555  }
78556  return rc;
78557}
78558
78559
78560/*
78561** Check schema cookies in all databases.  If any cookie is out
78562** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
78563** make no changes to pParse->rc.
78564*/
78565static void schemaIsValid(Parse *pParse){
78566  sqlite3 *db = pParse->db;
78567  int iDb;
78568  int rc;
78569  int cookie;
78570
78571  assert( pParse->checkSchema );
78572  assert( sqlite3_mutex_held(db->mutex) );
78573  for(iDb=0; iDb<db->nDb; iDb++){
78574    int openedTransaction = 0;         /* True if a transaction is opened */
78575    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
78576    if( pBt==0 ) continue;
78577
78578    /* If there is not already a read-only (or read-write) transaction opened
78579    ** on the b-tree database, open one now. If a transaction is opened, it
78580    ** will be closed immediately after reading the meta-value. */
78581    if( !sqlite3BtreeIsInReadTrans(pBt) ){
78582      rc = sqlite3BtreeBeginTrans(pBt, 0);
78583      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
78584        db->mallocFailed = 1;
78585      }
78586      if( rc!=SQLITE_OK ) return;
78587      openedTransaction = 1;
78588    }
78589
78590    /* Read the schema cookie from the database. If it does not match the
78591    ** value stored as part of the in-memory schema representation,
78592    ** set Parse.rc to SQLITE_SCHEMA. */
78593    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
78594    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
78595      pParse->rc = SQLITE_SCHEMA;
78596    }
78597
78598    /* Close the transaction, if one was opened. */
78599    if( openedTransaction ){
78600      sqlite3BtreeCommit(pBt);
78601    }
78602  }
78603}
78604
78605/*
78606** Convert a schema pointer into the iDb index that indicates
78607** which database file in db->aDb[] the schema refers to.
78608**
78609** If the same database is attached more than once, the first
78610** attached database is returned.
78611*/
78612SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
78613  int i = -1000000;
78614
78615  /* If pSchema is NULL, then return -1000000. This happens when code in
78616  ** expr.c is trying to resolve a reference to a transient table (i.e. one
78617  ** created by a sub-select). In this case the return value of this
78618  ** function should never be used.
78619  **
78620  ** We return -1000000 instead of the more usual -1 simply because using
78621  ** -1000000 as the incorrect index into db->aDb[] is much
78622  ** more likely to cause a segfault than -1 (of course there are assert()
78623  ** statements too, but it never hurts to play the odds).
78624  */
78625  assert( sqlite3_mutex_held(db->mutex) );
78626  if( pSchema ){
78627    for(i=0; ALWAYS(i<db->nDb); i++){
78628      if( db->aDb[i].pSchema==pSchema ){
78629        break;
78630      }
78631    }
78632    assert( i>=0 && i<db->nDb );
78633  }
78634  return i;
78635}
78636
78637/*
78638** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
78639*/
78640static int sqlite3Prepare(
78641  sqlite3 *db,              /* Database handle. */
78642  const char *zSql,         /* UTF-8 encoded SQL statement. */
78643  int nBytes,               /* Length of zSql in bytes. */
78644  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
78645  Vdbe *pReprepare,         /* VM being reprepared */
78646  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78647  const char **pzTail       /* OUT: End of parsed string */
78648){
78649  Parse *pParse;            /* Parsing context */
78650  char *zErrMsg = 0;        /* Error message */
78651  int rc = SQLITE_OK;       /* Result code */
78652  int i;                    /* Loop counter */
78653
78654  /* Allocate the parsing context */
78655  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
78656  if( pParse==0 ){
78657    rc = SQLITE_NOMEM;
78658    goto end_prepare;
78659  }
78660  pParse->pReprepare = pReprepare;
78661
78662  if( sqlite3SafetyOn(db) ){
78663    rc = SQLITE_MISUSE;
78664    goto end_prepare;
78665  }
78666  assert( ppStmt && *ppStmt==0 );
78667  assert( !db->mallocFailed );
78668  assert( sqlite3_mutex_held(db->mutex) );
78669
78670  /* Check to verify that it is possible to get a read lock on all
78671  ** database schemas.  The inability to get a read lock indicates that
78672  ** some other database connection is holding a write-lock, which in
78673  ** turn means that the other connection has made uncommitted changes
78674  ** to the schema.
78675  **
78676  ** Were we to proceed and prepare the statement against the uncommitted
78677  ** schema changes and if those schema changes are subsequently rolled
78678  ** back and different changes are made in their place, then when this
78679  ** prepared statement goes to run the schema cookie would fail to detect
78680  ** the schema change.  Disaster would follow.
78681  **
78682  ** This thread is currently holding mutexes on all Btrees (because
78683  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
78684  ** is not possible for another thread to start a new schema change
78685  ** while this routine is running.  Hence, we do not need to hold
78686  ** locks on the schema, we just need to make sure nobody else is
78687  ** holding them.
78688  **
78689  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
78690  ** but it does *not* override schema lock detection, so this all still
78691  ** works even if READ_UNCOMMITTED is set.
78692  */
78693  for(i=0; i<db->nDb; i++) {
78694    Btree *pBt = db->aDb[i].pBt;
78695    if( pBt ){
78696      assert( sqlite3BtreeHoldsMutex(pBt) );
78697      rc = sqlite3BtreeSchemaLocked(pBt);
78698      if( rc ){
78699        const char *zDb = db->aDb[i].zName;
78700        sqlite3Error(db, rc, "database schema is locked: %s", zDb);
78701        (void)sqlite3SafetyOff(db);
78702        testcase( db->flags & SQLITE_ReadUncommitted );
78703        goto end_prepare;
78704      }
78705    }
78706  }
78707
78708  sqlite3VtabUnlockList(db);
78709
78710  pParse->db = db;
78711  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
78712    char *zSqlCopy;
78713    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
78714    testcase( nBytes==mxLen );
78715    testcase( nBytes==mxLen+1 );
78716    if( nBytes>mxLen ){
78717      sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
78718      (void)sqlite3SafetyOff(db);
78719      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
78720      goto end_prepare;
78721    }
78722    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
78723    if( zSqlCopy ){
78724      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
78725      sqlite3DbFree(db, zSqlCopy);
78726      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
78727    }else{
78728      pParse->zTail = &zSql[nBytes];
78729    }
78730  }else{
78731    sqlite3RunParser(pParse, zSql, &zErrMsg);
78732  }
78733
78734  if( db->mallocFailed ){
78735    pParse->rc = SQLITE_NOMEM;
78736  }
78737  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
78738  if( pParse->checkSchema ){
78739    schemaIsValid(pParse);
78740  }
78741  if( pParse->rc==SQLITE_SCHEMA ){
78742    sqlite3ResetInternalSchema(db, 0);
78743  }
78744  if( db->mallocFailed ){
78745    pParse->rc = SQLITE_NOMEM;
78746  }
78747  if( pzTail ){
78748    *pzTail = pParse->zTail;
78749  }
78750  rc = pParse->rc;
78751
78752#ifndef SQLITE_OMIT_EXPLAIN
78753  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
78754    static const char * const azColName[] = {
78755       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
78756       "order", "from", "detail"
78757    };
78758    int iFirst, mx;
78759    if( pParse->explain==2 ){
78760      sqlite3VdbeSetNumCols(pParse->pVdbe, 3);
78761      iFirst = 8;
78762      mx = 11;
78763    }else{
78764      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
78765      iFirst = 0;
78766      mx = 8;
78767    }
78768    for(i=iFirst; i<mx; i++){
78769      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
78770                            azColName[i], SQLITE_STATIC);
78771    }
78772  }
78773#endif
78774
78775  if( sqlite3SafetyOff(db) ){
78776    rc = SQLITE_MISUSE;
78777  }
78778
78779  assert( db->init.busy==0 || saveSqlFlag==0 );
78780  if( db->init.busy==0 ){
78781    Vdbe *pVdbe = pParse->pVdbe;
78782    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
78783  }
78784  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
78785    sqlite3VdbeFinalize(pParse->pVdbe);
78786    assert(!(*ppStmt));
78787  }else{
78788    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
78789  }
78790
78791  if( zErrMsg ){
78792    sqlite3Error(db, rc, "%s", zErrMsg);
78793    sqlite3DbFree(db, zErrMsg);
78794  }else{
78795    sqlite3Error(db, rc, 0);
78796  }
78797
78798  /* Delete any TriggerPrg structures allocated while parsing this statement. */
78799  while( pParse->pTriggerPrg ){
78800    TriggerPrg *pT = pParse->pTriggerPrg;
78801    pParse->pTriggerPrg = pT->pNext;
78802    sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
78803    sqlite3DbFree(db, pT);
78804  }
78805
78806end_prepare:
78807
78808  sqlite3StackFree(db, pParse);
78809  rc = sqlite3ApiExit(db, rc);
78810  assert( (rc&db->errMask)==rc );
78811  return rc;
78812}
78813static int sqlite3LockAndPrepare(
78814  sqlite3 *db,              /* Database handle. */
78815  const char *zSql,         /* UTF-8 encoded SQL statement. */
78816  int nBytes,               /* Length of zSql in bytes. */
78817  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
78818  Vdbe *pOld,               /* VM being reprepared */
78819  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78820  const char **pzTail       /* OUT: End of parsed string */
78821){
78822  int rc;
78823  assert( ppStmt!=0 );
78824  *ppStmt = 0;
78825  if( !sqlite3SafetyCheckOk(db) ){
78826    return SQLITE_MISUSE;
78827  }
78828  sqlite3_mutex_enter(db->mutex);
78829  sqlite3BtreeEnterAll(db);
78830  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
78831  if( rc==SQLITE_SCHEMA ){
78832    sqlite3_finalize(*ppStmt);
78833    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
78834  }
78835  sqlite3BtreeLeaveAll(db);
78836  sqlite3_mutex_leave(db->mutex);
78837  return rc;
78838}
78839
78840/*
78841** Rerun the compilation of a statement after a schema change.
78842**
78843** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
78844** if the statement cannot be recompiled because another connection has
78845** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
78846** occurs, return SQLITE_SCHEMA.
78847*/
78848SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
78849  int rc;
78850  sqlite3_stmt *pNew;
78851  const char *zSql;
78852  sqlite3 *db;
78853
78854  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
78855  zSql = sqlite3_sql((sqlite3_stmt *)p);
78856  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
78857  db = sqlite3VdbeDb(p);
78858  assert( sqlite3_mutex_held(db->mutex) );
78859  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
78860  if( rc ){
78861    if( rc==SQLITE_NOMEM ){
78862      db->mallocFailed = 1;
78863    }
78864    assert( pNew==0 );
78865    return (rc==SQLITE_LOCKED) ? SQLITE_LOCKED : SQLITE_SCHEMA;
78866  }else{
78867    assert( pNew!=0 );
78868  }
78869  sqlite3VdbeSwap((Vdbe*)pNew, p);
78870  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
78871  sqlite3VdbeResetStepResult((Vdbe*)pNew);
78872  sqlite3VdbeFinalize((Vdbe*)pNew);
78873  return SQLITE_OK;
78874}
78875
78876
78877/*
78878** Two versions of the official API.  Legacy and new use.  In the legacy
78879** version, the original SQL text is not saved in the prepared statement
78880** and so if a schema change occurs, SQLITE_SCHEMA is returned by
78881** sqlite3_step().  In the new version, the original SQL text is retained
78882** and the statement is automatically recompiled if an schema change
78883** occurs.
78884*/
78885SQLITE_API int sqlite3_prepare(
78886  sqlite3 *db,              /* Database handle. */
78887  const char *zSql,         /* UTF-8 encoded SQL statement. */
78888  int nBytes,               /* Length of zSql in bytes. */
78889  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78890  const char **pzTail       /* OUT: End of parsed string */
78891){
78892  int rc;
78893  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
78894  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
78895  return rc;
78896}
78897SQLITE_API int sqlite3_prepare_v2(
78898  sqlite3 *db,              /* Database handle. */
78899  const char *zSql,         /* UTF-8 encoded SQL statement. */
78900  int nBytes,               /* Length of zSql in bytes. */
78901  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78902  const char **pzTail       /* OUT: End of parsed string */
78903){
78904  int rc;
78905  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
78906  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
78907  return rc;
78908}
78909
78910
78911#ifndef SQLITE_OMIT_UTF16
78912/*
78913** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
78914*/
78915static int sqlite3Prepare16(
78916  sqlite3 *db,              /* Database handle. */
78917  const void *zSql,         /* UTF-8 encoded SQL statement. */
78918  int nBytes,               /* Length of zSql in bytes. */
78919  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
78920  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78921  const void **pzTail       /* OUT: End of parsed string */
78922){
78923  /* This function currently works by first transforming the UTF-16
78924  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
78925  ** tricky bit is figuring out the pointer to return in *pzTail.
78926  */
78927  char *zSql8;
78928  const char *zTail8 = 0;
78929  int rc = SQLITE_OK;
78930
78931  assert( ppStmt );
78932  *ppStmt = 0;
78933  if( !sqlite3SafetyCheckOk(db) ){
78934    return SQLITE_MISUSE;
78935  }
78936  sqlite3_mutex_enter(db->mutex);
78937  zSql8 = sqlite3Utf16to8(db, zSql, nBytes);
78938  if( zSql8 ){
78939    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
78940  }
78941
78942  if( zTail8 && pzTail ){
78943    /* If sqlite3_prepare returns a tail pointer, we calculate the
78944    ** equivalent pointer into the UTF-16 string by counting the unicode
78945    ** characters between zSql8 and zTail8, and then returning a pointer
78946    ** the same number of characters into the UTF-16 string.
78947    */
78948    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
78949    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
78950  }
78951  sqlite3DbFree(db, zSql8);
78952  rc = sqlite3ApiExit(db, rc);
78953  sqlite3_mutex_leave(db->mutex);
78954  return rc;
78955}
78956
78957/*
78958** Two versions of the official API.  Legacy and new use.  In the legacy
78959** version, the original SQL text is not saved in the prepared statement
78960** and so if a schema change occurs, SQLITE_SCHEMA is returned by
78961** sqlite3_step().  In the new version, the original SQL text is retained
78962** and the statement is automatically recompiled if an schema change
78963** occurs.
78964*/
78965SQLITE_API int sqlite3_prepare16(
78966  sqlite3 *db,              /* Database handle. */
78967  const void *zSql,         /* UTF-8 encoded SQL statement. */
78968  int nBytes,               /* Length of zSql in bytes. */
78969  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78970  const void **pzTail       /* OUT: End of parsed string */
78971){
78972  int rc;
78973  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
78974  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
78975  return rc;
78976}
78977SQLITE_API int sqlite3_prepare16_v2(
78978  sqlite3 *db,              /* Database handle. */
78979  const void *zSql,         /* UTF-8 encoded SQL statement. */
78980  int nBytes,               /* Length of zSql in bytes. */
78981  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
78982  const void **pzTail       /* OUT: End of parsed string */
78983){
78984  int rc;
78985  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
78986  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
78987  return rc;
78988}
78989
78990#endif /* SQLITE_OMIT_UTF16 */
78991
78992/************** End of prepare.c *********************************************/
78993/************** Begin file select.c ******************************************/
78994/*
78995** 2001 September 15
78996**
78997** The author disclaims copyright to this source code.  In place of
78998** a legal notice, here is a blessing:
78999**
79000**    May you do good and not evil.
79001**    May you find forgiveness for yourself and forgive others.
79002**    May you share freely, never taking more than you give.
79003**
79004*************************************************************************
79005** This file contains C code routines that are called by the parser
79006** to handle SELECT statements in SQLite.
79007*/
79008
79009
79010/*
79011** Delete all the content of a Select structure but do not deallocate
79012** the select structure itself.
79013*/
79014static void clearSelect(sqlite3 *db, Select *p){
79015  sqlite3ExprListDelete(db, p->pEList);
79016  sqlite3SrcListDelete(db, p->pSrc);
79017  sqlite3ExprDelete(db, p->pWhere);
79018  sqlite3ExprListDelete(db, p->pGroupBy);
79019  sqlite3ExprDelete(db, p->pHaving);
79020  sqlite3ExprListDelete(db, p->pOrderBy);
79021  sqlite3SelectDelete(db, p->pPrior);
79022  sqlite3ExprDelete(db, p->pLimit);
79023  sqlite3ExprDelete(db, p->pOffset);
79024}
79025
79026/*
79027** Initialize a SelectDest structure.
79028*/
79029SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
79030  pDest->eDest = (u8)eDest;
79031  pDest->iParm = iParm;
79032  pDest->affinity = 0;
79033  pDest->iMem = 0;
79034  pDest->nMem = 0;
79035}
79036
79037
79038/*
79039** Allocate a new Select structure and return a pointer to that
79040** structure.
79041*/
79042SQLITE_PRIVATE Select *sqlite3SelectNew(
79043  Parse *pParse,        /* Parsing context */
79044  ExprList *pEList,     /* which columns to include in the result */
79045  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
79046  Expr *pWhere,         /* the WHERE clause */
79047  ExprList *pGroupBy,   /* the GROUP BY clause */
79048  Expr *pHaving,        /* the HAVING clause */
79049  ExprList *pOrderBy,   /* the ORDER BY clause */
79050  int isDistinct,       /* true if the DISTINCT keyword is present */
79051  Expr *pLimit,         /* LIMIT value.  NULL means not used */
79052  Expr *pOffset         /* OFFSET value.  NULL means no offset */
79053){
79054  Select *pNew;
79055  Select standin;
79056  sqlite3 *db = pParse->db;
79057  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
79058  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
79059  if( pNew==0 ){
79060    pNew = &standin;
79061    memset(pNew, 0, sizeof(*pNew));
79062  }
79063  if( pEList==0 ){
79064    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
79065  }
79066  pNew->pEList = pEList;
79067  pNew->pSrc = pSrc;
79068  pNew->pWhere = pWhere;
79069  pNew->pGroupBy = pGroupBy;
79070  pNew->pHaving = pHaving;
79071  pNew->pOrderBy = pOrderBy;
79072  pNew->selFlags = isDistinct ? SF_Distinct : 0;
79073  pNew->op = TK_SELECT;
79074  pNew->pLimit = pLimit;
79075  pNew->pOffset = pOffset;
79076  assert( pOffset==0 || pLimit!=0 );
79077  pNew->addrOpenEphm[0] = -1;
79078  pNew->addrOpenEphm[1] = -1;
79079  pNew->addrOpenEphm[2] = -1;
79080  if( db->mallocFailed ) {
79081    clearSelect(db, pNew);
79082    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
79083    pNew = 0;
79084  }
79085  return pNew;
79086}
79087
79088/*
79089** Delete the given Select structure and all of its substructures.
79090*/
79091SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
79092  if( p ){
79093    clearSelect(db, p);
79094    sqlite3DbFree(db, p);
79095  }
79096}
79097
79098/*
79099** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
79100** type of join.  Return an integer constant that expresses that type
79101** in terms of the following bit values:
79102**
79103**     JT_INNER
79104**     JT_CROSS
79105**     JT_OUTER
79106**     JT_NATURAL
79107**     JT_LEFT
79108**     JT_RIGHT
79109**
79110** A full outer join is the combination of JT_LEFT and JT_RIGHT.
79111**
79112** If an illegal or unsupported join type is seen, then still return
79113** a join type, but put an error in the pParse structure.
79114*/
79115SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
79116  int jointype = 0;
79117  Token *apAll[3];
79118  Token *p;
79119                             /*   0123456789 123456789 123456789 123 */
79120  static const char zKeyText[] = "naturaleftouterightfullinnercross";
79121  static const struct {
79122    u8 i;        /* Beginning of keyword text in zKeyText[] */
79123    u8 nChar;    /* Length of the keyword in characters */
79124    u8 code;     /* Join type mask */
79125  } aKeyword[] = {
79126    /* natural */ { 0,  7, JT_NATURAL                },
79127    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
79128    /* outer   */ { 10, 5, JT_OUTER                  },
79129    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
79130    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
79131    /* inner   */ { 23, 5, JT_INNER                  },
79132    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
79133  };
79134  int i, j;
79135  apAll[0] = pA;
79136  apAll[1] = pB;
79137  apAll[2] = pC;
79138  for(i=0; i<3 && apAll[i]; i++){
79139    p = apAll[i];
79140    for(j=0; j<ArraySize(aKeyword); j++){
79141      if( p->n==aKeyword[j].nChar
79142          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
79143        jointype |= aKeyword[j].code;
79144        break;
79145      }
79146    }
79147    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
79148    if( j>=ArraySize(aKeyword) ){
79149      jointype |= JT_ERROR;
79150      break;
79151    }
79152  }
79153  if(
79154     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
79155     (jointype & JT_ERROR)!=0
79156  ){
79157    const char *zSp = " ";
79158    assert( pB!=0 );
79159    if( pC==0 ){ zSp++; }
79160    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
79161       "%T %T%s%T", pA, pB, zSp, pC);
79162    jointype = JT_INNER;
79163  }else if( (jointype & JT_OUTER)!=0
79164         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
79165    sqlite3ErrorMsg(pParse,
79166      "RIGHT and FULL OUTER JOINs are not currently supported");
79167    jointype = JT_INNER;
79168  }
79169  return jointype;
79170}
79171
79172/*
79173** Return the index of a column in a table.  Return -1 if the column
79174** is not contained in the table.
79175*/
79176static int columnIndex(Table *pTab, const char *zCol){
79177  int i;
79178  for(i=0; i<pTab->nCol; i++){
79179    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
79180  }
79181  return -1;
79182}
79183
79184/*
79185** Search the first N tables in pSrc, from left to right, looking for a
79186** table that has a column named zCol.
79187**
79188** When found, set *piTab and *piCol to the table index and column index
79189** of the matching column and return TRUE.
79190**
79191** If not found, return FALSE.
79192*/
79193static int tableAndColumnIndex(
79194  SrcList *pSrc,       /* Array of tables to search */
79195  int N,               /* Number of tables in pSrc->a[] to search */
79196  const char *zCol,    /* Name of the column we are looking for */
79197  int *piTab,          /* Write index of pSrc->a[] here */
79198  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
79199){
79200  int i;               /* For looping over tables in pSrc */
79201  int iCol;            /* Index of column matching zCol */
79202
79203  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
79204  for(i=0; i<N; i++){
79205    iCol = columnIndex(pSrc->a[i].pTab, zCol);
79206    if( iCol>=0 ){
79207      if( piTab ){
79208        *piTab = i;
79209        *piCol = iCol;
79210      }
79211      return 1;
79212    }
79213  }
79214  return 0;
79215}
79216
79217/*
79218** This function is used to add terms implied by JOIN syntax to the
79219** WHERE clause expression of a SELECT statement. The new term, which
79220** is ANDed with the existing WHERE clause, is of the form:
79221**
79222**    (tab1.col1 = tab2.col2)
79223**
79224** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
79225** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
79226** column iColRight of tab2.
79227*/
79228static void addWhereTerm(
79229  Parse *pParse,                  /* Parsing context */
79230  SrcList *pSrc,                  /* List of tables in FROM clause */
79231  int iLeft,                      /* Index of first table to join in pSrc */
79232  int iColLeft,                   /* Index of column in first table */
79233  int iRight,                     /* Index of second table in pSrc */
79234  int iColRight,                  /* Index of column in second table */
79235  int isOuterJoin,                /* True if this is an OUTER join */
79236  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
79237){
79238  sqlite3 *db = pParse->db;
79239  Expr *pE1;
79240  Expr *pE2;
79241  Expr *pEq;
79242
79243  assert( iLeft<iRight );
79244  assert( pSrc->nSrc>iRight );
79245  assert( pSrc->a[iLeft].pTab );
79246  assert( pSrc->a[iRight].pTab );
79247
79248  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
79249  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
79250
79251  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
79252  if( pEq && isOuterJoin ){
79253    ExprSetProperty(pEq, EP_FromJoin);
79254    assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
79255    ExprSetIrreducible(pEq);
79256    pEq->iRightJoinTable = (i16)pE2->iTable;
79257  }
79258  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
79259}
79260
79261/*
79262** Set the EP_FromJoin property on all terms of the given expression.
79263** And set the Expr.iRightJoinTable to iTable for every term in the
79264** expression.
79265**
79266** The EP_FromJoin property is used on terms of an expression to tell
79267** the LEFT OUTER JOIN processing logic that this term is part of the
79268** join restriction specified in the ON or USING clause and not a part
79269** of the more general WHERE clause.  These terms are moved over to the
79270** WHERE clause during join processing but we need to remember that they
79271** originated in the ON or USING clause.
79272**
79273** The Expr.iRightJoinTable tells the WHERE clause processing that the
79274** expression depends on table iRightJoinTable even if that table is not
79275** explicitly mentioned in the expression.  That information is needed
79276** for cases like this:
79277**
79278**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
79279**
79280** The where clause needs to defer the handling of the t1.x=5
79281** term until after the t2 loop of the join.  In that way, a
79282** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
79283** defer the handling of t1.x=5, it will be processed immediately
79284** after the t1 loop and rows with t1.x!=5 will never appear in
79285** the output, which is incorrect.
79286*/
79287static void setJoinExpr(Expr *p, int iTable){
79288  while( p ){
79289    ExprSetProperty(p, EP_FromJoin);
79290    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
79291    ExprSetIrreducible(p);
79292    p->iRightJoinTable = (i16)iTable;
79293    setJoinExpr(p->pLeft, iTable);
79294    p = p->pRight;
79295  }
79296}
79297
79298/*
79299** This routine processes the join information for a SELECT statement.
79300** ON and USING clauses are converted into extra terms of the WHERE clause.
79301** NATURAL joins also create extra WHERE clause terms.
79302**
79303** The terms of a FROM clause are contained in the Select.pSrc structure.
79304** The left most table is the first entry in Select.pSrc.  The right-most
79305** table is the last entry.  The join operator is held in the entry to
79306** the left.  Thus entry 0 contains the join operator for the join between
79307** entries 0 and 1.  Any ON or USING clauses associated with the join are
79308** also attached to the left entry.
79309**
79310** This routine returns the number of errors encountered.
79311*/
79312static int sqliteProcessJoin(Parse *pParse, Select *p){
79313  SrcList *pSrc;                  /* All tables in the FROM clause */
79314  int i, j;                       /* Loop counters */
79315  struct SrcList_item *pLeft;     /* Left table being joined */
79316  struct SrcList_item *pRight;    /* Right table being joined */
79317
79318  pSrc = p->pSrc;
79319  pLeft = &pSrc->a[0];
79320  pRight = &pLeft[1];
79321  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
79322    Table *pLeftTab = pLeft->pTab;
79323    Table *pRightTab = pRight->pTab;
79324    int isOuter;
79325
79326    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
79327    isOuter = (pRight->jointype & JT_OUTER)!=0;
79328
79329    /* When the NATURAL keyword is present, add WHERE clause terms for
79330    ** every column that the two tables have in common.
79331    */
79332    if( pRight->jointype & JT_NATURAL ){
79333      if( pRight->pOn || pRight->pUsing ){
79334        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
79335           "an ON or USING clause", 0);
79336        return 1;
79337      }
79338      for(j=0; j<pRightTab->nCol; j++){
79339        char *zName;   /* Name of column in the right table */
79340        int iLeft;     /* Matching left table */
79341        int iLeftCol;  /* Matching column in the left table */
79342
79343        zName = pRightTab->aCol[j].zName;
79344        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
79345          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
79346                       isOuter, &p->pWhere);
79347        }
79348      }
79349    }
79350
79351    /* Disallow both ON and USING clauses in the same join
79352    */
79353    if( pRight->pOn && pRight->pUsing ){
79354      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
79355        "clauses in the same join");
79356      return 1;
79357    }
79358
79359    /* Add the ON clause to the end of the WHERE clause, connected by
79360    ** an AND operator.
79361    */
79362    if( pRight->pOn ){
79363      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
79364      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
79365      pRight->pOn = 0;
79366    }
79367
79368    /* Create extra terms on the WHERE clause for each column named
79369    ** in the USING clause.  Example: If the two tables to be joined are
79370    ** A and B and the USING clause names X, Y, and Z, then add this
79371    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
79372    ** Report an error if any column mentioned in the USING clause is
79373    ** not contained in both tables to be joined.
79374    */
79375    if( pRight->pUsing ){
79376      IdList *pList = pRight->pUsing;
79377      for(j=0; j<pList->nId; j++){
79378        char *zName;     /* Name of the term in the USING clause */
79379        int iLeft;       /* Table on the left with matching column name */
79380        int iLeftCol;    /* Column number of matching column on the left */
79381        int iRightCol;   /* Column number of matching column on the right */
79382
79383        zName = pList->a[j].zName;
79384        iRightCol = columnIndex(pRightTab, zName);
79385        if( iRightCol<0
79386         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
79387        ){
79388          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
79389            "not present in both tables", zName);
79390          return 1;
79391        }
79392        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
79393                     isOuter, &p->pWhere);
79394      }
79395    }
79396  }
79397  return 0;
79398}
79399
79400/*
79401** Insert code into "v" that will push the record on the top of the
79402** stack into the sorter.
79403*/
79404static void pushOntoSorter(
79405  Parse *pParse,         /* Parser context */
79406  ExprList *pOrderBy,    /* The ORDER BY clause */
79407  Select *pSelect,       /* The whole SELECT statement */
79408  int regData            /* Register holding data to be sorted */
79409){
79410  Vdbe *v = pParse->pVdbe;
79411  int nExpr = pOrderBy->nExpr;
79412  int regBase = sqlite3GetTempRange(pParse, nExpr+2);
79413  int regRecord = sqlite3GetTempReg(pParse);
79414  sqlite3ExprCacheClear(pParse);
79415  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
79416  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
79417  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
79418  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
79419  sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
79420  sqlite3ReleaseTempReg(pParse, regRecord);
79421  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
79422  if( pSelect->iLimit ){
79423    int addr1, addr2;
79424    int iLimit;
79425    if( pSelect->iOffset ){
79426      iLimit = pSelect->iOffset+1;
79427    }else{
79428      iLimit = pSelect->iLimit;
79429    }
79430    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
79431    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
79432    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
79433    sqlite3VdbeJumpHere(v, addr1);
79434    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
79435    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
79436    sqlite3VdbeJumpHere(v, addr2);
79437    pSelect->iLimit = 0;
79438  }
79439}
79440
79441/*
79442** Add code to implement the OFFSET
79443*/
79444static void codeOffset(
79445  Vdbe *v,          /* Generate code into this VM */
79446  Select *p,        /* The SELECT statement being coded */
79447  int iContinue     /* Jump here to skip the current record */
79448){
79449  if( p->iOffset && iContinue!=0 ){
79450    int addr;
79451    sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
79452    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
79453    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
79454    VdbeComment((v, "skip OFFSET records"));
79455    sqlite3VdbeJumpHere(v, addr);
79456  }
79457}
79458
79459/*
79460** Add code that will check to make sure the N registers starting at iMem
79461** form a distinct entry.  iTab is a sorting index that holds previously
79462** seen combinations of the N values.  A new entry is made in iTab
79463** if the current N values are new.
79464**
79465** A jump to addrRepeat is made and the N+1 values are popped from the
79466** stack if the top N elements are not distinct.
79467*/
79468static void codeDistinct(
79469  Parse *pParse,     /* Parsing and code generating context */
79470  int iTab,          /* A sorting index used to test for distinctness */
79471  int addrRepeat,    /* Jump to here if not distinct */
79472  int N,             /* Number of elements */
79473  int iMem           /* First element */
79474){
79475  Vdbe *v;
79476  int r1;
79477
79478  v = pParse->pVdbe;
79479  r1 = sqlite3GetTempReg(pParse);
79480  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
79481  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
79482  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
79483  sqlite3ReleaseTempReg(pParse, r1);
79484}
79485
79486/*
79487** Generate an error message when a SELECT is used within a subexpression
79488** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
79489** column.  We do this in a subroutine because the error occurs in multiple
79490** places.
79491*/
79492static int checkForMultiColumnSelectError(
79493  Parse *pParse,       /* Parse context. */
79494  SelectDest *pDest,   /* Destination of SELECT results */
79495  int nExpr            /* Number of result columns returned by SELECT */
79496){
79497  int eDest = pDest->eDest;
79498  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
79499    sqlite3ErrorMsg(pParse, "only a single result allowed for "
79500       "a SELECT that is part of an expression");
79501    return 1;
79502  }else{
79503    return 0;
79504  }
79505}
79506
79507/*
79508** This routine generates the code for the inside of the inner loop
79509** of a SELECT.
79510**
79511** If srcTab and nColumn are both zero, then the pEList expressions
79512** are evaluated in order to get the data for this row.  If nColumn>0
79513** then data is pulled from srcTab and pEList is used only to get the
79514** datatypes for each column.
79515*/
79516static void selectInnerLoop(
79517  Parse *pParse,          /* The parser context */
79518  Select *p,              /* The complete select statement being coded */
79519  ExprList *pEList,       /* List of values being extracted */
79520  int srcTab,             /* Pull data from this table */
79521  int nColumn,            /* Number of columns in the source table */
79522  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
79523  int distinct,           /* If >=0, make sure results are distinct */
79524  SelectDest *pDest,      /* How to dispose of the results */
79525  int iContinue,          /* Jump here to continue with next row */
79526  int iBreak              /* Jump here to break out of the inner loop */
79527){
79528  Vdbe *v = pParse->pVdbe;
79529  int i;
79530  int hasDistinct;        /* True if the DISTINCT keyword is present */
79531  int regResult;              /* Start of memory holding result set */
79532  int eDest = pDest->eDest;   /* How to dispose of results */
79533  int iParm = pDest->iParm;   /* First argument to disposal method */
79534  int nResultCol;             /* Number of result columns */
79535
79536  assert( v );
79537  if( NEVER(v==0) ) return;
79538  assert( pEList!=0 );
79539  hasDistinct = distinct>=0;
79540  if( pOrderBy==0 && !hasDistinct ){
79541    codeOffset(v, p, iContinue);
79542  }
79543
79544  /* Pull the requested columns.
79545  */
79546  if( nColumn>0 ){
79547    nResultCol = nColumn;
79548  }else{
79549    nResultCol = pEList->nExpr;
79550  }
79551  if( pDest->iMem==0 ){
79552    pDest->iMem = pParse->nMem+1;
79553    pDest->nMem = nResultCol;
79554    pParse->nMem += nResultCol;
79555  }else{
79556    assert( pDest->nMem==nResultCol );
79557  }
79558  regResult = pDest->iMem;
79559  if( nColumn>0 ){
79560    for(i=0; i<nColumn; i++){
79561      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
79562    }
79563  }else if( eDest!=SRT_Exists ){
79564    /* If the destination is an EXISTS(...) expression, the actual
79565    ** values returned by the SELECT are not required.
79566    */
79567    sqlite3ExprCacheClear(pParse);
79568    sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
79569  }
79570  nColumn = nResultCol;
79571
79572  /* If the DISTINCT keyword was present on the SELECT statement
79573  ** and this row has been seen before, then do not make this row
79574  ** part of the result.
79575  */
79576  if( hasDistinct ){
79577    assert( pEList!=0 );
79578    assert( pEList->nExpr==nColumn );
79579    codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
79580    if( pOrderBy==0 ){
79581      codeOffset(v, p, iContinue);
79582    }
79583  }
79584
79585  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
79586    return;
79587  }
79588
79589  switch( eDest ){
79590    /* In this mode, write each query result to the key of the temporary
79591    ** table iParm.
79592    */
79593#ifndef SQLITE_OMIT_COMPOUND_SELECT
79594    case SRT_Union: {
79595      int r1;
79596      r1 = sqlite3GetTempReg(pParse);
79597      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79598      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
79599      sqlite3ReleaseTempReg(pParse, r1);
79600      break;
79601    }
79602
79603    /* Construct a record from the query result, but instead of
79604    ** saving that record, use it as a key to delete elements from
79605    ** the temporary table iParm.
79606    */
79607    case SRT_Except: {
79608      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
79609      break;
79610    }
79611#endif
79612
79613    /* Store the result as data using a unique key.
79614    */
79615    case SRT_Table:
79616    case SRT_EphemTab: {
79617      int r1 = sqlite3GetTempReg(pParse);
79618      testcase( eDest==SRT_Table );
79619      testcase( eDest==SRT_EphemTab );
79620      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79621      if( pOrderBy ){
79622        pushOntoSorter(pParse, pOrderBy, p, r1);
79623      }else{
79624        int r2 = sqlite3GetTempReg(pParse);
79625        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
79626        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
79627        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79628        sqlite3ReleaseTempReg(pParse, r2);
79629      }
79630      sqlite3ReleaseTempReg(pParse, r1);
79631      break;
79632    }
79633
79634#ifndef SQLITE_OMIT_SUBQUERY
79635    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
79636    ** then there should be a single item on the stack.  Write this
79637    ** item into the set table with bogus data.
79638    */
79639    case SRT_Set: {
79640      assert( nColumn==1 );
79641      p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
79642      if( pOrderBy ){
79643        /* At first glance you would think we could optimize out the
79644        ** ORDER BY in this case since the order of entries in the set
79645        ** does not matter.  But there might be a LIMIT clause, in which
79646        ** case the order does matter */
79647        pushOntoSorter(pParse, pOrderBy, p, regResult);
79648      }else{
79649        int r1 = sqlite3GetTempReg(pParse);
79650        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
79651        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
79652        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
79653        sqlite3ReleaseTempReg(pParse, r1);
79654      }
79655      break;
79656    }
79657
79658    /* If any row exist in the result set, record that fact and abort.
79659    */
79660    case SRT_Exists: {
79661      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
79662      /* The LIMIT clause will terminate the loop for us */
79663      break;
79664    }
79665
79666    /* If this is a scalar select that is part of an expression, then
79667    ** store the results in the appropriate memory cell and break out
79668    ** of the scan loop.
79669    */
79670    case SRT_Mem: {
79671      assert( nColumn==1 );
79672      if( pOrderBy ){
79673        pushOntoSorter(pParse, pOrderBy, p, regResult);
79674      }else{
79675        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
79676        /* The LIMIT clause will jump out of the loop for us */
79677      }
79678      break;
79679    }
79680#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
79681
79682    /* Send the data to the callback function or to a subroutine.  In the
79683    ** case of a subroutine, the subroutine itself is responsible for
79684    ** popping the data from the stack.
79685    */
79686    case SRT_Coroutine:
79687    case SRT_Output: {
79688      testcase( eDest==SRT_Coroutine );
79689      testcase( eDest==SRT_Output );
79690      if( pOrderBy ){
79691        int r1 = sqlite3GetTempReg(pParse);
79692        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
79693        pushOntoSorter(pParse, pOrderBy, p, r1);
79694        sqlite3ReleaseTempReg(pParse, r1);
79695      }else if( eDest==SRT_Coroutine ){
79696        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
79697      }else{
79698        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
79699        sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
79700      }
79701      break;
79702    }
79703
79704#if !defined(SQLITE_OMIT_TRIGGER)
79705    /* Discard the results.  This is used for SELECT statements inside
79706    ** the body of a TRIGGER.  The purpose of such selects is to call
79707    ** user-defined functions that have side effects.  We do not care
79708    ** about the actual results of the select.
79709    */
79710    default: {
79711      assert( eDest==SRT_Discard );
79712      break;
79713    }
79714#endif
79715  }
79716
79717  /* Jump to the end of the loop if the LIMIT is reached.
79718  */
79719  if( p->iLimit ){
79720    assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
79721                            ** pushOntoSorter() would have cleared p->iLimit */
79722    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
79723  }
79724}
79725
79726/*
79727** Given an expression list, generate a KeyInfo structure that records
79728** the collating sequence for each expression in that expression list.
79729**
79730** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
79731** KeyInfo structure is appropriate for initializing a virtual index to
79732** implement that clause.  If the ExprList is the result set of a SELECT
79733** then the KeyInfo structure is appropriate for initializing a virtual
79734** index to implement a DISTINCT test.
79735**
79736** Space to hold the KeyInfo structure is obtain from malloc.  The calling
79737** function is responsible for seeing that this structure is eventually
79738** freed.  Add the KeyInfo structure to the P4 field of an opcode using
79739** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
79740*/
79741static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
79742  sqlite3 *db = pParse->db;
79743  int nExpr;
79744  KeyInfo *pInfo;
79745  struct ExprList_item *pItem;
79746  int i;
79747
79748  nExpr = pList->nExpr;
79749  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
79750  if( pInfo ){
79751    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
79752    pInfo->nField = (u16)nExpr;
79753    pInfo->enc = ENC(db);
79754    pInfo->db = db;
79755    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
79756      CollSeq *pColl;
79757      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
79758      if( !pColl ){
79759        pColl = db->pDfltColl;
79760      }
79761      pInfo->aColl[i] = pColl;
79762      pInfo->aSortOrder[i] = pItem->sortOrder;
79763    }
79764  }
79765  return pInfo;
79766}
79767
79768
79769/*
79770** If the inner loop was generated using a non-null pOrderBy argument,
79771** then the results were placed in a sorter.  After the loop is terminated
79772** we need to run the sorter and output the results.  The following
79773** routine generates the code needed to do that.
79774*/
79775static void generateSortTail(
79776  Parse *pParse,    /* Parsing context */
79777  Select *p,        /* The SELECT statement */
79778  Vdbe *v,          /* Generate code into this VDBE */
79779  int nColumn,      /* Number of columns of data */
79780  SelectDest *pDest /* Write the sorted results here */
79781){
79782  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
79783  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
79784  int addr;
79785  int iTab;
79786  int pseudoTab = 0;
79787  ExprList *pOrderBy = p->pOrderBy;
79788
79789  int eDest = pDest->eDest;
79790  int iParm = pDest->iParm;
79791
79792  int regRow;
79793  int regRowid;
79794
79795  iTab = pOrderBy->iECursor;
79796  regRow = sqlite3GetTempReg(pParse);
79797  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
79798    pseudoTab = pParse->nTab++;
79799    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
79800    regRowid = 0;
79801  }else{
79802    regRowid = sqlite3GetTempReg(pParse);
79803  }
79804  addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
79805  codeOffset(v, p, addrContinue);
79806  sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
79807  switch( eDest ){
79808    case SRT_Table:
79809    case SRT_EphemTab: {
79810      testcase( eDest==SRT_Table );
79811      testcase( eDest==SRT_EphemTab );
79812      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
79813      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
79814      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79815      break;
79816    }
79817#ifndef SQLITE_OMIT_SUBQUERY
79818    case SRT_Set: {
79819      assert( nColumn==1 );
79820      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
79821      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
79822      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
79823      break;
79824    }
79825    case SRT_Mem: {
79826      assert( nColumn==1 );
79827      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
79828      /* The LIMIT clause will terminate the loop for us */
79829      break;
79830    }
79831#endif
79832    default: {
79833      int i;
79834      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
79835      testcase( eDest==SRT_Output );
79836      testcase( eDest==SRT_Coroutine );
79837      for(i=0; i<nColumn; i++){
79838        assert( regRow!=pDest->iMem+i );
79839        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
79840        if( i==0 ){
79841          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
79842        }
79843      }
79844      if( eDest==SRT_Output ){
79845        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
79846        sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
79847      }else{
79848        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
79849      }
79850      break;
79851    }
79852  }
79853  sqlite3ReleaseTempReg(pParse, regRow);
79854  sqlite3ReleaseTempReg(pParse, regRowid);
79855
79856  /* LIMIT has been implemented by the pushOntoSorter() routine.
79857  */
79858  assert( p->iLimit==0 );
79859
79860  /* The bottom of the loop
79861  */
79862  sqlite3VdbeResolveLabel(v, addrContinue);
79863  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
79864  sqlite3VdbeResolveLabel(v, addrBreak);
79865  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
79866    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
79867  }
79868}
79869
79870/*
79871** Return a pointer to a string containing the 'declaration type' of the
79872** expression pExpr. The string may be treated as static by the caller.
79873**
79874** The declaration type is the exact datatype definition extracted from the
79875** original CREATE TABLE statement if the expression is a column. The
79876** declaration type for a ROWID field is INTEGER. Exactly when an expression
79877** is considered a column can be complex in the presence of subqueries. The
79878** result-set expression in all of the following SELECT statements is
79879** considered a column by this function.
79880**
79881**   SELECT col FROM tbl;
79882**   SELECT (SELECT col FROM tbl;
79883**   SELECT (SELECT col FROM tbl);
79884**   SELECT abc FROM (SELECT col AS abc FROM tbl);
79885**
79886** The declaration type for any expression other than a column is NULL.
79887*/
79888static const char *columnType(
79889  NameContext *pNC,
79890  Expr *pExpr,
79891  const char **pzOriginDb,
79892  const char **pzOriginTab,
79893  const char **pzOriginCol
79894){
79895  char const *zType = 0;
79896  char const *zOriginDb = 0;
79897  char const *zOriginTab = 0;
79898  char const *zOriginCol = 0;
79899  int j;
79900  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
79901
79902  switch( pExpr->op ){
79903    case TK_AGG_COLUMN:
79904    case TK_COLUMN: {
79905      /* The expression is a column. Locate the table the column is being
79906      ** extracted from in NameContext.pSrcList. This table may be real
79907      ** database table or a subquery.
79908      */
79909      Table *pTab = 0;            /* Table structure column is extracted from */
79910      Select *pS = 0;             /* Select the column is extracted from */
79911      int iCol = pExpr->iColumn;  /* Index of column in pTab */
79912      testcase( pExpr->op==TK_AGG_COLUMN );
79913      testcase( pExpr->op==TK_COLUMN );
79914      while( pNC && !pTab ){
79915        SrcList *pTabList = pNC->pSrcList;
79916        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
79917        if( j<pTabList->nSrc ){
79918          pTab = pTabList->a[j].pTab;
79919          pS = pTabList->a[j].pSelect;
79920        }else{
79921          pNC = pNC->pNext;
79922        }
79923      }
79924
79925      if( pTab==0 ){
79926        /* At one time, code such as "SELECT new.x" within a trigger would
79927        ** cause this condition to run.  Since then, we have restructured how
79928        ** trigger code is generated and so this condition is no longer
79929        ** possible. However, it can still be true for statements like
79930        ** the following:
79931        **
79932        **   CREATE TABLE t1(col INTEGER);
79933        **   SELECT (SELECT t1.col) FROM FROM t1;
79934        **
79935        ** when columnType() is called on the expression "t1.col" in the
79936        ** sub-select. In this case, set the column type to NULL, even
79937        ** though it should really be "INTEGER".
79938        **
79939        ** This is not a problem, as the column type of "t1.col" is never
79940        ** used. When columnType() is called on the expression
79941        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
79942        ** branch below.  */
79943        break;
79944      }
79945
79946      assert( pTab && pExpr->pTab==pTab );
79947      if( pS ){
79948        /* The "table" is actually a sub-select or a view in the FROM clause
79949        ** of the SELECT statement. Return the declaration type and origin
79950        ** data for the result-set column of the sub-select.
79951        */
79952        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
79953          /* If iCol is less than zero, then the expression requests the
79954          ** rowid of the sub-select or view. This expression is legal (see
79955          ** test case misc2.2.2) - it always evaluates to NULL.
79956          */
79957          NameContext sNC;
79958          Expr *p = pS->pEList->a[iCol].pExpr;
79959          sNC.pSrcList = pS->pSrc;
79960          sNC.pNext = pNC;
79961          sNC.pParse = pNC->pParse;
79962          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
79963        }
79964      }else if( ALWAYS(pTab->pSchema) ){
79965        /* A real table */
79966        assert( !pS );
79967        if( iCol<0 ) iCol = pTab->iPKey;
79968        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
79969        if( iCol<0 ){
79970          zType = "INTEGER";
79971          zOriginCol = "rowid";
79972        }else{
79973          zType = pTab->aCol[iCol].zType;
79974          zOriginCol = pTab->aCol[iCol].zName;
79975        }
79976        zOriginTab = pTab->zName;
79977        if( pNC->pParse ){
79978          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
79979          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
79980        }
79981      }
79982      break;
79983    }
79984#ifndef SQLITE_OMIT_SUBQUERY
79985    case TK_SELECT: {
79986      /* The expression is a sub-select. Return the declaration type and
79987      ** origin info for the single column in the result set of the SELECT
79988      ** statement.
79989      */
79990      NameContext sNC;
79991      Select *pS = pExpr->x.pSelect;
79992      Expr *p = pS->pEList->a[0].pExpr;
79993      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
79994      sNC.pSrcList = pS->pSrc;
79995      sNC.pNext = pNC;
79996      sNC.pParse = pNC->pParse;
79997      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
79998      break;
79999    }
80000#endif
80001  }
80002
80003  if( pzOriginDb ){
80004    assert( pzOriginTab && pzOriginCol );
80005    *pzOriginDb = zOriginDb;
80006    *pzOriginTab = zOriginTab;
80007    *pzOriginCol = zOriginCol;
80008  }
80009  return zType;
80010}
80011
80012/*
80013** Generate code that will tell the VDBE the declaration types of columns
80014** in the result set.
80015*/
80016static void generateColumnTypes(
80017  Parse *pParse,      /* Parser context */
80018  SrcList *pTabList,  /* List of tables */
80019  ExprList *pEList    /* Expressions defining the result set */
80020){
80021#ifndef SQLITE_OMIT_DECLTYPE
80022  Vdbe *v = pParse->pVdbe;
80023  int i;
80024  NameContext sNC;
80025  sNC.pSrcList = pTabList;
80026  sNC.pParse = pParse;
80027  for(i=0; i<pEList->nExpr; i++){
80028    Expr *p = pEList->a[i].pExpr;
80029    const char *zType;
80030#ifdef SQLITE_ENABLE_COLUMN_METADATA
80031    const char *zOrigDb = 0;
80032    const char *zOrigTab = 0;
80033    const char *zOrigCol = 0;
80034    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
80035
80036    /* The vdbe must make its own copy of the column-type and other
80037    ** column specific strings, in case the schema is reset before this
80038    ** virtual machine is deleted.
80039    */
80040    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
80041    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
80042    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
80043#else
80044    zType = columnType(&sNC, p, 0, 0, 0);
80045#endif
80046    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
80047  }
80048#endif /* SQLITE_OMIT_DECLTYPE */
80049}
80050
80051/*
80052** Generate code that will tell the VDBE the names of columns
80053** in the result set.  This information is used to provide the
80054** azCol[] values in the callback.
80055*/
80056static void generateColumnNames(
80057  Parse *pParse,      /* Parser context */
80058  SrcList *pTabList,  /* List of tables */
80059  ExprList *pEList    /* Expressions defining the result set */
80060){
80061  Vdbe *v = pParse->pVdbe;
80062  int i, j;
80063  sqlite3 *db = pParse->db;
80064  int fullNames, shortNames;
80065
80066#ifndef SQLITE_OMIT_EXPLAIN
80067  /* If this is an EXPLAIN, skip this step */
80068  if( pParse->explain ){
80069    return;
80070  }
80071#endif
80072
80073  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
80074  pParse->colNamesSet = 1;
80075  fullNames = (db->flags & SQLITE_FullColNames)!=0;
80076  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
80077  sqlite3VdbeSetNumCols(v, pEList->nExpr);
80078  for(i=0; i<pEList->nExpr; i++){
80079    Expr *p;
80080    p = pEList->a[i].pExpr;
80081    if( NEVER(p==0) ) continue;
80082    if( pEList->a[i].zName ){
80083      char *zName = pEList->a[i].zName;
80084      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
80085    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
80086      Table *pTab;
80087      char *zCol;
80088      int iCol = p->iColumn;
80089      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
80090        if( pTabList->a[j].iCursor==p->iTable ) break;
80091      }
80092      assert( j<pTabList->nSrc );
80093      pTab = pTabList->a[j].pTab;
80094      if( iCol<0 ) iCol = pTab->iPKey;
80095      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
80096      if( iCol<0 ){
80097        zCol = "rowid";
80098      }else{
80099        zCol = pTab->aCol[iCol].zName;
80100      }
80101      if( !shortNames && !fullNames ){
80102        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
80103            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
80104      }else if( fullNames ){
80105        char *zName = 0;
80106        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
80107        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
80108      }else{
80109        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
80110      }
80111    }else{
80112      sqlite3VdbeSetColName(v, i, COLNAME_NAME,
80113          sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
80114    }
80115  }
80116  generateColumnTypes(pParse, pTabList, pEList);
80117}
80118
80119#ifndef SQLITE_OMIT_COMPOUND_SELECT
80120/*
80121** Name of the connection operator, used for error messages.
80122*/
80123static const char *selectOpName(int id){
80124  char *z;
80125  switch( id ){
80126    case TK_ALL:       z = "UNION ALL";   break;
80127    case TK_INTERSECT: z = "INTERSECT";   break;
80128    case TK_EXCEPT:    z = "EXCEPT";      break;
80129    default:           z = "UNION";       break;
80130  }
80131  return z;
80132}
80133#endif /* SQLITE_OMIT_COMPOUND_SELECT */
80134
80135/*
80136** Given a an expression list (which is really the list of expressions
80137** that form the result set of a SELECT statement) compute appropriate
80138** column names for a table that would hold the expression list.
80139**
80140** All column names will be unique.
80141**
80142** Only the column names are computed.  Column.zType, Column.zColl,
80143** and other fields of Column are zeroed.
80144**
80145** Return SQLITE_OK on success.  If a memory allocation error occurs,
80146** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
80147*/
80148static int selectColumnsFromExprList(
80149  Parse *pParse,          /* Parsing context */
80150  ExprList *pEList,       /* Expr list from which to derive column names */
80151  int *pnCol,             /* Write the number of columns here */
80152  Column **paCol          /* Write the new column list here */
80153){
80154  sqlite3 *db = pParse->db;   /* Database connection */
80155  int i, j;                   /* Loop counters */
80156  int cnt;                    /* Index added to make the name unique */
80157  Column *aCol, *pCol;        /* For looping over result columns */
80158  int nCol;                   /* Number of columns in the result set */
80159  Expr *p;                    /* Expression for a single result column */
80160  char *zName;                /* Column name */
80161  int nName;                  /* Size of name in zName[] */
80162
80163  *pnCol = nCol = pEList->nExpr;
80164  aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
80165  if( aCol==0 ) return SQLITE_NOMEM;
80166  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
80167    /* Get an appropriate name for the column
80168    */
80169    p = pEList->a[i].pExpr;
80170    assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
80171               || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
80172    if( (zName = pEList->a[i].zName)!=0 ){
80173      /* If the column contains an "AS <name>" phrase, use <name> as the name */
80174      zName = sqlite3DbStrDup(db, zName);
80175    }else{
80176      Expr *pColExpr = p;  /* The expression that is the result column name */
80177      Table *pTab;         /* Table associated with this expression */
80178      while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
80179      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
80180        /* For columns use the column name name */
80181        int iCol = pColExpr->iColumn;
80182        pTab = pColExpr->pTab;
80183        if( iCol<0 ) iCol = pTab->iPKey;
80184        zName = sqlite3MPrintf(db, "%s",
80185                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
80186      }else if( pColExpr->op==TK_ID ){
80187        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
80188        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
80189      }else{
80190        /* Use the original text of the column expression as its name */
80191        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
80192      }
80193    }
80194    if( db->mallocFailed ){
80195      sqlite3DbFree(db, zName);
80196      break;
80197    }
80198
80199    /* Make sure the column name is unique.  If the name is not unique,
80200    ** append a integer to the name so that it becomes unique.
80201    */
80202    nName = sqlite3Strlen30(zName);
80203    for(j=cnt=0; j<i; j++){
80204      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
80205        char *zNewName;
80206        zName[nName] = 0;
80207        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
80208        sqlite3DbFree(db, zName);
80209        zName = zNewName;
80210        j = -1;
80211        if( zName==0 ) break;
80212      }
80213    }
80214    pCol->zName = zName;
80215  }
80216  if( db->mallocFailed ){
80217    for(j=0; j<i; j++){
80218      sqlite3DbFree(db, aCol[j].zName);
80219    }
80220    sqlite3DbFree(db, aCol);
80221    *paCol = 0;
80222    *pnCol = 0;
80223    return SQLITE_NOMEM;
80224  }
80225  return SQLITE_OK;
80226}
80227
80228/*
80229** Add type and collation information to a column list based on
80230** a SELECT statement.
80231**
80232** The column list presumably came from selectColumnNamesFromExprList().
80233** The column list has only names, not types or collations.  This
80234** routine goes through and adds the types and collations.
80235**
80236** This routine requires that all identifiers in the SELECT
80237** statement be resolved.
80238*/
80239static void selectAddColumnTypeAndCollation(
80240  Parse *pParse,        /* Parsing contexts */
80241  int nCol,             /* Number of columns */
80242  Column *aCol,         /* List of columns */
80243  Select *pSelect       /* SELECT used to determine types and collations */
80244){
80245  sqlite3 *db = pParse->db;
80246  NameContext sNC;
80247  Column *pCol;
80248  CollSeq *pColl;
80249  int i;
80250  Expr *p;
80251  struct ExprList_item *a;
80252
80253  assert( pSelect!=0 );
80254  assert( (pSelect->selFlags & SF_Resolved)!=0 );
80255  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
80256  if( db->mallocFailed ) return;
80257  memset(&sNC, 0, sizeof(sNC));
80258  sNC.pSrcList = pSelect->pSrc;
80259  a = pSelect->pEList->a;
80260  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
80261    p = a[i].pExpr;
80262    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
80263    pCol->affinity = sqlite3ExprAffinity(p);
80264    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
80265    pColl = sqlite3ExprCollSeq(pParse, p);
80266    if( pColl ){
80267      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
80268    }
80269  }
80270}
80271
80272/*
80273** Given a SELECT statement, generate a Table structure that describes
80274** the result set of that SELECT.
80275*/
80276SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
80277  Table *pTab;
80278  sqlite3 *db = pParse->db;
80279  int savedFlags;
80280
80281  savedFlags = db->flags;
80282  db->flags &= ~SQLITE_FullColNames;
80283  db->flags |= SQLITE_ShortColNames;
80284  sqlite3SelectPrep(pParse, pSelect, 0);
80285  if( pParse->nErr ) return 0;
80286  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
80287  db->flags = savedFlags;
80288  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
80289  if( pTab==0 ){
80290    return 0;
80291  }
80292  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
80293  ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
80294  assert( db->lookaside.bEnabled==0 );
80295  pTab->dbMem = 0;
80296  pTab->nRef = 1;
80297  pTab->zName = 0;
80298  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
80299  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
80300  pTab->iPKey = -1;
80301  if( db->mallocFailed ){
80302    sqlite3DeleteTable(pTab);
80303    return 0;
80304  }
80305  return pTab;
80306}
80307
80308/*
80309** Get a VDBE for the given parser context.  Create a new one if necessary.
80310** If an error occurs, return NULL and leave a message in pParse.
80311*/
80312SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
80313  Vdbe *v = pParse->pVdbe;
80314  if( v==0 ){
80315    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
80316#ifndef SQLITE_OMIT_TRACE
80317    if( v ){
80318      sqlite3VdbeAddOp0(v, OP_Trace);
80319    }
80320#endif
80321  }
80322  return v;
80323}
80324
80325
80326/*
80327** Compute the iLimit and iOffset fields of the SELECT based on the
80328** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
80329** that appear in the original SQL statement after the LIMIT and OFFSET
80330** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
80331** are the integer memory register numbers for counters used to compute
80332** the limit and offset.  If there is no limit and/or offset, then
80333** iLimit and iOffset are negative.
80334**
80335** This routine changes the values of iLimit and iOffset only if
80336** a limit or offset is defined by pLimit and pOffset.  iLimit and
80337** iOffset should have been preset to appropriate default values
80338** (usually but not always -1) prior to calling this routine.
80339** Only if pLimit!=0 or pOffset!=0 do the limit registers get
80340** redefined.  The UNION ALL operator uses this property to force
80341** the reuse of the same limit and offset registers across multiple
80342** SELECT statements.
80343*/
80344static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
80345  Vdbe *v = 0;
80346  int iLimit = 0;
80347  int iOffset;
80348  int addr1, n;
80349  if( p->iLimit ) return;
80350
80351  /*
80352  ** "LIMIT -1" always shows all rows.  There is some
80353  ** contraversy about what the correct behavior should be.
80354  ** The current implementation interprets "LIMIT 0" to mean
80355  ** no rows.
80356  */
80357  sqlite3ExprCacheClear(pParse);
80358  assert( p->pOffset==0 || p->pLimit!=0 );
80359  if( p->pLimit ){
80360    p->iLimit = iLimit = ++pParse->nMem;
80361    v = sqlite3GetVdbe(pParse);
80362    if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
80363    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
80364      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
80365      VdbeComment((v, "LIMIT counter"));
80366      if( n==0 ){
80367        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
80368      }
80369    }else{
80370      sqlite3ExprCode(pParse, p->pLimit, iLimit);
80371      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
80372      VdbeComment((v, "LIMIT counter"));
80373      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
80374    }
80375    if( p->pOffset ){
80376      p->iOffset = iOffset = ++pParse->nMem;
80377      pParse->nMem++;   /* Allocate an extra register for limit+offset */
80378      sqlite3ExprCode(pParse, p->pOffset, iOffset);
80379      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
80380      VdbeComment((v, "OFFSET counter"));
80381      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
80382      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
80383      sqlite3VdbeJumpHere(v, addr1);
80384      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
80385      VdbeComment((v, "LIMIT+OFFSET"));
80386      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
80387      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
80388      sqlite3VdbeJumpHere(v, addr1);
80389    }
80390  }
80391}
80392
80393#ifndef SQLITE_OMIT_COMPOUND_SELECT
80394/*
80395** Return the appropriate collating sequence for the iCol-th column of
80396** the result set for the compound-select statement "p".  Return NULL if
80397** the column has no default collating sequence.
80398**
80399** The collating sequence for the compound select is taken from the
80400** left-most term of the select that has a collating sequence.
80401*/
80402static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
80403  CollSeq *pRet;
80404  if( p->pPrior ){
80405    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
80406  }else{
80407    pRet = 0;
80408  }
80409  assert( iCol>=0 );
80410  if( pRet==0 && iCol<p->pEList->nExpr ){
80411    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
80412  }
80413  return pRet;
80414}
80415#endif /* SQLITE_OMIT_COMPOUND_SELECT */
80416
80417/* Forward reference */
80418static int multiSelectOrderBy(
80419  Parse *pParse,        /* Parsing context */
80420  Select *p,            /* The right-most of SELECTs to be coded */
80421  SelectDest *pDest     /* What to do with query results */
80422);
80423
80424
80425#ifndef SQLITE_OMIT_COMPOUND_SELECT
80426/*
80427** This routine is called to process a compound query form from
80428** two or more separate queries using UNION, UNION ALL, EXCEPT, or
80429** INTERSECT
80430**
80431** "p" points to the right-most of the two queries.  the query on the
80432** left is p->pPrior.  The left query could also be a compound query
80433** in which case this routine will be called recursively.
80434**
80435** The results of the total query are to be written into a destination
80436** of type eDest with parameter iParm.
80437**
80438** Example 1:  Consider a three-way compound SQL statement.
80439**
80440**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
80441**
80442** This statement is parsed up as follows:
80443**
80444**     SELECT c FROM t3
80445**      |
80446**      `----->  SELECT b FROM t2
80447**                |
80448**                `------>  SELECT a FROM t1
80449**
80450** The arrows in the diagram above represent the Select.pPrior pointer.
80451** So if this routine is called with p equal to the t3 query, then
80452** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
80453**
80454** Notice that because of the way SQLite parses compound SELECTs, the
80455** individual selects always group from left to right.
80456*/
80457static int multiSelect(
80458  Parse *pParse,        /* Parsing context */
80459  Select *p,            /* The right-most of SELECTs to be coded */
80460  SelectDest *pDest     /* What to do with query results */
80461){
80462  int rc = SQLITE_OK;   /* Success code from a subroutine */
80463  Select *pPrior;       /* Another SELECT immediately to our left */
80464  Vdbe *v;              /* Generate code to this VDBE */
80465  SelectDest dest;      /* Alternative data destination */
80466  Select *pDelete = 0;  /* Chain of simple selects to delete */
80467  sqlite3 *db;          /* Database connection */
80468
80469  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
80470  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
80471  */
80472  assert( p && p->pPrior );  /* Calling function guarantees this much */
80473  db = pParse->db;
80474  pPrior = p->pPrior;
80475  assert( pPrior->pRightmost!=pPrior );
80476  assert( pPrior->pRightmost==p->pRightmost );
80477  dest = *pDest;
80478  if( pPrior->pOrderBy ){
80479    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
80480      selectOpName(p->op));
80481    rc = 1;
80482    goto multi_select_end;
80483  }
80484  if( pPrior->pLimit ){
80485    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
80486      selectOpName(p->op));
80487    rc = 1;
80488    goto multi_select_end;
80489  }
80490
80491  v = sqlite3GetVdbe(pParse);
80492  assert( v!=0 );  /* The VDBE already created by calling function */
80493
80494  /* Create the destination temporary table if necessary
80495  */
80496  if( dest.eDest==SRT_EphemTab ){
80497    assert( p->pEList );
80498    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
80499    dest.eDest = SRT_Table;
80500  }
80501
80502  /* Make sure all SELECTs in the statement have the same number of elements
80503  ** in their result sets.
80504  */
80505  assert( p->pEList && pPrior->pEList );
80506  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
80507    sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
80508      " do not have the same number of result columns", selectOpName(p->op));
80509    rc = 1;
80510    goto multi_select_end;
80511  }
80512
80513  /* Compound SELECTs that have an ORDER BY clause are handled separately.
80514  */
80515  if( p->pOrderBy ){
80516    return multiSelectOrderBy(pParse, p, pDest);
80517  }
80518
80519  /* Generate code for the left and right SELECT statements.
80520  */
80521  switch( p->op ){
80522    case TK_ALL: {
80523      int addr = 0;
80524      assert( !pPrior->pLimit );
80525      pPrior->pLimit = p->pLimit;
80526      pPrior->pOffset = p->pOffset;
80527      rc = sqlite3Select(pParse, pPrior, &dest);
80528      p->pLimit = 0;
80529      p->pOffset = 0;
80530      if( rc ){
80531        goto multi_select_end;
80532      }
80533      p->pPrior = 0;
80534      p->iLimit = pPrior->iLimit;
80535      p->iOffset = pPrior->iOffset;
80536      if( p->iLimit ){
80537        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
80538        VdbeComment((v, "Jump ahead if LIMIT reached"));
80539      }
80540      rc = sqlite3Select(pParse, p, &dest);
80541      testcase( rc!=SQLITE_OK );
80542      pDelete = p->pPrior;
80543      p->pPrior = pPrior;
80544      if( addr ){
80545        sqlite3VdbeJumpHere(v, addr);
80546      }
80547      break;
80548    }
80549    case TK_EXCEPT:
80550    case TK_UNION: {
80551      int unionTab;    /* Cursor number of the temporary table holding result */
80552      u8 op = 0;       /* One of the SRT_ operations to apply to self */
80553      int priorOp;     /* The SRT_ operation to apply to prior selects */
80554      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
80555      int addr;
80556      SelectDest uniondest;
80557
80558      testcase( p->op==TK_EXCEPT );
80559      testcase( p->op==TK_UNION );
80560      priorOp = SRT_Union;
80561      if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
80562        /* We can reuse a temporary table generated by a SELECT to our
80563        ** right.
80564        */
80565        assert( p->pRightmost!=p );  /* Can only happen for leftward elements
80566                                     ** of a 3-way or more compound */
80567        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
80568        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
80569        unionTab = dest.iParm;
80570      }else{
80571        /* We will need to create our own temporary table to hold the
80572        ** intermediate results.
80573        */
80574        unionTab = pParse->nTab++;
80575        assert( p->pOrderBy==0 );
80576        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
80577        assert( p->addrOpenEphm[0] == -1 );
80578        p->addrOpenEphm[0] = addr;
80579        p->pRightmost->selFlags |= SF_UsesEphemeral;
80580        assert( p->pEList );
80581      }
80582
80583      /* Code the SELECT statements to our left
80584      */
80585      assert( !pPrior->pOrderBy );
80586      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
80587      rc = sqlite3Select(pParse, pPrior, &uniondest);
80588      if( rc ){
80589        goto multi_select_end;
80590      }
80591
80592      /* Code the current SELECT statement
80593      */
80594      if( p->op==TK_EXCEPT ){
80595        op = SRT_Except;
80596      }else{
80597        assert( p->op==TK_UNION );
80598        op = SRT_Union;
80599      }
80600      p->pPrior = 0;
80601      pLimit = p->pLimit;
80602      p->pLimit = 0;
80603      pOffset = p->pOffset;
80604      p->pOffset = 0;
80605      uniondest.eDest = op;
80606      rc = sqlite3Select(pParse, p, &uniondest);
80607      testcase( rc!=SQLITE_OK );
80608      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
80609      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
80610      sqlite3ExprListDelete(db, p->pOrderBy);
80611      pDelete = p->pPrior;
80612      p->pPrior = pPrior;
80613      p->pOrderBy = 0;
80614      sqlite3ExprDelete(db, p->pLimit);
80615      p->pLimit = pLimit;
80616      p->pOffset = pOffset;
80617      p->iLimit = 0;
80618      p->iOffset = 0;
80619
80620      /* Convert the data in the temporary table into whatever form
80621      ** it is that we currently need.
80622      */
80623      assert( unionTab==dest.iParm || dest.eDest!=priorOp );
80624      if( dest.eDest!=priorOp ){
80625        int iCont, iBreak, iStart;
80626        assert( p->pEList );
80627        if( dest.eDest==SRT_Output ){
80628          Select *pFirst = p;
80629          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
80630          generateColumnNames(pParse, 0, pFirst->pEList);
80631        }
80632        iBreak = sqlite3VdbeMakeLabel(v);
80633        iCont = sqlite3VdbeMakeLabel(v);
80634        computeLimitRegisters(pParse, p, iBreak);
80635        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
80636        iStart = sqlite3VdbeCurrentAddr(v);
80637        selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
80638                        0, -1, &dest, iCont, iBreak);
80639        sqlite3VdbeResolveLabel(v, iCont);
80640        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
80641        sqlite3VdbeResolveLabel(v, iBreak);
80642        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
80643      }
80644      break;
80645    }
80646    default: assert( p->op==TK_INTERSECT ); {
80647      int tab1, tab2;
80648      int iCont, iBreak, iStart;
80649      Expr *pLimit, *pOffset;
80650      int addr;
80651      SelectDest intersectdest;
80652      int r1;
80653
80654      /* INTERSECT is different from the others since it requires
80655      ** two temporary tables.  Hence it has its own case.  Begin
80656      ** by allocating the tables we will need.
80657      */
80658      tab1 = pParse->nTab++;
80659      tab2 = pParse->nTab++;
80660      assert( p->pOrderBy==0 );
80661
80662      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
80663      assert( p->addrOpenEphm[0] == -1 );
80664      p->addrOpenEphm[0] = addr;
80665      p->pRightmost->selFlags |= SF_UsesEphemeral;
80666      assert( p->pEList );
80667
80668      /* Code the SELECTs to our left into temporary table "tab1".
80669      */
80670      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
80671      rc = sqlite3Select(pParse, pPrior, &intersectdest);
80672      if( rc ){
80673        goto multi_select_end;
80674      }
80675
80676      /* Code the current SELECT into temporary table "tab2"
80677      */
80678      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
80679      assert( p->addrOpenEphm[1] == -1 );
80680      p->addrOpenEphm[1] = addr;
80681      p->pPrior = 0;
80682      pLimit = p->pLimit;
80683      p->pLimit = 0;
80684      pOffset = p->pOffset;
80685      p->pOffset = 0;
80686      intersectdest.iParm = tab2;
80687      rc = sqlite3Select(pParse, p, &intersectdest);
80688      testcase( rc!=SQLITE_OK );
80689      pDelete = p->pPrior;
80690      p->pPrior = pPrior;
80691      sqlite3ExprDelete(db, p->pLimit);
80692      p->pLimit = pLimit;
80693      p->pOffset = pOffset;
80694
80695      /* Generate code to take the intersection of the two temporary
80696      ** tables.
80697      */
80698      assert( p->pEList );
80699      if( dest.eDest==SRT_Output ){
80700        Select *pFirst = p;
80701        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
80702        generateColumnNames(pParse, 0, pFirst->pEList);
80703      }
80704      iBreak = sqlite3VdbeMakeLabel(v);
80705      iCont = sqlite3VdbeMakeLabel(v);
80706      computeLimitRegisters(pParse, p, iBreak);
80707      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
80708      r1 = sqlite3GetTempReg(pParse);
80709      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
80710      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
80711      sqlite3ReleaseTempReg(pParse, r1);
80712      selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
80713                      0, -1, &dest, iCont, iBreak);
80714      sqlite3VdbeResolveLabel(v, iCont);
80715      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
80716      sqlite3VdbeResolveLabel(v, iBreak);
80717      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
80718      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
80719      break;
80720    }
80721  }
80722
80723  /* Compute collating sequences used by
80724  ** temporary tables needed to implement the compound select.
80725  ** Attach the KeyInfo structure to all temporary tables.
80726  **
80727  ** This section is run by the right-most SELECT statement only.
80728  ** SELECT statements to the left always skip this part.  The right-most
80729  ** SELECT might also skip this part if it has no ORDER BY clause and
80730  ** no temp tables are required.
80731  */
80732  if( p->selFlags & SF_UsesEphemeral ){
80733    int i;                        /* Loop counter */
80734    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
80735    Select *pLoop;                /* For looping through SELECT statements */
80736    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
80737    int nCol;                     /* Number of columns in result set */
80738
80739    assert( p->pRightmost==p );
80740    nCol = p->pEList->nExpr;
80741    pKeyInfo = sqlite3DbMallocZero(db,
80742                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
80743    if( !pKeyInfo ){
80744      rc = SQLITE_NOMEM;
80745      goto multi_select_end;
80746    }
80747
80748    pKeyInfo->enc = ENC(db);
80749    pKeyInfo->nField = (u16)nCol;
80750
80751    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
80752      *apColl = multiSelectCollSeq(pParse, p, i);
80753      if( 0==*apColl ){
80754        *apColl = db->pDfltColl;
80755      }
80756    }
80757
80758    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
80759      for(i=0; i<2; i++){
80760        int addr = pLoop->addrOpenEphm[i];
80761        if( addr<0 ){
80762          /* If [0] is unused then [1] is also unused.  So we can
80763          ** always safely abort as soon as the first unused slot is found */
80764          assert( pLoop->addrOpenEphm[1]<0 );
80765          break;
80766        }
80767        sqlite3VdbeChangeP2(v, addr, nCol);
80768        sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
80769        pLoop->addrOpenEphm[i] = -1;
80770      }
80771    }
80772    sqlite3DbFree(db, pKeyInfo);
80773  }
80774
80775multi_select_end:
80776  pDest->iMem = dest.iMem;
80777  pDest->nMem = dest.nMem;
80778  sqlite3SelectDelete(db, pDelete);
80779  return rc;
80780}
80781#endif /* SQLITE_OMIT_COMPOUND_SELECT */
80782
80783/*
80784** Code an output subroutine for a coroutine implementation of a
80785** SELECT statment.
80786**
80787** The data to be output is contained in pIn->iMem.  There are
80788** pIn->nMem columns to be output.  pDest is where the output should
80789** be sent.
80790**
80791** regReturn is the number of the register holding the subroutine
80792** return address.
80793**
80794** If regPrev>0 then it is a the first register in a vector that
80795** records the previous output.  mem[regPrev] is a flag that is false
80796** if there has been no previous output.  If regPrev>0 then code is
80797** generated to suppress duplicates.  pKeyInfo is used for comparing
80798** keys.
80799**
80800** If the LIMIT found in p->iLimit is reached, jump immediately to
80801** iBreak.
80802*/
80803static int generateOutputSubroutine(
80804  Parse *pParse,          /* Parsing context */
80805  Select *p,              /* The SELECT statement */
80806  SelectDest *pIn,        /* Coroutine supplying data */
80807  SelectDest *pDest,      /* Where to send the data */
80808  int regReturn,          /* The return address register */
80809  int regPrev,            /* Previous result register.  No uniqueness if 0 */
80810  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
80811  int p4type,             /* The p4 type for pKeyInfo */
80812  int iBreak              /* Jump here if we hit the LIMIT */
80813){
80814  Vdbe *v = pParse->pVdbe;
80815  int iContinue;
80816  int addr;
80817
80818  addr = sqlite3VdbeCurrentAddr(v);
80819  iContinue = sqlite3VdbeMakeLabel(v);
80820
80821  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
80822  */
80823  if( regPrev ){
80824    int j1, j2;
80825    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
80826    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
80827                              (char*)pKeyInfo, p4type);
80828    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
80829    sqlite3VdbeJumpHere(v, j1);
80830    sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
80831    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
80832  }
80833  if( pParse->db->mallocFailed ) return 0;
80834
80835  /* Suppress the the first OFFSET entries if there is an OFFSET clause
80836  */
80837  codeOffset(v, p, iContinue);
80838
80839  switch( pDest->eDest ){
80840    /* Store the result as data using a unique key.
80841    */
80842    case SRT_Table:
80843    case SRT_EphemTab: {
80844      int r1 = sqlite3GetTempReg(pParse);
80845      int r2 = sqlite3GetTempReg(pParse);
80846      testcase( pDest->eDest==SRT_Table );
80847      testcase( pDest->eDest==SRT_EphemTab );
80848      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
80849      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
80850      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
80851      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80852      sqlite3ReleaseTempReg(pParse, r2);
80853      sqlite3ReleaseTempReg(pParse, r1);
80854      break;
80855    }
80856
80857#ifndef SQLITE_OMIT_SUBQUERY
80858    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
80859    ** then there should be a single item on the stack.  Write this
80860    ** item into the set table with bogus data.
80861    */
80862    case SRT_Set: {
80863      int r1;
80864      assert( pIn->nMem==1 );
80865      p->affinity =
80866         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
80867      r1 = sqlite3GetTempReg(pParse);
80868      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
80869      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
80870      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
80871      sqlite3ReleaseTempReg(pParse, r1);
80872      break;
80873    }
80874
80875#if 0  /* Never occurs on an ORDER BY query */
80876    /* If any row exist in the result set, record that fact and abort.
80877    */
80878    case SRT_Exists: {
80879      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
80880      /* The LIMIT clause will terminate the loop for us */
80881      break;
80882    }
80883#endif
80884
80885    /* If this is a scalar select that is part of an expression, then
80886    ** store the results in the appropriate memory cell and break out
80887    ** of the scan loop.
80888    */
80889    case SRT_Mem: {
80890      assert( pIn->nMem==1 );
80891      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
80892      /* The LIMIT clause will jump out of the loop for us */
80893      break;
80894    }
80895#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
80896
80897    /* The results are stored in a sequence of registers
80898    ** starting at pDest->iMem.  Then the co-routine yields.
80899    */
80900    case SRT_Coroutine: {
80901      if( pDest->iMem==0 ){
80902        pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
80903        pDest->nMem = pIn->nMem;
80904      }
80905      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
80906      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
80907      break;
80908    }
80909
80910    /* If none of the above, then the result destination must be
80911    ** SRT_Output.  This routine is never called with any other
80912    ** destination other than the ones handled above or SRT_Output.
80913    **
80914    ** For SRT_Output, results are stored in a sequence of registers.
80915    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
80916    ** return the next row of result.
80917    */
80918    default: {
80919      assert( pDest->eDest==SRT_Output );
80920      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
80921      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
80922      break;
80923    }
80924  }
80925
80926  /* Jump to the end of the loop if the LIMIT is reached.
80927  */
80928  if( p->iLimit ){
80929    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
80930  }
80931
80932  /* Generate the subroutine return
80933  */
80934  sqlite3VdbeResolveLabel(v, iContinue);
80935  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
80936
80937  return addr;
80938}
80939
80940/*
80941** Alternative compound select code generator for cases when there
80942** is an ORDER BY clause.
80943**
80944** We assume a query of the following form:
80945**
80946**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
80947**
80948** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
80949** is to code both <selectA> and <selectB> with the ORDER BY clause as
80950** co-routines.  Then run the co-routines in parallel and merge the results
80951** into the output.  In addition to the two coroutines (called selectA and
80952** selectB) there are 7 subroutines:
80953**
80954**    outA:    Move the output of the selectA coroutine into the output
80955**             of the compound query.
80956**
80957**    outB:    Move the output of the selectB coroutine into the output
80958**             of the compound query.  (Only generated for UNION and
80959**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
80960**             appears only in B.)
80961**
80962**    AltB:    Called when there is data from both coroutines and A<B.
80963**
80964**    AeqB:    Called when there is data from both coroutines and A==B.
80965**
80966**    AgtB:    Called when there is data from both coroutines and A>B.
80967**
80968**    EofA:    Called when data is exhausted from selectA.
80969**
80970**    EofB:    Called when data is exhausted from selectB.
80971**
80972** The implementation of the latter five subroutines depend on which
80973** <operator> is used:
80974**
80975**
80976**             UNION ALL         UNION            EXCEPT          INTERSECT
80977**          -------------  -----------------  --------------  -----------------
80978**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
80979**
80980**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
80981**
80982**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
80983**
80984**   EofA:   outB, nextB      outB, nextB          halt             halt
80985**
80986**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
80987**
80988** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
80989** causes an immediate jump to EofA and an EOF on B following nextB causes
80990** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
80991** following nextX causes a jump to the end of the select processing.
80992**
80993** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
80994** within the output subroutine.  The regPrev register set holds the previously
80995** output value.  A comparison is made against this value and the output
80996** is skipped if the next results would be the same as the previous.
80997**
80998** The implementation plan is to implement the two coroutines and seven
80999** subroutines first, then put the control logic at the bottom.  Like this:
81000**
81001**          goto Init
81002**     coA: coroutine for left query (A)
81003**     coB: coroutine for right query (B)
81004**    outA: output one row of A
81005**    outB: output one row of B (UNION and UNION ALL only)
81006**    EofA: ...
81007**    EofB: ...
81008**    AltB: ...
81009**    AeqB: ...
81010**    AgtB: ...
81011**    Init: initialize coroutine registers
81012**          yield coA
81013**          if eof(A) goto EofA
81014**          yield coB
81015**          if eof(B) goto EofB
81016**    Cmpr: Compare A, B
81017**          Jump AltB, AeqB, AgtB
81018**     End: ...
81019**
81020** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
81021** actually called using Gosub and they do not Return.  EofA and EofB loop
81022** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
81023** and AgtB jump to either L2 or to one of EofA or EofB.
81024*/
81025#ifndef SQLITE_OMIT_COMPOUND_SELECT
81026static int multiSelectOrderBy(
81027  Parse *pParse,        /* Parsing context */
81028  Select *p,            /* The right-most of SELECTs to be coded */
81029  SelectDest *pDest     /* What to do with query results */
81030){
81031  int i, j;             /* Loop counters */
81032  Select *pPrior;       /* Another SELECT immediately to our left */
81033  Vdbe *v;              /* Generate code to this VDBE */
81034  SelectDest destA;     /* Destination for coroutine A */
81035  SelectDest destB;     /* Destination for coroutine B */
81036  int regAddrA;         /* Address register for select-A coroutine */
81037  int regEofA;          /* Flag to indicate when select-A is complete */
81038  int regAddrB;         /* Address register for select-B coroutine */
81039  int regEofB;          /* Flag to indicate when select-B is complete */
81040  int addrSelectA;      /* Address of the select-A coroutine */
81041  int addrSelectB;      /* Address of the select-B coroutine */
81042  int regOutA;          /* Address register for the output-A subroutine */
81043  int regOutB;          /* Address register for the output-B subroutine */
81044  int addrOutA;         /* Address of the output-A subroutine */
81045  int addrOutB = 0;     /* Address of the output-B subroutine */
81046  int addrEofA;         /* Address of the select-A-exhausted subroutine */
81047  int addrEofB;         /* Address of the select-B-exhausted subroutine */
81048  int addrAltB;         /* Address of the A<B subroutine */
81049  int addrAeqB;         /* Address of the A==B subroutine */
81050  int addrAgtB;         /* Address of the A>B subroutine */
81051  int regLimitA;        /* Limit register for select-A */
81052  int regLimitB;        /* Limit register for select-A */
81053  int regPrev;          /* A range of registers to hold previous output */
81054  int savedLimit;       /* Saved value of p->iLimit */
81055  int savedOffset;      /* Saved value of p->iOffset */
81056  int labelCmpr;        /* Label for the start of the merge algorithm */
81057  int labelEnd;         /* Label for the end of the overall SELECT stmt */
81058  int j1;               /* Jump instructions that get retargetted */
81059  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
81060  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
81061  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
81062  sqlite3 *db;          /* Database connection */
81063  ExprList *pOrderBy;   /* The ORDER BY clause */
81064  int nOrderBy;         /* Number of terms in the ORDER BY clause */
81065  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
81066
81067  assert( p->pOrderBy!=0 );
81068  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
81069  db = pParse->db;
81070  v = pParse->pVdbe;
81071  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
81072  labelEnd = sqlite3VdbeMakeLabel(v);
81073  labelCmpr = sqlite3VdbeMakeLabel(v);
81074
81075
81076  /* Patch up the ORDER BY clause
81077  */
81078  op = p->op;
81079  pPrior = p->pPrior;
81080  assert( pPrior->pOrderBy==0 );
81081  pOrderBy = p->pOrderBy;
81082  assert( pOrderBy );
81083  nOrderBy = pOrderBy->nExpr;
81084
81085  /* For operators other than UNION ALL we have to make sure that
81086  ** the ORDER BY clause covers every term of the result set.  Add
81087  ** terms to the ORDER BY clause as necessary.
81088  */
81089  if( op!=TK_ALL ){
81090    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
81091      struct ExprList_item *pItem;
81092      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
81093        assert( pItem->iCol>0 );
81094        if( pItem->iCol==i ) break;
81095      }
81096      if( j==nOrderBy ){
81097        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
81098        if( pNew==0 ) return SQLITE_NOMEM;
81099        pNew->flags |= EP_IntValue;
81100        pNew->u.iValue = i;
81101        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
81102        pOrderBy->a[nOrderBy++].iCol = (u16)i;
81103      }
81104    }
81105  }
81106
81107  /* Compute the comparison permutation and keyinfo that is used with
81108  ** the permutation used to determine if the next
81109  ** row of results comes from selectA or selectB.  Also add explicit
81110  ** collations to the ORDER BY clause terms so that when the subqueries
81111  ** to the right and the left are evaluated, they use the correct
81112  ** collation.
81113  */
81114  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
81115  if( aPermute ){
81116    struct ExprList_item *pItem;
81117    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
81118      assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
81119      aPermute[i] = pItem->iCol - 1;
81120    }
81121    pKeyMerge =
81122      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
81123    if( pKeyMerge ){
81124      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
81125      pKeyMerge->nField = (u16)nOrderBy;
81126      pKeyMerge->enc = ENC(db);
81127      for(i=0; i<nOrderBy; i++){
81128        CollSeq *pColl;
81129        Expr *pTerm = pOrderBy->a[i].pExpr;
81130        if( pTerm->flags & EP_ExpCollate ){
81131          pColl = pTerm->pColl;
81132        }else{
81133          pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
81134          pTerm->flags |= EP_ExpCollate;
81135          pTerm->pColl = pColl;
81136        }
81137        pKeyMerge->aColl[i] = pColl;
81138        pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
81139      }
81140    }
81141  }else{
81142    pKeyMerge = 0;
81143  }
81144
81145  /* Reattach the ORDER BY clause to the query.
81146  */
81147  p->pOrderBy = pOrderBy;
81148  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
81149
81150  /* Allocate a range of temporary registers and the KeyInfo needed
81151  ** for the logic that removes duplicate result rows when the
81152  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
81153  */
81154  if( op==TK_ALL ){
81155    regPrev = 0;
81156  }else{
81157    int nExpr = p->pEList->nExpr;
81158    assert( nOrderBy>=nExpr || db->mallocFailed );
81159    regPrev = sqlite3GetTempRange(pParse, nExpr+1);
81160    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
81161    pKeyDup = sqlite3DbMallocZero(db,
81162                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
81163    if( pKeyDup ){
81164      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
81165      pKeyDup->nField = (u16)nExpr;
81166      pKeyDup->enc = ENC(db);
81167      for(i=0; i<nExpr; i++){
81168        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
81169        pKeyDup->aSortOrder[i] = 0;
81170      }
81171    }
81172  }
81173
81174  /* Separate the left and the right query from one another
81175  */
81176  p->pPrior = 0;
81177  pPrior->pRightmost = 0;
81178  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
81179  if( pPrior->pPrior==0 ){
81180    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
81181  }
81182
81183  /* Compute the limit registers */
81184  computeLimitRegisters(pParse, p, labelEnd);
81185  if( p->iLimit && op==TK_ALL ){
81186    regLimitA = ++pParse->nMem;
81187    regLimitB = ++pParse->nMem;
81188    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
81189                                  regLimitA);
81190    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
81191  }else{
81192    regLimitA = regLimitB = 0;
81193  }
81194  sqlite3ExprDelete(db, p->pLimit);
81195  p->pLimit = 0;
81196  sqlite3ExprDelete(db, p->pOffset);
81197  p->pOffset = 0;
81198
81199  regAddrA = ++pParse->nMem;
81200  regEofA = ++pParse->nMem;
81201  regAddrB = ++pParse->nMem;
81202  regEofB = ++pParse->nMem;
81203  regOutA = ++pParse->nMem;
81204  regOutB = ++pParse->nMem;
81205  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
81206  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
81207
81208  /* Jump past the various subroutines and coroutines to the main
81209  ** merge loop
81210  */
81211  j1 = sqlite3VdbeAddOp0(v, OP_Goto);
81212  addrSelectA = sqlite3VdbeCurrentAddr(v);
81213
81214
81215  /* Generate a coroutine to evaluate the SELECT statement to the
81216  ** left of the compound operator - the "A" select.
81217  */
81218  VdbeNoopComment((v, "Begin coroutine for left SELECT"));
81219  pPrior->iLimit = regLimitA;
81220  sqlite3Select(pParse, pPrior, &destA);
81221  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
81222  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81223  VdbeNoopComment((v, "End coroutine for left SELECT"));
81224
81225  /* Generate a coroutine to evaluate the SELECT statement on
81226  ** the right - the "B" select
81227  */
81228  addrSelectB = sqlite3VdbeCurrentAddr(v);
81229  VdbeNoopComment((v, "Begin coroutine for right SELECT"));
81230  savedLimit = p->iLimit;
81231  savedOffset = p->iOffset;
81232  p->iLimit = regLimitB;
81233  p->iOffset = 0;
81234  sqlite3Select(pParse, p, &destB);
81235  p->iLimit = savedLimit;
81236  p->iOffset = savedOffset;
81237  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
81238  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81239  VdbeNoopComment((v, "End coroutine for right SELECT"));
81240
81241  /* Generate a subroutine that outputs the current row of the A
81242  ** select as the next output row of the compound select.
81243  */
81244  VdbeNoopComment((v, "Output routine for A"));
81245  addrOutA = generateOutputSubroutine(pParse,
81246                 p, &destA, pDest, regOutA,
81247                 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
81248
81249  /* Generate a subroutine that outputs the current row of the B
81250  ** select as the next output row of the compound select.
81251  */
81252  if( op==TK_ALL || op==TK_UNION ){
81253    VdbeNoopComment((v, "Output routine for B"));
81254    addrOutB = generateOutputSubroutine(pParse,
81255                 p, &destB, pDest, regOutB,
81256                 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
81257  }
81258
81259  /* Generate a subroutine to run when the results from select A
81260  ** are exhausted and only data in select B remains.
81261  */
81262  VdbeNoopComment((v, "eof-A subroutine"));
81263  if( op==TK_EXCEPT || op==TK_INTERSECT ){
81264    addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
81265  }else{
81266    addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
81267    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
81268    sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81269    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
81270  }
81271
81272  /* Generate a subroutine to run when the results from select B
81273  ** are exhausted and only data in select A remains.
81274  */
81275  if( op==TK_INTERSECT ){
81276    addrEofB = addrEofA;
81277  }else{
81278    VdbeNoopComment((v, "eof-B subroutine"));
81279    addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
81280    sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
81281    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81282    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
81283  }
81284
81285  /* Generate code to handle the case of A<B
81286  */
81287  VdbeNoopComment((v, "A-lt-B subroutine"));
81288  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
81289  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81290  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81291  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81292
81293  /* Generate code to handle the case of A==B
81294  */
81295  if( op==TK_ALL ){
81296    addrAeqB = addrAltB;
81297  }else if( op==TK_INTERSECT ){
81298    addrAeqB = addrAltB;
81299    addrAltB++;
81300  }else{
81301    VdbeNoopComment((v, "A-eq-B subroutine"));
81302    addrAeqB =
81303    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
81304    sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81305    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81306  }
81307
81308  /* Generate code to handle the case of A>B
81309  */
81310  VdbeNoopComment((v, "A-gt-B subroutine"));
81311  addrAgtB = sqlite3VdbeCurrentAddr(v);
81312  if( op==TK_ALL || op==TK_UNION ){
81313    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
81314  }
81315  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
81316  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
81317  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
81318
81319  /* This code runs once to initialize everything.
81320  */
81321  sqlite3VdbeJumpHere(v, j1);
81322  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
81323  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
81324  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
81325  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
81326  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
81327  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
81328
81329  /* Implement the main merge loop
81330  */
81331  sqlite3VdbeResolveLabel(v, labelCmpr);
81332  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
81333  sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
81334                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
81335  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
81336
81337  /* Release temporary registers
81338  */
81339  if( regPrev ){
81340    sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
81341  }
81342
81343  /* Jump to the this point in order to terminate the query.
81344  */
81345  sqlite3VdbeResolveLabel(v, labelEnd);
81346
81347  /* Set the number of output columns
81348  */
81349  if( pDest->eDest==SRT_Output ){
81350    Select *pFirst = pPrior;
81351    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
81352    generateColumnNames(pParse, 0, pFirst->pEList);
81353  }
81354
81355  /* Reassembly the compound query so that it will be freed correctly
81356  ** by the calling function */
81357  if( p->pPrior ){
81358    sqlite3SelectDelete(db, p->pPrior);
81359  }
81360  p->pPrior = pPrior;
81361
81362  /*** TBD:  Insert subroutine calls to close cursors on incomplete
81363  **** subqueries ****/
81364  return SQLITE_OK;
81365}
81366#endif
81367
81368#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
81369/* Forward Declarations */
81370static void substExprList(sqlite3*, ExprList*, int, ExprList*);
81371static void substSelect(sqlite3*, Select *, int, ExprList *);
81372
81373/*
81374** Scan through the expression pExpr.  Replace every reference to
81375** a column in table number iTable with a copy of the iColumn-th
81376** entry in pEList.  (But leave references to the ROWID column
81377** unchanged.)
81378**
81379** This routine is part of the flattening procedure.  A subquery
81380** whose result set is defined by pEList appears as entry in the
81381** FROM clause of a SELECT such that the VDBE cursor assigned to that
81382** FORM clause entry is iTable.  This routine make the necessary
81383** changes to pExpr so that it refers directly to the source table
81384** of the subquery rather the result set of the subquery.
81385*/
81386static Expr *substExpr(
81387  sqlite3 *db,        /* Report malloc errors to this connection */
81388  Expr *pExpr,        /* Expr in which substitution occurs */
81389  int iTable,         /* Table to be substituted */
81390  ExprList *pEList    /* Substitute expressions */
81391){
81392  if( pExpr==0 ) return 0;
81393  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
81394    if( pExpr->iColumn<0 ){
81395      pExpr->op = TK_NULL;
81396    }else{
81397      Expr *pNew;
81398      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
81399      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
81400      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
81401      if( pNew && pExpr->pColl ){
81402        pNew->pColl = pExpr->pColl;
81403      }
81404      sqlite3ExprDelete(db, pExpr);
81405      pExpr = pNew;
81406    }
81407  }else{
81408    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
81409    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
81410    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
81411      substSelect(db, pExpr->x.pSelect, iTable, pEList);
81412    }else{
81413      substExprList(db, pExpr->x.pList, iTable, pEList);
81414    }
81415  }
81416  return pExpr;
81417}
81418static void substExprList(
81419  sqlite3 *db,         /* Report malloc errors here */
81420  ExprList *pList,     /* List to scan and in which to make substitutes */
81421  int iTable,          /* Table to be substituted */
81422  ExprList *pEList     /* Substitute values */
81423){
81424  int i;
81425  if( pList==0 ) return;
81426  for(i=0; i<pList->nExpr; i++){
81427    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
81428  }
81429}
81430static void substSelect(
81431  sqlite3 *db,         /* Report malloc errors here */
81432  Select *p,           /* SELECT statement in which to make substitutions */
81433  int iTable,          /* Table to be replaced */
81434  ExprList *pEList     /* Substitute values */
81435){
81436  SrcList *pSrc;
81437  struct SrcList_item *pItem;
81438  int i;
81439  if( !p ) return;
81440  substExprList(db, p->pEList, iTable, pEList);
81441  substExprList(db, p->pGroupBy, iTable, pEList);
81442  substExprList(db, p->pOrderBy, iTable, pEList);
81443  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
81444  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
81445  substSelect(db, p->pPrior, iTable, pEList);
81446  pSrc = p->pSrc;
81447  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
81448  if( ALWAYS(pSrc) ){
81449    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
81450      substSelect(db, pItem->pSelect, iTable, pEList);
81451    }
81452  }
81453}
81454#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
81455
81456#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
81457/*
81458** This routine attempts to flatten subqueries in order to speed
81459** execution.  It returns 1 if it makes changes and 0 if no flattening
81460** occurs.
81461**
81462** To understand the concept of flattening, consider the following
81463** query:
81464**
81465**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
81466**
81467** The default way of implementing this query is to execute the
81468** subquery first and store the results in a temporary table, then
81469** run the outer query on that temporary table.  This requires two
81470** passes over the data.  Furthermore, because the temporary table
81471** has no indices, the WHERE clause on the outer query cannot be
81472** optimized.
81473**
81474** This routine attempts to rewrite queries such as the above into
81475** a single flat select, like this:
81476**
81477**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
81478**
81479** The code generated for this simpification gives the same result
81480** but only has to scan the data once.  And because indices might
81481** exist on the table t1, a complete scan of the data might be
81482** avoided.
81483**
81484** Flattening is only attempted if all of the following are true:
81485**
81486**   (1)  The subquery and the outer query do not both use aggregates.
81487**
81488**   (2)  The subquery is not an aggregate or the outer query is not a join.
81489**
81490**   (3)  The subquery is not the right operand of a left outer join
81491**        (Originally ticket #306.  Strenghtened by ticket #3300)
81492**
81493**   (4)  The subquery is not DISTINCT or the outer query is not a join.
81494**
81495**   (5)  The subquery is not DISTINCT or the outer query does not use
81496**        aggregates.
81497**
81498**   (6)  The subquery does not use aggregates or the outer query is not
81499**        DISTINCT.
81500**
81501**   (7)  The subquery has a FROM clause.
81502**
81503**   (8)  The subquery does not use LIMIT or the outer query is not a join.
81504**
81505**   (9)  The subquery does not use LIMIT or the outer query does not use
81506**        aggregates.
81507**
81508**  (10)  The subquery does not use aggregates or the outer query does not
81509**        use LIMIT.
81510**
81511**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
81512**
81513**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
81514**        a separate restriction deriving from ticket #350.
81515**
81516**  (13)  The subquery and outer query do not both use LIMIT
81517**
81518**  (14)  The subquery does not use OFFSET
81519**
81520**  (15)  The outer query is not part of a compound select or the
81521**        subquery does not have both an ORDER BY and a LIMIT clause.
81522**        (See ticket #2339)
81523**
81524**  (16)  The outer query is not an aggregate or the subquery does
81525**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
81526**        until we introduced the group_concat() function.
81527**
81528**  (17)  The sub-query is not a compound select, or it is a UNION ALL
81529**        compound clause made up entirely of non-aggregate queries, and
81530**        the parent query:
81531**
81532**          * is not itself part of a compound select,
81533**          * is not an aggregate or DISTINCT query, and
81534**          * has no other tables or sub-selects in the FROM clause.
81535**
81536**        The parent and sub-query may contain WHERE clauses. Subject to
81537**        rules (11), (13) and (14), they may also contain ORDER BY,
81538**        LIMIT and OFFSET clauses.
81539**
81540**  (18)  If the sub-query is a compound select, then all terms of the
81541**        ORDER by clause of the parent must be simple references to
81542**        columns of the sub-query.
81543**
81544**  (19)  The subquery does not use LIMIT or the outer query does not
81545**        have a WHERE clause.
81546**
81547**  (20)  If the sub-query is a compound select, then it must not use
81548**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
81549**        somewhat by saying that the terms of the ORDER BY clause must
81550**        appear as unmodified result columns in the outer query.  But
81551**        have other optimizations in mind to deal with that case.
81552**
81553** In this routine, the "p" parameter is a pointer to the outer query.
81554** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
81555** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
81556**
81557** If flattening is not attempted, this routine is a no-op and returns 0.
81558** If flattening is attempted this routine returns 1.
81559**
81560** All of the expression analysis must occur on both the outer query and
81561** the subquery before this routine runs.
81562*/
81563static int flattenSubquery(
81564  Parse *pParse,       /* Parsing context */
81565  Select *p,           /* The parent or outer SELECT statement */
81566  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
81567  int isAgg,           /* True if outer SELECT uses aggregate functions */
81568  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
81569){
81570  const char *zSavedAuthContext = pParse->zAuthContext;
81571  Select *pParent;
81572  Select *pSub;       /* The inner query or "subquery" */
81573  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
81574  SrcList *pSrc;      /* The FROM clause of the outer query */
81575  SrcList *pSubSrc;   /* The FROM clause of the subquery */
81576  ExprList *pList;    /* The result set of the outer query */
81577  int iParent;        /* VDBE cursor number of the pSub result set temp table */
81578  int i;              /* Loop counter */
81579  Expr *pWhere;                    /* The WHERE clause */
81580  struct SrcList_item *pSubitem;   /* The subquery */
81581  sqlite3 *db = pParse->db;
81582
81583  /* Check to see if flattening is permitted.  Return 0 if not.
81584  */
81585  assert( p!=0 );
81586  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
81587  if( db->flags & SQLITE_QueryFlattener ) return 0;
81588  pSrc = p->pSrc;
81589  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
81590  pSubitem = &pSrc->a[iFrom];
81591  iParent = pSubitem->iCursor;
81592  pSub = pSubitem->pSelect;
81593  assert( pSub!=0 );
81594  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
81595  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
81596  pSubSrc = pSub->pSrc;
81597  assert( pSubSrc );
81598  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
81599  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
81600  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
81601  ** became arbitrary expressions, we were forced to add restrictions (13)
81602  ** and (14). */
81603  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
81604  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
81605  if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
81606    return 0;                                            /* Restriction (15) */
81607  }
81608  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
81609  if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit)
81610         && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
81611     return 0;
81612  }
81613  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
81614     return 0;         /* Restriction (6)  */
81615  }
81616  if( p->pOrderBy && pSub->pOrderBy ){
81617     return 0;                                           /* Restriction (11) */
81618  }
81619  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
81620  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
81621
81622  /* OBSOLETE COMMENT 1:
81623  ** Restriction 3:  If the subquery is a join, make sure the subquery is
81624  ** not used as the right operand of an outer join.  Examples of why this
81625  ** is not allowed:
81626  **
81627  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
81628  **
81629  ** If we flatten the above, we would get
81630  **
81631  **         (t1 LEFT OUTER JOIN t2) JOIN t3
81632  **
81633  ** which is not at all the same thing.
81634  **
81635  ** OBSOLETE COMMENT 2:
81636  ** Restriction 12:  If the subquery is the right operand of a left outer
81637  ** join, make sure the subquery has no WHERE clause.
81638  ** An examples of why this is not allowed:
81639  **
81640  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
81641  **
81642  ** If we flatten the above, we would get
81643  **
81644  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
81645  **
81646  ** But the t2.x>0 test will always fail on a NULL row of t2, which
81647  ** effectively converts the OUTER JOIN into an INNER JOIN.
81648  **
81649  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
81650  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
81651  ** is fraught with danger.  Best to avoid the whole thing.  If the
81652  ** subquery is the right term of a LEFT JOIN, then do not flatten.
81653  */
81654  if( (pSubitem->jointype & JT_OUTER)!=0 ){
81655    return 0;
81656  }
81657
81658  /* Restriction 17: If the sub-query is a compound SELECT, then it must
81659  ** use only the UNION ALL operator. And none of the simple select queries
81660  ** that make up the compound SELECT are allowed to be aggregate or distinct
81661  ** queries.
81662  */
81663  if( pSub->pPrior ){
81664    if( pSub->pOrderBy ){
81665      return 0;  /* Restriction 20 */
81666    }
81667    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
81668      return 0;
81669    }
81670    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
81671      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
81672      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
81673      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
81674       || (pSub1->pPrior && pSub1->op!=TK_ALL)
81675       || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
81676      ){
81677        return 0;
81678      }
81679    }
81680
81681    /* Restriction 18. */
81682    if( p->pOrderBy ){
81683      int ii;
81684      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
81685        if( p->pOrderBy->a[ii].iCol==0 ) return 0;
81686      }
81687    }
81688  }
81689
81690  /***** If we reach this point, flattening is permitted. *****/
81691
81692  /* Authorize the subquery */
81693  pParse->zAuthContext = pSubitem->zName;
81694  sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
81695  pParse->zAuthContext = zSavedAuthContext;
81696
81697  /* If the sub-query is a compound SELECT statement, then (by restrictions
81698  ** 17 and 18 above) it must be a UNION ALL and the parent query must
81699  ** be of the form:
81700  **
81701  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
81702  **
81703  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
81704  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
81705  ** OFFSET clauses and joins them to the left-hand-side of the original
81706  ** using UNION ALL operators. In this case N is the number of simple
81707  ** select statements in the compound sub-query.
81708  **
81709  ** Example:
81710  **
81711  **     SELECT a+1 FROM (
81712  **        SELECT x FROM tab
81713  **        UNION ALL
81714  **        SELECT y FROM tab
81715  **        UNION ALL
81716  **        SELECT abs(z*2) FROM tab2
81717  **     ) WHERE a!=5 ORDER BY 1
81718  **
81719  ** Transformed into:
81720  **
81721  **     SELECT x+1 FROM tab WHERE x+1!=5
81722  **     UNION ALL
81723  **     SELECT y+1 FROM tab WHERE y+1!=5
81724  **     UNION ALL
81725  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
81726  **     ORDER BY 1
81727  **
81728  ** We call this the "compound-subquery flattening".
81729  */
81730  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
81731    Select *pNew;
81732    ExprList *pOrderBy = p->pOrderBy;
81733    Expr *pLimit = p->pLimit;
81734    Select *pPrior = p->pPrior;
81735    p->pOrderBy = 0;
81736    p->pSrc = 0;
81737    p->pPrior = 0;
81738    p->pLimit = 0;
81739    pNew = sqlite3SelectDup(db, p, 0);
81740    p->pLimit = pLimit;
81741    p->pOrderBy = pOrderBy;
81742    p->pSrc = pSrc;
81743    p->op = TK_ALL;
81744    p->pRightmost = 0;
81745    if( pNew==0 ){
81746      pNew = pPrior;
81747    }else{
81748      pNew->pPrior = pPrior;
81749      pNew->pRightmost = 0;
81750    }
81751    p->pPrior = pNew;
81752    if( db->mallocFailed ) return 1;
81753  }
81754
81755  /* Begin flattening the iFrom-th entry of the FROM clause
81756  ** in the outer query.
81757  */
81758  pSub = pSub1 = pSubitem->pSelect;
81759
81760  /* Delete the transient table structure associated with the
81761  ** subquery
81762  */
81763  sqlite3DbFree(db, pSubitem->zDatabase);
81764  sqlite3DbFree(db, pSubitem->zName);
81765  sqlite3DbFree(db, pSubitem->zAlias);
81766  pSubitem->zDatabase = 0;
81767  pSubitem->zName = 0;
81768  pSubitem->zAlias = 0;
81769  pSubitem->pSelect = 0;
81770
81771  /* Defer deleting the Table object associated with the
81772  ** subquery until code generation is
81773  ** complete, since there may still exist Expr.pTab entries that
81774  ** refer to the subquery even after flattening.  Ticket #3346.
81775  **
81776  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
81777  */
81778  if( ALWAYS(pSubitem->pTab!=0) ){
81779    Table *pTabToDel = pSubitem->pTab;
81780    if( pTabToDel->nRef==1 ){
81781      Parse *pToplevel = sqlite3ParseToplevel(pParse);
81782      pTabToDel->pNextZombie = pToplevel->pZombieTab;
81783      pToplevel->pZombieTab = pTabToDel;
81784    }else{
81785      pTabToDel->nRef--;
81786    }
81787    pSubitem->pTab = 0;
81788  }
81789
81790  /* The following loop runs once for each term in a compound-subquery
81791  ** flattening (as described above).  If we are doing a different kind
81792  ** of flattening - a flattening other than a compound-subquery flattening -
81793  ** then this loop only runs once.
81794  **
81795  ** This loop moves all of the FROM elements of the subquery into the
81796  ** the FROM clause of the outer query.  Before doing this, remember
81797  ** the cursor number for the original outer query FROM element in
81798  ** iParent.  The iParent cursor will never be used.  Subsequent code
81799  ** will scan expressions looking for iParent references and replace
81800  ** those references with expressions that resolve to the subquery FROM
81801  ** elements we are now copying in.
81802  */
81803  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
81804    int nSubSrc;
81805    u8 jointype = 0;
81806    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
81807    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
81808    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
81809
81810    if( pSrc ){
81811      assert( pParent==p );  /* First time through the loop */
81812      jointype = pSubitem->jointype;
81813    }else{
81814      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
81815      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
81816      if( pSrc==0 ){
81817        assert( db->mallocFailed );
81818        break;
81819      }
81820    }
81821
81822    /* The subquery uses a single slot of the FROM clause of the outer
81823    ** query.  If the subquery has more than one element in its FROM clause,
81824    ** then expand the outer query to make space for it to hold all elements
81825    ** of the subquery.
81826    **
81827    ** Example:
81828    **
81829    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
81830    **
81831    ** The outer query has 3 slots in its FROM clause.  One slot of the
81832    ** outer query (the middle slot) is used by the subquery.  The next
81833    ** block of code will expand the out query to 4 slots.  The middle
81834    ** slot is expanded to two slots in order to make space for the
81835    ** two elements in the FROM clause of the subquery.
81836    */
81837    if( nSubSrc>1 ){
81838      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
81839      if( db->mallocFailed ){
81840        break;
81841      }
81842    }
81843
81844    /* Transfer the FROM clause terms from the subquery into the
81845    ** outer query.
81846    */
81847    for(i=0; i<nSubSrc; i++){
81848      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
81849      pSrc->a[i+iFrom] = pSubSrc->a[i];
81850      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
81851    }
81852    pSrc->a[iFrom].jointype = jointype;
81853
81854    /* Now begin substituting subquery result set expressions for
81855    ** references to the iParent in the outer query.
81856    **
81857    ** Example:
81858    **
81859    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
81860    **   \                     \_____________ subquery __________/          /
81861    **    \_____________________ outer query ______________________________/
81862    **
81863    ** We look at every expression in the outer query and every place we see
81864    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
81865    */
81866    pList = pParent->pEList;
81867    for(i=0; i<pList->nExpr; i++){
81868      if( pList->a[i].zName==0 ){
81869        const char *zSpan = pList->a[i].zSpan;
81870        if( ALWAYS(zSpan) ){
81871          pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
81872        }
81873      }
81874    }
81875    substExprList(db, pParent->pEList, iParent, pSub->pEList);
81876    if( isAgg ){
81877      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
81878      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
81879    }
81880    if( pSub->pOrderBy ){
81881      assert( pParent->pOrderBy==0 );
81882      pParent->pOrderBy = pSub->pOrderBy;
81883      pSub->pOrderBy = 0;
81884    }else if( pParent->pOrderBy ){
81885      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
81886    }
81887    if( pSub->pWhere ){
81888      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
81889    }else{
81890      pWhere = 0;
81891    }
81892    if( subqueryIsAgg ){
81893      assert( pParent->pHaving==0 );
81894      pParent->pHaving = pParent->pWhere;
81895      pParent->pWhere = pWhere;
81896      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
81897      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
81898                                  sqlite3ExprDup(db, pSub->pHaving, 0));
81899      assert( pParent->pGroupBy==0 );
81900      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
81901    }else{
81902      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
81903      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
81904    }
81905
81906    /* The flattened query is distinct if either the inner or the
81907    ** outer query is distinct.
81908    */
81909    pParent->selFlags |= pSub->selFlags & SF_Distinct;
81910
81911    /*
81912    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
81913    **
81914    ** One is tempted to try to add a and b to combine the limits.  But this
81915    ** does not work if either limit is negative.
81916    */
81917    if( pSub->pLimit ){
81918      pParent->pLimit = pSub->pLimit;
81919      pSub->pLimit = 0;
81920    }
81921  }
81922
81923  /* Finially, delete what is left of the subquery and return
81924  ** success.
81925  */
81926  sqlite3SelectDelete(db, pSub1);
81927
81928  return 1;
81929}
81930#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
81931
81932/*
81933** Analyze the SELECT statement passed as an argument to see if it
81934** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
81935** it is, or 0 otherwise. At present, a query is considered to be
81936** a min()/max() query if:
81937**
81938**   1. There is a single object in the FROM clause.
81939**
81940**   2. There is a single expression in the result set, and it is
81941**      either min(x) or max(x), where x is a column reference.
81942*/
81943static u8 minMaxQuery(Select *p){
81944  Expr *pExpr;
81945  ExprList *pEList = p->pEList;
81946
81947  if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
81948  pExpr = pEList->a[0].pExpr;
81949  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
81950  if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
81951  pEList = pExpr->x.pList;
81952  if( pEList==0 || pEList->nExpr!=1 ) return 0;
81953  if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
81954  assert( !ExprHasProperty(pExpr, EP_IntValue) );
81955  if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
81956    return WHERE_ORDERBY_MIN;
81957  }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
81958    return WHERE_ORDERBY_MAX;
81959  }
81960  return WHERE_ORDERBY_NORMAL;
81961}
81962
81963/*
81964** The select statement passed as the first argument is an aggregate query.
81965** The second argment is the associated aggregate-info object. This
81966** function tests if the SELECT is of the form:
81967**
81968**   SELECT count(*) FROM <tbl>
81969**
81970** where table is a database table, not a sub-select or view. If the query
81971** does match this pattern, then a pointer to the Table object representing
81972** <tbl> is returned. Otherwise, 0 is returned.
81973*/
81974static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
81975  Table *pTab;
81976  Expr *pExpr;
81977
81978  assert( !p->pGroupBy );
81979
81980  if( p->pWhere || p->pEList->nExpr!=1
81981   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
81982  ){
81983    return 0;
81984  }
81985  pTab = p->pSrc->a[0].pTab;
81986  pExpr = p->pEList->a[0].pExpr;
81987  assert( pTab && !pTab->pSelect && pExpr );
81988
81989  if( IsVirtual(pTab) ) return 0;
81990  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
81991  if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
81992  if( pExpr->flags&EP_Distinct ) return 0;
81993
81994  return pTab;
81995}
81996
81997/*
81998** If the source-list item passed as an argument was augmented with an
81999** INDEXED BY clause, then try to locate the specified index. If there
82000** was such a clause and the named index cannot be found, return
82001** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
82002** pFrom->pIndex and return SQLITE_OK.
82003*/
82004SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
82005  if( pFrom->pTab && pFrom->zIndex ){
82006    Table *pTab = pFrom->pTab;
82007    char *zIndex = pFrom->zIndex;
82008    Index *pIdx;
82009    for(pIdx=pTab->pIndex;
82010        pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
82011        pIdx=pIdx->pNext
82012    );
82013    if( !pIdx ){
82014      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
82015      return SQLITE_ERROR;
82016    }
82017    pFrom->pIndex = pIdx;
82018  }
82019  return SQLITE_OK;
82020}
82021
82022/*
82023** This routine is a Walker callback for "expanding" a SELECT statement.
82024** "Expanding" means to do the following:
82025**
82026**    (1)  Make sure VDBE cursor numbers have been assigned to every
82027**         element of the FROM clause.
82028**
82029**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
82030**         defines FROM clause.  When views appear in the FROM clause,
82031**         fill pTabList->a[].pSelect with a copy of the SELECT statement
82032**         that implements the view.  A copy is made of the view's SELECT
82033**         statement so that we can freely modify or delete that statement
82034**         without worrying about messing up the presistent representation
82035**         of the view.
82036**
82037**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
82038**         on joins and the ON and USING clause of joins.
82039**
82040**    (4)  Scan the list of columns in the result set (pEList) looking
82041**         for instances of the "*" operator or the TABLE.* operator.
82042**         If found, expand each "*" to be every column in every table
82043**         and TABLE.* to be every column in TABLE.
82044**
82045*/
82046static int selectExpander(Walker *pWalker, Select *p){
82047  Parse *pParse = pWalker->pParse;
82048  int i, j, k;
82049  SrcList *pTabList;
82050  ExprList *pEList;
82051  struct SrcList_item *pFrom;
82052  sqlite3 *db = pParse->db;
82053
82054  if( db->mallocFailed  ){
82055    return WRC_Abort;
82056  }
82057  if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
82058    return WRC_Prune;
82059  }
82060  p->selFlags |= SF_Expanded;
82061  pTabList = p->pSrc;
82062  pEList = p->pEList;
82063
82064  /* Make sure cursor numbers have been assigned to all entries in
82065  ** the FROM clause of the SELECT statement.
82066  */
82067  sqlite3SrcListAssignCursors(pParse, pTabList);
82068
82069  /* Look up every table named in the FROM clause of the select.  If
82070  ** an entry of the FROM clause is a subquery instead of a table or view,
82071  ** then create a transient table structure to describe the subquery.
82072  */
82073  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82074    Table *pTab;
82075    if( pFrom->pTab!=0 ){
82076      /* This statement has already been prepared.  There is no need
82077      ** to go further. */
82078      assert( i==0 );
82079      return WRC_Prune;
82080    }
82081    if( pFrom->zName==0 ){
82082#ifndef SQLITE_OMIT_SUBQUERY
82083      Select *pSel = pFrom->pSelect;
82084      /* A sub-query in the FROM clause of a SELECT */
82085      assert( pSel!=0 );
82086      assert( pFrom->pTab==0 );
82087      sqlite3WalkSelect(pWalker, pSel);
82088      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
82089      if( pTab==0 ) return WRC_Abort;
82090      pTab->dbMem = db->lookaside.bEnabled ? db : 0;
82091      pTab->nRef = 1;
82092      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
82093      while( pSel->pPrior ){ pSel = pSel->pPrior; }
82094      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
82095      pTab->iPKey = -1;
82096      pTab->tabFlags |= TF_Ephemeral;
82097#endif
82098    }else{
82099      /* An ordinary table or view name in the FROM clause */
82100      assert( pFrom->pTab==0 );
82101      pFrom->pTab = pTab =
82102        sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
82103      if( pTab==0 ) return WRC_Abort;
82104      pTab->nRef++;
82105#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
82106      if( pTab->pSelect || IsVirtual(pTab) ){
82107        /* We reach here if the named table is a really a view */
82108        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
82109        assert( pFrom->pSelect==0 );
82110        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
82111        sqlite3WalkSelect(pWalker, pFrom->pSelect);
82112      }
82113#endif
82114    }
82115
82116    /* Locate the index named by the INDEXED BY clause, if any. */
82117    if( sqlite3IndexedByLookup(pParse, pFrom) ){
82118      return WRC_Abort;
82119    }
82120  }
82121
82122  /* Process NATURAL keywords, and ON and USING clauses of joins.
82123  */
82124  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
82125    return WRC_Abort;
82126  }
82127
82128  /* For every "*" that occurs in the column list, insert the names of
82129  ** all columns in all tables.  And for every TABLE.* insert the names
82130  ** of all columns in TABLE.  The parser inserted a special expression
82131  ** with the TK_ALL operator for each "*" that it found in the column list.
82132  ** The following code just has to locate the TK_ALL expressions and expand
82133  ** each one to the list of all columns in all tables.
82134  **
82135  ** The first loop just checks to see if there are any "*" operators
82136  ** that need expanding.
82137  */
82138  for(k=0; k<pEList->nExpr; k++){
82139    Expr *pE = pEList->a[k].pExpr;
82140    if( pE->op==TK_ALL ) break;
82141    assert( pE->op!=TK_DOT || pE->pRight!=0 );
82142    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
82143    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
82144  }
82145  if( k<pEList->nExpr ){
82146    /*
82147    ** If we get here it means the result set contains one or more "*"
82148    ** operators that need to be expanded.  Loop through each expression
82149    ** in the result set and expand them one by one.
82150    */
82151    struct ExprList_item *a = pEList->a;
82152    ExprList *pNew = 0;
82153    int flags = pParse->db->flags;
82154    int longNames = (flags & SQLITE_FullColNames)!=0
82155                      && (flags & SQLITE_ShortColNames)==0;
82156
82157    for(k=0; k<pEList->nExpr; k++){
82158      Expr *pE = a[k].pExpr;
82159      assert( pE->op!=TK_DOT || pE->pRight!=0 );
82160      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
82161        /* This particular expression does not need to be expanded.
82162        */
82163        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
82164        if( pNew ){
82165          pNew->a[pNew->nExpr-1].zName = a[k].zName;
82166          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
82167          a[k].zName = 0;
82168          a[k].zSpan = 0;
82169        }
82170        a[k].pExpr = 0;
82171      }else{
82172        /* This expression is a "*" or a "TABLE.*" and needs to be
82173        ** expanded. */
82174        int tableSeen = 0;      /* Set to 1 when TABLE matches */
82175        char *zTName;            /* text of name of TABLE */
82176        if( pE->op==TK_DOT ){
82177          assert( pE->pLeft!=0 );
82178          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
82179          zTName = pE->pLeft->u.zToken;
82180        }else{
82181          zTName = 0;
82182        }
82183        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82184          Table *pTab = pFrom->pTab;
82185          char *zTabName = pFrom->zAlias;
82186          if( zTabName==0 ){
82187            zTabName = pTab->zName;
82188          }
82189          if( db->mallocFailed ) break;
82190          if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
82191            continue;
82192          }
82193          tableSeen = 1;
82194          for(j=0; j<pTab->nCol; j++){
82195            Expr *pExpr, *pRight;
82196            char *zName = pTab->aCol[j].zName;
82197            char *zColname;  /* The computed column name */
82198            char *zToFree;   /* Malloced string that needs to be freed */
82199            Token sColname;  /* Computed column name as a token */
82200
82201            /* If a column is marked as 'hidden' (currently only possible
82202            ** for virtual tables), do not include it in the expanded
82203            ** result-set list.
82204            */
82205            if( IsHiddenColumn(&pTab->aCol[j]) ){
82206              assert(IsVirtual(pTab));
82207              continue;
82208            }
82209
82210            if( i>0 && zTName==0 ){
82211              if( (pFrom->jointype & JT_NATURAL)!=0
82212                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
82213              ){
82214                /* In a NATURAL join, omit the join columns from the
82215                ** table to the right of the join */
82216                continue;
82217              }
82218              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
82219                /* In a join with a USING clause, omit columns in the
82220                ** using clause from the table on the right. */
82221                continue;
82222              }
82223            }
82224            pRight = sqlite3Expr(db, TK_ID, zName);
82225            zColname = zName;
82226            zToFree = 0;
82227            if( longNames || pTabList->nSrc>1 ){
82228              Expr *pLeft;
82229              pLeft = sqlite3Expr(db, TK_ID, zTabName);
82230              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
82231              if( longNames ){
82232                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
82233                zToFree = zColname;
82234              }
82235            }else{
82236              pExpr = pRight;
82237            }
82238            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
82239            sColname.z = zColname;
82240            sColname.n = sqlite3Strlen30(zColname);
82241            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
82242            sqlite3DbFree(db, zToFree);
82243          }
82244        }
82245        if( !tableSeen ){
82246          if( zTName ){
82247            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
82248          }else{
82249            sqlite3ErrorMsg(pParse, "no tables specified");
82250          }
82251        }
82252      }
82253    }
82254    sqlite3ExprListDelete(db, pEList);
82255    p->pEList = pNew;
82256  }
82257#if SQLITE_MAX_COLUMN
82258  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
82259    sqlite3ErrorMsg(pParse, "too many columns in result set");
82260  }
82261#endif
82262  return WRC_Continue;
82263}
82264
82265/*
82266** No-op routine for the parse-tree walker.
82267**
82268** When this routine is the Walker.xExprCallback then expression trees
82269** are walked without any actions being taken at each node.  Presumably,
82270** when this routine is used for Walker.xExprCallback then
82271** Walker.xSelectCallback is set to do something useful for every
82272** subquery in the parser tree.
82273*/
82274static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
82275  UNUSED_PARAMETER2(NotUsed, NotUsed2);
82276  return WRC_Continue;
82277}
82278
82279/*
82280** This routine "expands" a SELECT statement and all of its subqueries.
82281** For additional information on what it means to "expand" a SELECT
82282** statement, see the comment on the selectExpand worker callback above.
82283**
82284** Expanding a SELECT statement is the first step in processing a
82285** SELECT statement.  The SELECT statement must be expanded before
82286** name resolution is performed.
82287**
82288** If anything goes wrong, an error message is written into pParse.
82289** The calling function can detect the problem by looking at pParse->nErr
82290** and/or pParse->db->mallocFailed.
82291*/
82292static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
82293  Walker w;
82294  w.xSelectCallback = selectExpander;
82295  w.xExprCallback = exprWalkNoop;
82296  w.pParse = pParse;
82297  sqlite3WalkSelect(&w, pSelect);
82298}
82299
82300
82301#ifndef SQLITE_OMIT_SUBQUERY
82302/*
82303** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
82304** interface.
82305**
82306** For each FROM-clause subquery, add Column.zType and Column.zColl
82307** information to the Table structure that represents the result set
82308** of that subquery.
82309**
82310** The Table structure that represents the result set was constructed
82311** by selectExpander() but the type and collation information was omitted
82312** at that point because identifiers had not yet been resolved.  This
82313** routine is called after identifier resolution.
82314*/
82315static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
82316  Parse *pParse;
82317  int i;
82318  SrcList *pTabList;
82319  struct SrcList_item *pFrom;
82320
82321  assert( p->selFlags & SF_Resolved );
82322  assert( (p->selFlags & SF_HasTypeInfo)==0 );
82323  p->selFlags |= SF_HasTypeInfo;
82324  pParse = pWalker->pParse;
82325  pTabList = p->pSrc;
82326  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
82327    Table *pTab = pFrom->pTab;
82328    if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
82329      /* A sub-query in the FROM clause of a SELECT */
82330      Select *pSel = pFrom->pSelect;
82331      assert( pSel );
82332      while( pSel->pPrior ) pSel = pSel->pPrior;
82333      selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
82334    }
82335  }
82336  return WRC_Continue;
82337}
82338#endif
82339
82340
82341/*
82342** This routine adds datatype and collating sequence information to
82343** the Table structures of all FROM-clause subqueries in a
82344** SELECT statement.
82345**
82346** Use this routine after name resolution.
82347*/
82348static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
82349#ifndef SQLITE_OMIT_SUBQUERY
82350  Walker w;
82351  w.xSelectCallback = selectAddSubqueryTypeInfo;
82352  w.xExprCallback = exprWalkNoop;
82353  w.pParse = pParse;
82354  sqlite3WalkSelect(&w, pSelect);
82355#endif
82356}
82357
82358
82359/*
82360** This routine sets of a SELECT statement for processing.  The
82361** following is accomplished:
82362**
82363**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
82364**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
82365**     *  ON and USING clauses are shifted into WHERE statements
82366**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
82367**     *  Identifiers in expression are matched to tables.
82368**
82369** This routine acts recursively on all subqueries within the SELECT.
82370*/
82371SQLITE_PRIVATE void sqlite3SelectPrep(
82372  Parse *pParse,         /* The parser context */
82373  Select *p,             /* The SELECT statement being coded. */
82374  NameContext *pOuterNC  /* Name context for container */
82375){
82376  sqlite3 *db;
82377  if( NEVER(p==0) ) return;
82378  db = pParse->db;
82379  if( p->selFlags & SF_HasTypeInfo ) return;
82380  sqlite3SelectExpand(pParse, p);
82381  if( pParse->nErr || db->mallocFailed ) return;
82382  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
82383  if( pParse->nErr || db->mallocFailed ) return;
82384  sqlite3SelectAddTypeInfo(pParse, p);
82385}
82386
82387/*
82388** Reset the aggregate accumulator.
82389**
82390** The aggregate accumulator is a set of memory cells that hold
82391** intermediate results while calculating an aggregate.  This
82392** routine simply stores NULLs in all of those memory cells.
82393*/
82394static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
82395  Vdbe *v = pParse->pVdbe;
82396  int i;
82397  struct AggInfo_func *pFunc;
82398  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
82399    return;
82400  }
82401  for(i=0; i<pAggInfo->nColumn; i++){
82402    sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
82403  }
82404  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
82405    sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
82406    if( pFunc->iDistinct>=0 ){
82407      Expr *pE = pFunc->pExpr;
82408      assert( !ExprHasProperty(pE, EP_xIsSelect) );
82409      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
82410        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
82411           "argument");
82412        pFunc->iDistinct = -1;
82413      }else{
82414        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
82415        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
82416                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82417      }
82418    }
82419  }
82420}
82421
82422/*
82423** Invoke the OP_AggFinalize opcode for every aggregate function
82424** in the AggInfo structure.
82425*/
82426static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
82427  Vdbe *v = pParse->pVdbe;
82428  int i;
82429  struct AggInfo_func *pF;
82430  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
82431    ExprList *pList = pF->pExpr->x.pList;
82432    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
82433    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
82434                      (void*)pF->pFunc, P4_FUNCDEF);
82435  }
82436}
82437
82438/*
82439** Update the accumulator memory cells for an aggregate based on
82440** the current cursor position.
82441*/
82442static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
82443  Vdbe *v = pParse->pVdbe;
82444  int i;
82445  struct AggInfo_func *pF;
82446  struct AggInfo_col *pC;
82447
82448  pAggInfo->directMode = 1;
82449  sqlite3ExprCacheClear(pParse);
82450  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
82451    int nArg;
82452    int addrNext = 0;
82453    int regAgg;
82454    ExprList *pList = pF->pExpr->x.pList;
82455    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
82456    if( pList ){
82457      nArg = pList->nExpr;
82458      regAgg = sqlite3GetTempRange(pParse, nArg);
82459      sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
82460    }else{
82461      nArg = 0;
82462      regAgg = 0;
82463    }
82464    if( pF->iDistinct>=0 ){
82465      addrNext = sqlite3VdbeMakeLabel(v);
82466      assert( nArg==1 );
82467      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
82468    }
82469    if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
82470      CollSeq *pColl = 0;
82471      struct ExprList_item *pItem;
82472      int j;
82473      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
82474      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
82475        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
82476      }
82477      if( !pColl ){
82478        pColl = pParse->db->pDfltColl;
82479      }
82480      sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
82481    }
82482    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
82483                      (void*)pF->pFunc, P4_FUNCDEF);
82484    sqlite3VdbeChangeP5(v, (u8)nArg);
82485    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
82486    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
82487    if( addrNext ){
82488      sqlite3VdbeResolveLabel(v, addrNext);
82489      sqlite3ExprCacheClear(pParse);
82490    }
82491  }
82492  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
82493    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
82494  }
82495  pAggInfo->directMode = 0;
82496  sqlite3ExprCacheClear(pParse);
82497}
82498
82499/*
82500** Generate code for the SELECT statement given in the p argument.
82501**
82502** The results are distributed in various ways depending on the
82503** contents of the SelectDest structure pointed to by argument pDest
82504** as follows:
82505**
82506**     pDest->eDest    Result
82507**     ------------    -------------------------------------------
82508**     SRT_Output      Generate a row of output (using the OP_ResultRow
82509**                     opcode) for each row in the result set.
82510**
82511**     SRT_Mem         Only valid if the result is a single column.
82512**                     Store the first column of the first result row
82513**                     in register pDest->iParm then abandon the rest
82514**                     of the query.  This destination implies "LIMIT 1".
82515**
82516**     SRT_Set         The result must be a single column.  Store each
82517**                     row of result as the key in table pDest->iParm.
82518**                     Apply the affinity pDest->affinity before storing
82519**                     results.  Used to implement "IN (SELECT ...)".
82520**
82521**     SRT_Union       Store results as a key in a temporary table pDest->iParm.
82522**
82523**     SRT_Except      Remove results from the temporary table pDest->iParm.
82524**
82525**     SRT_Table       Store results in temporary table pDest->iParm.
82526**                     This is like SRT_EphemTab except that the table
82527**                     is assumed to already be open.
82528**
82529**     SRT_EphemTab    Create an temporary table pDest->iParm and store
82530**                     the result there. The cursor is left open after
82531**                     returning.  This is like SRT_Table except that
82532**                     this destination uses OP_OpenEphemeral to create
82533**                     the table first.
82534**
82535**     SRT_Coroutine   Generate a co-routine that returns a new row of
82536**                     results each time it is invoked.  The entry point
82537**                     of the co-routine is stored in register pDest->iParm.
82538**
82539**     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
82540**                     set is not empty.
82541**
82542**     SRT_Discard     Throw the results away.  This is used by SELECT
82543**                     statements within triggers whose only purpose is
82544**                     the side-effects of functions.
82545**
82546** This routine returns the number of errors.  If any errors are
82547** encountered, then an appropriate error message is left in
82548** pParse->zErrMsg.
82549**
82550** This routine does NOT free the Select structure passed in.  The
82551** calling function needs to do that.
82552*/
82553SQLITE_PRIVATE int sqlite3Select(
82554  Parse *pParse,         /* The parser context */
82555  Select *p,             /* The SELECT statement being coded. */
82556  SelectDest *pDest      /* What to do with the query results */
82557){
82558  int i, j;              /* Loop counters */
82559  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
82560  Vdbe *v;               /* The virtual machine under construction */
82561  int isAgg;             /* True for select lists like "count(*)" */
82562  ExprList *pEList;      /* List of columns to extract. */
82563  SrcList *pTabList;     /* List of tables to select from */
82564  Expr *pWhere;          /* The WHERE clause.  May be NULL */
82565  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
82566  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
82567  Expr *pHaving;         /* The HAVING clause.  May be NULL */
82568  int isDistinct;        /* True if the DISTINCT keyword is present */
82569  int distinct;          /* Table to use for the distinct set */
82570  int rc = 1;            /* Value to return from this function */
82571  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
82572  AggInfo sAggInfo;      /* Information used by aggregate queries */
82573  int iEnd;              /* Address of the end of the query */
82574  sqlite3 *db;           /* The database connection */
82575
82576  db = pParse->db;
82577  if( p==0 || db->mallocFailed || pParse->nErr ){
82578    return 1;
82579  }
82580  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
82581  memset(&sAggInfo, 0, sizeof(sAggInfo));
82582
82583  if( IgnorableOrderby(pDest) ){
82584    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
82585           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
82586    /* If ORDER BY makes no difference in the output then neither does
82587    ** DISTINCT so it can be removed too. */
82588    sqlite3ExprListDelete(db, p->pOrderBy);
82589    p->pOrderBy = 0;
82590    p->selFlags &= ~SF_Distinct;
82591  }
82592  sqlite3SelectPrep(pParse, p, 0);
82593  pOrderBy = p->pOrderBy;
82594  pTabList = p->pSrc;
82595  pEList = p->pEList;
82596  if( pParse->nErr || db->mallocFailed ){
82597    goto select_end;
82598  }
82599  isAgg = (p->selFlags & SF_Aggregate)!=0;
82600  assert( pEList!=0 );
82601
82602  /* Begin generating code.
82603  */
82604  v = sqlite3GetVdbe(pParse);
82605  if( v==0 ) goto select_end;
82606
82607  /* Generate code for all sub-queries in the FROM clause
82608  */
82609#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
82610  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
82611    struct SrcList_item *pItem = &pTabList->a[i];
82612    SelectDest dest;
82613    Select *pSub = pItem->pSelect;
82614    int isAggSub;
82615
82616    if( pSub==0 || pItem->isPopulated ) continue;
82617
82618    /* Increment Parse.nHeight by the height of the largest expression
82619    ** tree refered to by this, the parent select. The child select
82620    ** may contain expression trees of at most
82621    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
82622    ** more conservative than necessary, but much easier than enforcing
82623    ** an exact limit.
82624    */
82625    pParse->nHeight += sqlite3SelectExprHeight(p);
82626
82627    /* Check to see if the subquery can be absorbed into the parent. */
82628    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
82629    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
82630      if( isAggSub ){
82631        isAgg = 1;
82632        p->selFlags |= SF_Aggregate;
82633      }
82634      i = -1;
82635    }else{
82636      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
82637      assert( pItem->isPopulated==0 );
82638      sqlite3Select(pParse, pSub, &dest);
82639      pItem->isPopulated = 1;
82640    }
82641    if( /*pParse->nErr ||*/ db->mallocFailed ){
82642      goto select_end;
82643    }
82644    pParse->nHeight -= sqlite3SelectExprHeight(p);
82645    pTabList = p->pSrc;
82646    if( !IgnorableOrderby(pDest) ){
82647      pOrderBy = p->pOrderBy;
82648    }
82649  }
82650  pEList = p->pEList;
82651#endif
82652  pWhere = p->pWhere;
82653  pGroupBy = p->pGroupBy;
82654  pHaving = p->pHaving;
82655  isDistinct = (p->selFlags & SF_Distinct)!=0;
82656
82657#ifndef SQLITE_OMIT_COMPOUND_SELECT
82658  /* If there is are a sequence of queries, do the earlier ones first.
82659  */
82660  if( p->pPrior ){
82661    if( p->pRightmost==0 ){
82662      Select *pLoop, *pRight = 0;
82663      int cnt = 0;
82664      int mxSelect;
82665      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
82666        pLoop->pRightmost = p;
82667        pLoop->pNext = pRight;
82668        pRight = pLoop;
82669      }
82670      mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
82671      if( mxSelect && cnt>mxSelect ){
82672        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
82673        return 1;
82674      }
82675    }
82676    return multiSelect(pParse, p, pDest);
82677  }
82678#endif
82679
82680  /* If writing to memory or generating a set
82681  ** only a single column may be output.
82682  */
82683#ifndef SQLITE_OMIT_SUBQUERY
82684  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
82685    goto select_end;
82686  }
82687#endif
82688
82689  /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
82690  ** GROUP BY might use an index, DISTINCT never does.
82691  */
82692  assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
82693  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
82694    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
82695    pGroupBy = p->pGroupBy;
82696    p->selFlags &= ~SF_Distinct;
82697    isDistinct = 0;
82698  }
82699
82700  /* If there is an ORDER BY clause, then this sorting
82701  ** index might end up being unused if the data can be
82702  ** extracted in pre-sorted order.  If that is the case, then the
82703  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
82704  ** we figure out that the sorting index is not needed.  The addrSortIndex
82705  ** variable is used to facilitate that change.
82706  */
82707  if( pOrderBy ){
82708    KeyInfo *pKeyInfo;
82709    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
82710    pOrderBy->iECursor = pParse->nTab++;
82711    p->addrOpenEphm[2] = addrSortIndex =
82712      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
82713                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
82714                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82715  }else{
82716    addrSortIndex = -1;
82717  }
82718
82719  /* If the output is destined for a temporary table, open that table.
82720  */
82721  if( pDest->eDest==SRT_EphemTab ){
82722    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
82723  }
82724
82725  /* Set the limiter.
82726  */
82727  iEnd = sqlite3VdbeMakeLabel(v);
82728  computeLimitRegisters(pParse, p, iEnd);
82729
82730  /* Open a virtual index to use for the distinct set.
82731  */
82732  if( isDistinct ){
82733    KeyInfo *pKeyInfo;
82734    assert( isAgg || pGroupBy );
82735    distinct = pParse->nTab++;
82736    pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
82737    sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
82738                        (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82739  }else{
82740    distinct = -1;
82741  }
82742
82743  /* Aggregate and non-aggregate queries are handled differently */
82744  if( !isAgg && pGroupBy==0 ){
82745    /* This case is for non-aggregate queries
82746    ** Begin the database scan
82747    */
82748    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
82749    if( pWInfo==0 ) goto select_end;
82750
82751    /* If sorting index that was created by a prior OP_OpenEphemeral
82752    ** instruction ended up not being needed, then change the OP_OpenEphemeral
82753    ** into an OP_Noop.
82754    */
82755    if( addrSortIndex>=0 && pOrderBy==0 ){
82756      sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
82757      p->addrOpenEphm[2] = -1;
82758    }
82759
82760    /* Use the standard inner loop
82761    */
82762    assert(!isDistinct);
82763    selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
82764                    pWInfo->iContinue, pWInfo->iBreak);
82765
82766    /* End the database scan loop.
82767    */
82768    sqlite3WhereEnd(pWInfo);
82769  }else{
82770    /* This is the processing for aggregate queries */
82771    NameContext sNC;    /* Name context for processing aggregate information */
82772    int iAMem;          /* First Mem address for storing current GROUP BY */
82773    int iBMem;          /* First Mem address for previous GROUP BY */
82774    int iUseFlag;       /* Mem address holding flag indicating that at least
82775                        ** one row of the input to the aggregator has been
82776                        ** processed */
82777    int iAbortFlag;     /* Mem address which causes query abort if positive */
82778    int groupBySort;    /* Rows come from source in GROUP BY order */
82779    int addrEnd;        /* End of processing for this SELECT */
82780
82781    /* Remove any and all aliases between the result set and the
82782    ** GROUP BY clause.
82783    */
82784    if( pGroupBy ){
82785      int k;                        /* Loop counter */
82786      struct ExprList_item *pItem;  /* For looping over expression in a list */
82787
82788      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
82789        pItem->iAlias = 0;
82790      }
82791      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
82792        pItem->iAlias = 0;
82793      }
82794    }
82795
82796
82797    /* Create a label to jump to when we want to abort the query */
82798    addrEnd = sqlite3VdbeMakeLabel(v);
82799
82800    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
82801    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
82802    ** SELECT statement.
82803    */
82804    memset(&sNC, 0, sizeof(sNC));
82805    sNC.pParse = pParse;
82806    sNC.pSrcList = pTabList;
82807    sNC.pAggInfo = &sAggInfo;
82808    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
82809    sAggInfo.pGroupBy = pGroupBy;
82810    sqlite3ExprAnalyzeAggList(&sNC, pEList);
82811    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
82812    if( pHaving ){
82813      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
82814    }
82815    sAggInfo.nAccumulator = sAggInfo.nColumn;
82816    for(i=0; i<sAggInfo.nFunc; i++){
82817      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
82818      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
82819    }
82820    if( db->mallocFailed ) goto select_end;
82821
82822    /* Processing for aggregates with GROUP BY is very different and
82823    ** much more complex than aggregates without a GROUP BY.
82824    */
82825    if( pGroupBy ){
82826      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
82827      int j1;             /* A-vs-B comparision jump */
82828      int addrOutputRow;  /* Start of subroutine that outputs a result row */
82829      int regOutputRow;   /* Return address register for output subroutine */
82830      int addrSetAbort;   /* Set the abort flag and return */
82831      int addrTopOfLoop;  /* Top of the input loop */
82832      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
82833      int addrReset;      /* Subroutine for resetting the accumulator */
82834      int regReset;       /* Return address register for reset subroutine */
82835
82836      /* If there is a GROUP BY clause we might need a sorting index to
82837      ** implement it.  Allocate that sorting index now.  If it turns out
82838      ** that we do not need it after all, the OpenEphemeral instruction
82839      ** will be converted into a Noop.
82840      */
82841      sAggInfo.sortingIdx = pParse->nTab++;
82842      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
82843      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
82844          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
82845          0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
82846
82847      /* Initialize memory locations used by GROUP BY aggregate processing
82848      */
82849      iUseFlag = ++pParse->nMem;
82850      iAbortFlag = ++pParse->nMem;
82851      regOutputRow = ++pParse->nMem;
82852      addrOutputRow = sqlite3VdbeMakeLabel(v);
82853      regReset = ++pParse->nMem;
82854      addrReset = sqlite3VdbeMakeLabel(v);
82855      iAMem = pParse->nMem + 1;
82856      pParse->nMem += pGroupBy->nExpr;
82857      iBMem = pParse->nMem + 1;
82858      pParse->nMem += pGroupBy->nExpr;
82859      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
82860      VdbeComment((v, "clear abort flag"));
82861      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
82862      VdbeComment((v, "indicate accumulator empty"));
82863
82864      /* Begin a loop that will extract all source rows in GROUP BY order.
82865      ** This might involve two separate loops with an OP_Sort in between, or
82866      ** it might be a single loop that uses an index to extract information
82867      ** in the right order to begin with.
82868      */
82869      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
82870      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
82871      if( pWInfo==0 ) goto select_end;
82872      if( pGroupBy==0 ){
82873        /* The optimizer is able to deliver rows in group by order so
82874        ** we do not have to sort.  The OP_OpenEphemeral table will be
82875        ** cancelled later because we still need to use the pKeyInfo
82876        */
82877        pGroupBy = p->pGroupBy;
82878        groupBySort = 0;
82879      }else{
82880        /* Rows are coming out in undetermined order.  We have to push
82881        ** each row into a sorting index, terminate the first loop,
82882        ** then loop over the sorting index in order to get the output
82883        ** in sorted order
82884        */
82885        int regBase;
82886        int regRecord;
82887        int nCol;
82888        int nGroupBy;
82889
82890        groupBySort = 1;
82891        nGroupBy = pGroupBy->nExpr;
82892        nCol = nGroupBy + 1;
82893        j = nGroupBy+1;
82894        for(i=0; i<sAggInfo.nColumn; i++){
82895          if( sAggInfo.aCol[i].iSorterColumn>=j ){
82896            nCol++;
82897            j++;
82898          }
82899        }
82900        regBase = sqlite3GetTempRange(pParse, nCol);
82901        sqlite3ExprCacheClear(pParse);
82902        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
82903        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
82904        j = nGroupBy+1;
82905        for(i=0; i<sAggInfo.nColumn; i++){
82906          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
82907          if( pCol->iSorterColumn>=j ){
82908            int r1 = j + regBase;
82909            int r2;
82910
82911            r2 = sqlite3ExprCodeGetColumn(pParse,
82912                               pCol->pTab, pCol->iColumn, pCol->iTable, r1);
82913            if( r1!=r2 ){
82914              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
82915            }
82916            j++;
82917          }
82918        }
82919        regRecord = sqlite3GetTempReg(pParse);
82920        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
82921        sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
82922        sqlite3ReleaseTempReg(pParse, regRecord);
82923        sqlite3ReleaseTempRange(pParse, regBase, nCol);
82924        sqlite3WhereEnd(pWInfo);
82925        sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
82926        VdbeComment((v, "GROUP BY sort"));
82927        sAggInfo.useSortingIdx = 1;
82928        sqlite3ExprCacheClear(pParse);
82929      }
82930
82931      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
82932      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
82933      ** Then compare the current GROUP BY terms against the GROUP BY terms
82934      ** from the previous row currently stored in a0, a1, a2...
82935      */
82936      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
82937      sqlite3ExprCacheClear(pParse);
82938      for(j=0; j<pGroupBy->nExpr; j++){
82939        if( groupBySort ){
82940          sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
82941        }else{
82942          sAggInfo.directMode = 1;
82943          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
82944        }
82945      }
82946      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
82947                          (char*)pKeyInfo, P4_KEYINFO);
82948      j1 = sqlite3VdbeCurrentAddr(v);
82949      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
82950
82951      /* Generate code that runs whenever the GROUP BY changes.
82952      ** Changes in the GROUP BY are detected by the previous code
82953      ** block.  If there were no changes, this block is skipped.
82954      **
82955      ** This code copies current group by terms in b0,b1,b2,...
82956      ** over to a0,a1,a2.  It then calls the output subroutine
82957      ** and resets the aggregate accumulator registers in preparation
82958      ** for the next GROUP BY batch.
82959      */
82960      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
82961      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
82962      VdbeComment((v, "output one row"));
82963      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
82964      VdbeComment((v, "check abort flag"));
82965      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
82966      VdbeComment((v, "reset accumulator"));
82967
82968      /* Update the aggregate accumulators based on the content of
82969      ** the current row
82970      */
82971      sqlite3VdbeJumpHere(v, j1);
82972      updateAccumulator(pParse, &sAggInfo);
82973      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
82974      VdbeComment((v, "indicate data in accumulator"));
82975
82976      /* End of the loop
82977      */
82978      if( groupBySort ){
82979        sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
82980      }else{
82981        sqlite3WhereEnd(pWInfo);
82982        sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
82983      }
82984
82985      /* Output the final row of result
82986      */
82987      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
82988      VdbeComment((v, "output final row"));
82989
82990      /* Jump over the subroutines
82991      */
82992      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
82993
82994      /* Generate a subroutine that outputs a single row of the result
82995      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
82996      ** is less than or equal to zero, the subroutine is a no-op.  If
82997      ** the processing calls for the query to abort, this subroutine
82998      ** increments the iAbortFlag memory location before returning in
82999      ** order to signal the caller to abort.
83000      */
83001      addrSetAbort = sqlite3VdbeCurrentAddr(v);
83002      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
83003      VdbeComment((v, "set abort flag"));
83004      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83005      sqlite3VdbeResolveLabel(v, addrOutputRow);
83006      addrOutputRow = sqlite3VdbeCurrentAddr(v);
83007      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
83008      VdbeComment((v, "Groupby result generator entry point"));
83009      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83010      finalizeAggFunctions(pParse, &sAggInfo);
83011      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
83012      selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
83013                      distinct, pDest,
83014                      addrOutputRow+1, addrSetAbort);
83015      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
83016      VdbeComment((v, "end groupby result generator"));
83017
83018      /* Generate a subroutine that will reset the group-by accumulator
83019      */
83020      sqlite3VdbeResolveLabel(v, addrReset);
83021      resetAccumulator(pParse, &sAggInfo);
83022      sqlite3VdbeAddOp1(v, OP_Return, regReset);
83023
83024    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
83025    else {
83026      ExprList *pDel = 0;
83027#ifndef SQLITE_OMIT_BTREECOUNT
83028      Table *pTab;
83029      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
83030        /* If isSimpleCount() returns a pointer to a Table structure, then
83031        ** the SQL statement is of the form:
83032        **
83033        **   SELECT count(*) FROM <tbl>
83034        **
83035        ** where the Table structure returned represents table <tbl>.
83036        **
83037        ** This statement is so common that it is optimized specially. The
83038        ** OP_Count instruction is executed either on the intkey table that
83039        ** contains the data for table <tbl> or on one of its indexes. It
83040        ** is better to execute the op on an index, as indexes are almost
83041        ** always spread across less pages than their corresponding tables.
83042        */
83043        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83044        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
83045        Index *pIdx;                         /* Iterator variable */
83046        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
83047        Index *pBest = 0;                    /* Best index found so far */
83048        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
83049
83050        sqlite3CodeVerifySchema(pParse, iDb);
83051        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
83052
83053        /* Search for the index that has the least amount of columns. If
83054        ** there is such an index, and it has less columns than the table
83055        ** does, then we can assume that it consumes less space on disk and
83056        ** will therefore be cheaper to scan to determine the query result.
83057        ** In this case set iRoot to the root page number of the index b-tree
83058        ** and pKeyInfo to the KeyInfo structure required to navigate the
83059        ** index.
83060        **
83061        ** In practice the KeyInfo structure will not be used. It is only
83062        ** passed to keep OP_OpenRead happy.
83063        */
83064        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83065          if( !pBest || pIdx->nColumn<pBest->nColumn ){
83066            pBest = pIdx;
83067          }
83068        }
83069        if( pBest && pBest->nColumn<pTab->nCol ){
83070          iRoot = pBest->tnum;
83071          pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
83072        }
83073
83074        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
83075        sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
83076        if( pKeyInfo ){
83077          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
83078        }
83079        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
83080        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
83081      }else
83082#endif /* SQLITE_OMIT_BTREECOUNT */
83083      {
83084        /* Check if the query is of one of the following forms:
83085        **
83086        **   SELECT min(x) FROM ...
83087        **   SELECT max(x) FROM ...
83088        **
83089        ** If it is, then ask the code in where.c to attempt to sort results
83090        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
83091        ** If where.c is able to produce results sorted in this order, then
83092        ** add vdbe code to break out of the processing loop after the
83093        ** first iteration (since the first iteration of the loop is
83094        ** guaranteed to operate on the row with the minimum or maximum
83095        ** value of x, the only row required).
83096        **
83097        ** A special flag must be passed to sqlite3WhereBegin() to slightly
83098        ** modify behaviour as follows:
83099        **
83100        **   + If the query is a "SELECT min(x)", then the loop coded by
83101        **     where.c should not iterate over any values with a NULL value
83102        **     for x.
83103        **
83104        **   + The optimizer code in where.c (the thing that decides which
83105        **     index or indices to use) should place a different priority on
83106        **     satisfying the 'ORDER BY' clause than it does in other cases.
83107        **     Refer to code and comments in where.c for details.
83108        */
83109        ExprList *pMinMax = 0;
83110        u8 flag = minMaxQuery(p);
83111        if( flag ){
83112          assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
83113          pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
83114          pDel = pMinMax;
83115          if( pMinMax && !db->mallocFailed ){
83116            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
83117            pMinMax->a[0].pExpr->op = TK_COLUMN;
83118          }
83119        }
83120
83121        /* This case runs if the aggregate has no GROUP BY clause.  The
83122        ** processing is much simpler since there is only a single row
83123        ** of output.
83124        */
83125        resetAccumulator(pParse, &sAggInfo);
83126        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
83127        if( pWInfo==0 ){
83128          sqlite3ExprListDelete(db, pDel);
83129          goto select_end;
83130        }
83131        updateAccumulator(pParse, &sAggInfo);
83132        if( !pMinMax && flag ){
83133          sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
83134          VdbeComment((v, "%s() by index",
83135                (flag==WHERE_ORDERBY_MIN?"min":"max")));
83136        }
83137        sqlite3WhereEnd(pWInfo);
83138        finalizeAggFunctions(pParse, &sAggInfo);
83139      }
83140
83141      pOrderBy = 0;
83142      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
83143      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
83144                      pDest, addrEnd, addrEnd);
83145      sqlite3ExprListDelete(db, pDel);
83146    }
83147    sqlite3VdbeResolveLabel(v, addrEnd);
83148
83149  } /* endif aggregate query */
83150
83151  /* If there is an ORDER BY clause, then we need to sort the results
83152  ** and send them to the callback one by one.
83153  */
83154  if( pOrderBy ){
83155    generateSortTail(pParse, p, v, pEList->nExpr, pDest);
83156  }
83157
83158  /* Jump here to skip this query
83159  */
83160  sqlite3VdbeResolveLabel(v, iEnd);
83161
83162  /* The SELECT was successfully coded.   Set the return code to 0
83163  ** to indicate no errors.
83164  */
83165  rc = 0;
83166
83167  /* Control jumps to here if an error is encountered above, or upon
83168  ** successful coding of the SELECT.
83169  */
83170select_end:
83171
83172  /* Identify column names if results of the SELECT are to be output.
83173  */
83174  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
83175    generateColumnNames(pParse, pTabList, pEList);
83176  }
83177
83178  sqlite3DbFree(db, sAggInfo.aCol);
83179  sqlite3DbFree(db, sAggInfo.aFunc);
83180  return rc;
83181}
83182
83183#if defined(SQLITE_DEBUG)
83184/*
83185*******************************************************************************
83186** The following code is used for testing and debugging only.  The code
83187** that follows does not appear in normal builds.
83188**
83189** These routines are used to print out the content of all or part of a
83190** parse structures such as Select or Expr.  Such printouts are useful
83191** for helping to understand what is happening inside the code generator
83192** during the execution of complex SELECT statements.
83193**
83194** These routine are not called anywhere from within the normal
83195** code base.  Then are intended to be called from within the debugger
83196** or from temporary "printf" statements inserted for debugging.
83197*/
83198SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
83199  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
83200    sqlite3DebugPrintf("(%s", p->u.zToken);
83201  }else{
83202    sqlite3DebugPrintf("(%d", p->op);
83203  }
83204  if( p->pLeft ){
83205    sqlite3DebugPrintf(" ");
83206    sqlite3PrintExpr(p->pLeft);
83207  }
83208  if( p->pRight ){
83209    sqlite3DebugPrintf(" ");
83210    sqlite3PrintExpr(p->pRight);
83211  }
83212  sqlite3DebugPrintf(")");
83213}
83214SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
83215  int i;
83216  for(i=0; i<pList->nExpr; i++){
83217    sqlite3PrintExpr(pList->a[i].pExpr);
83218    if( i<pList->nExpr-1 ){
83219      sqlite3DebugPrintf(", ");
83220    }
83221  }
83222}
83223SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
83224  sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
83225  sqlite3PrintExprList(p->pEList);
83226  sqlite3DebugPrintf("\n");
83227  if( p->pSrc ){
83228    char *zPrefix;
83229    int i;
83230    zPrefix = "FROM";
83231    for(i=0; i<p->pSrc->nSrc; i++){
83232      struct SrcList_item *pItem = &p->pSrc->a[i];
83233      sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
83234      zPrefix = "";
83235      if( pItem->pSelect ){
83236        sqlite3DebugPrintf("(\n");
83237        sqlite3PrintSelect(pItem->pSelect, indent+10);
83238        sqlite3DebugPrintf("%*s)", indent+8, "");
83239      }else if( pItem->zName ){
83240        sqlite3DebugPrintf("%s", pItem->zName);
83241      }
83242      if( pItem->pTab ){
83243        sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
83244      }
83245      if( pItem->zAlias ){
83246        sqlite3DebugPrintf(" AS %s", pItem->zAlias);
83247      }
83248      if( i<p->pSrc->nSrc-1 ){
83249        sqlite3DebugPrintf(",");
83250      }
83251      sqlite3DebugPrintf("\n");
83252    }
83253  }
83254  if( p->pWhere ){
83255    sqlite3DebugPrintf("%*s WHERE ", indent, "");
83256    sqlite3PrintExpr(p->pWhere);
83257    sqlite3DebugPrintf("\n");
83258  }
83259  if( p->pGroupBy ){
83260    sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
83261    sqlite3PrintExprList(p->pGroupBy);
83262    sqlite3DebugPrintf("\n");
83263  }
83264  if( p->pHaving ){
83265    sqlite3DebugPrintf("%*s HAVING ", indent, "");
83266    sqlite3PrintExpr(p->pHaving);
83267    sqlite3DebugPrintf("\n");
83268  }
83269  if( p->pOrderBy ){
83270    sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
83271    sqlite3PrintExprList(p->pOrderBy);
83272    sqlite3DebugPrintf("\n");
83273  }
83274}
83275/* End of the structure debug printing code
83276*****************************************************************************/
83277#endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
83278
83279/************** End of select.c **********************************************/
83280/************** Begin file table.c *******************************************/
83281/*
83282** 2001 September 15
83283**
83284** The author disclaims copyright to this source code.  In place of
83285** a legal notice, here is a blessing:
83286**
83287**    May you do good and not evil.
83288**    May you find forgiveness for yourself and forgive others.
83289**    May you share freely, never taking more than you give.
83290**
83291*************************************************************************
83292** This file contains the sqlite3_get_table() and sqlite3_free_table()
83293** interface routines.  These are just wrappers around the main
83294** interface routine of sqlite3_exec().
83295**
83296** These routines are in a separate files so that they will not be linked
83297** if they are not used.
83298*/
83299
83300#ifndef SQLITE_OMIT_GET_TABLE
83301
83302/*
83303** This structure is used to pass data from sqlite3_get_table() through
83304** to the callback function is uses to build the result.
83305*/
83306typedef struct TabResult {
83307  char **azResult;   /* Accumulated output */
83308  char *zErrMsg;     /* Error message text, if an error occurs */
83309  int nAlloc;        /* Slots allocated for azResult[] */
83310  int nRow;          /* Number of rows in the result */
83311  int nColumn;       /* Number of columns in the result */
83312  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
83313  int rc;            /* Return code from sqlite3_exec() */
83314} TabResult;
83315
83316/*
83317** This routine is called once for each row in the result table.  Its job
83318** is to fill in the TabResult structure appropriately, allocating new
83319** memory as necessary.
83320*/
83321static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
83322  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
83323  int need;                         /* Slots needed in p->azResult[] */
83324  int i;                            /* Loop counter */
83325  char *z;                          /* A single column of result */
83326
83327  /* Make sure there is enough space in p->azResult to hold everything
83328  ** we need to remember from this invocation of the callback.
83329  */
83330  if( p->nRow==0 && argv!=0 ){
83331    need = nCol*2;
83332  }else{
83333    need = nCol;
83334  }
83335  if( p->nData + need > p->nAlloc ){
83336    char **azNew;
83337    p->nAlloc = p->nAlloc*2 + need;
83338    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
83339    if( azNew==0 ) goto malloc_failed;
83340    p->azResult = azNew;
83341  }
83342
83343  /* If this is the first row, then generate an extra row containing
83344  ** the names of all columns.
83345  */
83346  if( p->nRow==0 ){
83347    p->nColumn = nCol;
83348    for(i=0; i<nCol; i++){
83349      z = sqlite3_mprintf("%s", colv[i]);
83350      if( z==0 ) goto malloc_failed;
83351      p->azResult[p->nData++] = z;
83352    }
83353  }else if( p->nColumn!=nCol ){
83354    sqlite3_free(p->zErrMsg);
83355    p->zErrMsg = sqlite3_mprintf(
83356       "sqlite3_get_table() called with two or more incompatible queries"
83357    );
83358    p->rc = SQLITE_ERROR;
83359    return 1;
83360  }
83361
83362  /* Copy over the row data
83363  */
83364  if( argv!=0 ){
83365    for(i=0; i<nCol; i++){
83366      if( argv[i]==0 ){
83367        z = 0;
83368      }else{
83369        int n = sqlite3Strlen30(argv[i])+1;
83370        z = sqlite3_malloc( n );
83371        if( z==0 ) goto malloc_failed;
83372        memcpy(z, argv[i], n);
83373      }
83374      p->azResult[p->nData++] = z;
83375    }
83376    p->nRow++;
83377  }
83378  return 0;
83379
83380malloc_failed:
83381  p->rc = SQLITE_NOMEM;
83382  return 1;
83383}
83384
83385/*
83386** Query the database.  But instead of invoking a callback for each row,
83387** malloc() for space to hold the result and return the entire results
83388** at the conclusion of the call.
83389**
83390** The result that is written to ***pazResult is held in memory obtained
83391** from malloc().  But the caller cannot free this memory directly.
83392** Instead, the entire table should be passed to sqlite3_free_table() when
83393** the calling procedure is finished using it.
83394*/
83395SQLITE_API int sqlite3_get_table(
83396  sqlite3 *db,                /* The database on which the SQL executes */
83397  const char *zSql,           /* The SQL to be executed */
83398  char ***pazResult,          /* Write the result table here */
83399  int *pnRow,                 /* Write the number of rows in the result here */
83400  int *pnColumn,              /* Write the number of columns of result here */
83401  char **pzErrMsg             /* Write error messages here */
83402){
83403  int rc;
83404  TabResult res;
83405
83406  *pazResult = 0;
83407  if( pnColumn ) *pnColumn = 0;
83408  if( pnRow ) *pnRow = 0;
83409  if( pzErrMsg ) *pzErrMsg = 0;
83410  res.zErrMsg = 0;
83411  res.nRow = 0;
83412  res.nColumn = 0;
83413  res.nData = 1;
83414  res.nAlloc = 20;
83415  res.rc = SQLITE_OK;
83416  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
83417  if( res.azResult==0 ){
83418     db->errCode = SQLITE_NOMEM;
83419     return SQLITE_NOMEM;
83420  }
83421  res.azResult[0] = 0;
83422  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
83423  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
83424  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
83425  if( (rc&0xff)==SQLITE_ABORT ){
83426    sqlite3_free_table(&res.azResult[1]);
83427    if( res.zErrMsg ){
83428      if( pzErrMsg ){
83429        sqlite3_free(*pzErrMsg);
83430        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
83431      }
83432      sqlite3_free(res.zErrMsg);
83433    }
83434    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
83435    return res.rc;
83436  }
83437  sqlite3_free(res.zErrMsg);
83438  if( rc!=SQLITE_OK ){
83439    sqlite3_free_table(&res.azResult[1]);
83440    return rc;
83441  }
83442  if( res.nAlloc>res.nData ){
83443    char **azNew;
83444    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
83445    if( azNew==0 ){
83446      sqlite3_free_table(&res.azResult[1]);
83447      db->errCode = SQLITE_NOMEM;
83448      return SQLITE_NOMEM;
83449    }
83450    res.azResult = azNew;
83451  }
83452  *pazResult = &res.azResult[1];
83453  if( pnColumn ) *pnColumn = res.nColumn;
83454  if( pnRow ) *pnRow = res.nRow;
83455  return rc;
83456}
83457
83458/*
83459** This routine frees the space the sqlite3_get_table() malloced.
83460*/
83461SQLITE_API void sqlite3_free_table(
83462  char **azResult            /* Result returned from from sqlite3_get_table() */
83463){
83464  if( azResult ){
83465    int i, n;
83466    azResult--;
83467    assert( azResult!=0 );
83468    n = SQLITE_PTR_TO_INT(azResult[0]);
83469    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
83470    sqlite3_free(azResult);
83471  }
83472}
83473
83474#endif /* SQLITE_OMIT_GET_TABLE */
83475
83476/************** End of table.c ***********************************************/
83477/************** Begin file trigger.c *****************************************/
83478/*
83479**
83480** The author disclaims copyright to this source code.  In place of
83481** a legal notice, here is a blessing:
83482**
83483**    May you do good and not evil.
83484**    May you find forgiveness for yourself and forgive others.
83485**    May you share freely, never taking more than you give.
83486**
83487*************************************************************************
83488** This file contains the implementation for TRIGGERs
83489*/
83490
83491#ifndef SQLITE_OMIT_TRIGGER
83492/*
83493** Delete a linked list of TriggerStep structures.
83494*/
83495SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
83496  while( pTriggerStep ){
83497    TriggerStep * pTmp = pTriggerStep;
83498    pTriggerStep = pTriggerStep->pNext;
83499
83500    sqlite3ExprDelete(db, pTmp->pWhere);
83501    sqlite3ExprListDelete(db, pTmp->pExprList);
83502    sqlite3SelectDelete(db, pTmp->pSelect);
83503    sqlite3IdListDelete(db, pTmp->pIdList);
83504
83505    sqlite3DbFree(db, pTmp);
83506  }
83507}
83508
83509/*
83510** Given table pTab, return a list of all the triggers attached to
83511** the table. The list is connected by Trigger.pNext pointers.
83512**
83513** All of the triggers on pTab that are in the same database as pTab
83514** are already attached to pTab->pTrigger.  But there might be additional
83515** triggers on pTab in the TEMP schema.  This routine prepends all
83516** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
83517** and returns the combined list.
83518**
83519** To state it another way:  This routine returns a list of all triggers
83520** that fire off of pTab.  The list will include any TEMP triggers on
83521** pTab as well as the triggers lised in pTab->pTrigger.
83522*/
83523SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
83524  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
83525  Trigger *pList = 0;                  /* List of triggers to return */
83526
83527  if( pParse->disableTriggers ){
83528    return 0;
83529  }
83530
83531  if( pTmpSchema!=pTab->pSchema ){
83532    HashElem *p;
83533    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
83534      Trigger *pTrig = (Trigger *)sqliteHashData(p);
83535      if( pTrig->pTabSchema==pTab->pSchema
83536       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
83537      ){
83538        pTrig->pNext = (pList ? pList : pTab->pTrigger);
83539        pList = pTrig;
83540      }
83541    }
83542  }
83543
83544  return (pList ? pList : pTab->pTrigger);
83545}
83546
83547/*
83548** This is called by the parser when it sees a CREATE TRIGGER statement
83549** up to the point of the BEGIN before the trigger actions.  A Trigger
83550** structure is generated based on the information available and stored
83551** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
83552** sqlite3FinishTrigger() function is called to complete the trigger
83553** construction process.
83554*/
83555SQLITE_PRIVATE void sqlite3BeginTrigger(
83556  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
83557  Token *pName1,      /* The name of the trigger */
83558  Token *pName2,      /* The name of the trigger */
83559  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
83560  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
83561  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
83562  SrcList *pTableName,/* The name of the table/view the trigger applies to */
83563  Expr *pWhen,        /* WHEN clause */
83564  int isTemp,         /* True if the TEMPORARY keyword is present */
83565  int noErr           /* Suppress errors if the trigger already exists */
83566){
83567  Trigger *pTrigger = 0;  /* The new trigger */
83568  Table *pTab;            /* Table that the trigger fires off of */
83569  char *zName = 0;        /* Name of the trigger */
83570  sqlite3 *db = pParse->db;  /* The database connection */
83571  int iDb;                /* The database to store the trigger in */
83572  Token *pName;           /* The unqualified db name */
83573  DbFixer sFix;           /* State vector for the DB fixer */
83574  int iTabDb;             /* Index of the database holding pTab */
83575
83576  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
83577  assert( pName2!=0 );
83578  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
83579  assert( op>0 && op<0xff );
83580  if( isTemp ){
83581    /* If TEMP was specified, then the trigger name may not be qualified. */
83582    if( pName2->n>0 ){
83583      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
83584      goto trigger_cleanup;
83585    }
83586    iDb = 1;
83587    pName = pName1;
83588  }else{
83589    /* Figure out the db that the the trigger will be created in */
83590    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83591    if( iDb<0 ){
83592      goto trigger_cleanup;
83593    }
83594  }
83595
83596  /* If the trigger name was unqualified, and the table is a temp table,
83597  ** then set iDb to 1 to create the trigger in the temporary database.
83598  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
83599  ** exist, the error is caught by the block below.
83600  */
83601  if( !pTableName || db->mallocFailed ){
83602    goto trigger_cleanup;
83603  }
83604  pTab = sqlite3SrcListLookup(pParse, pTableName);
83605  if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
83606    iDb = 1;
83607  }
83608
83609  /* Ensure the table name matches database name and that the table exists */
83610  if( db->mallocFailed ) goto trigger_cleanup;
83611  assert( pTableName->nSrc==1 );
83612  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
83613      sqlite3FixSrcList(&sFix, pTableName) ){
83614    goto trigger_cleanup;
83615  }
83616  pTab = sqlite3SrcListLookup(pParse, pTableName);
83617  if( !pTab ){
83618    /* The table does not exist. */
83619    if( db->init.iDb==1 ){
83620      /* Ticket #3810.
83621      ** Normally, whenever a table is dropped, all associated triggers are
83622      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
83623      ** and the table is dropped by a different database connection, the
83624      ** trigger is not visible to the database connection that does the
83625      ** drop so the trigger cannot be dropped.  This results in an
83626      ** "orphaned trigger" - a trigger whose associated table is missing.
83627      */
83628      db->init.orphanTrigger = 1;
83629    }
83630    goto trigger_cleanup;
83631  }
83632  if( IsVirtual(pTab) ){
83633    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
83634    goto trigger_cleanup;
83635  }
83636
83637  /* Check that the trigger name is not reserved and that no trigger of the
83638  ** specified name exists */
83639  zName = sqlite3NameFromToken(db, pName);
83640  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
83641    goto trigger_cleanup;
83642  }
83643  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
83644                      zName, sqlite3Strlen30(zName)) ){
83645    if( !noErr ){
83646      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
83647    }
83648    goto trigger_cleanup;
83649  }
83650
83651  /* Do not create a trigger on a system table */
83652  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
83653    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
83654    pParse->nErr++;
83655    goto trigger_cleanup;
83656  }
83657
83658  /* INSTEAD of triggers are only for views and views only support INSTEAD
83659  ** of triggers.
83660  */
83661  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
83662    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
83663        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
83664    goto trigger_cleanup;
83665  }
83666  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
83667    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
83668        " trigger on table: %S", pTableName, 0);
83669    goto trigger_cleanup;
83670  }
83671  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83672
83673#ifndef SQLITE_OMIT_AUTHORIZATION
83674  {
83675    int code = SQLITE_CREATE_TRIGGER;
83676    const char *zDb = db->aDb[iTabDb].zName;
83677    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
83678    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
83679    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
83680      goto trigger_cleanup;
83681    }
83682    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
83683      goto trigger_cleanup;
83684    }
83685  }
83686#endif
83687
83688  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
83689  ** cannot appear on views.  So we might as well translate every
83690  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
83691  ** elsewhere.
83692  */
83693  if (tr_tm == TK_INSTEAD){
83694    tr_tm = TK_BEFORE;
83695  }
83696
83697  /* Build the Trigger object */
83698  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
83699  if( pTrigger==0 ) goto trigger_cleanup;
83700  pTrigger->zName = zName;
83701  zName = 0;
83702  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
83703  pTrigger->pSchema = db->aDb[iDb].pSchema;
83704  pTrigger->pTabSchema = pTab->pSchema;
83705  pTrigger->op = (u8)op;
83706  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
83707  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
83708  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
83709  assert( pParse->pNewTrigger==0 );
83710  pParse->pNewTrigger = pTrigger;
83711
83712trigger_cleanup:
83713  sqlite3DbFree(db, zName);
83714  sqlite3SrcListDelete(db, pTableName);
83715  sqlite3IdListDelete(db, pColumns);
83716  sqlite3ExprDelete(db, pWhen);
83717  if( !pParse->pNewTrigger ){
83718    sqlite3DeleteTrigger(db, pTrigger);
83719  }else{
83720    assert( pParse->pNewTrigger==pTrigger );
83721  }
83722}
83723
83724/*
83725** This routine is called after all of the trigger actions have been parsed
83726** in order to complete the process of building the trigger.
83727*/
83728SQLITE_PRIVATE void sqlite3FinishTrigger(
83729  Parse *pParse,          /* Parser context */
83730  TriggerStep *pStepList, /* The triggered program */
83731  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
83732){
83733  Trigger *pTrig = pParse->pNewTrigger;    /* Trigger being finished */
83734  char *zName;                             /* Name of trigger */
83735  sqlite3 *db = pParse->db;                /* The database */
83736  DbFixer sFix;
83737  int iDb;                                 /* Database containing the trigger */
83738  Token nameToken;           /* Trigger name for error reporting */
83739
83740  pTrig = pParse->pNewTrigger;
83741  pParse->pNewTrigger = 0;
83742  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
83743  zName = pTrig->zName;
83744  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
83745  pTrig->step_list = pStepList;
83746  while( pStepList ){
83747    pStepList->pTrig = pTrig;
83748    pStepList = pStepList->pNext;
83749  }
83750  nameToken.z = pTrig->zName;
83751  nameToken.n = sqlite3Strlen30(nameToken.z);
83752  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
83753          && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
83754    goto triggerfinish_cleanup;
83755  }
83756
83757  /* if we are not initializing, and this trigger is not on a TEMP table,
83758  ** build the sqlite_master entry
83759  */
83760  if( !db->init.busy ){
83761    Vdbe *v;
83762    char *z;
83763
83764    /* Make an entry in the sqlite_master table */
83765    v = sqlite3GetVdbe(pParse);
83766    if( v==0 ) goto triggerfinish_cleanup;
83767    sqlite3BeginWriteOperation(pParse, 0, iDb);
83768    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
83769    sqlite3NestedParse(pParse,
83770       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
83771       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
83772       pTrig->table, z);
83773    sqlite3DbFree(db, z);
83774    sqlite3ChangeCookie(pParse, iDb);
83775    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
83776        db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
83777    );
83778  }
83779
83780  if( db->init.busy ){
83781    Trigger *pLink = pTrig;
83782    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
83783    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
83784    if( pTrig ){
83785      db->mallocFailed = 1;
83786    }else if( pLink->pSchema==pLink->pTabSchema ){
83787      Table *pTab;
83788      int n = sqlite3Strlen30(pLink->table);
83789      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
83790      assert( pTab!=0 );
83791      pLink->pNext = pTab->pTrigger;
83792      pTab->pTrigger = pLink;
83793    }
83794  }
83795
83796triggerfinish_cleanup:
83797  sqlite3DeleteTrigger(db, pTrig);
83798  assert( !pParse->pNewTrigger );
83799  sqlite3DeleteTriggerStep(db, pStepList);
83800}
83801
83802/*
83803** Turn a SELECT statement (that the pSelect parameter points to) into
83804** a trigger step.  Return a pointer to a TriggerStep structure.
83805**
83806** The parser calls this routine when it finds a SELECT statement in
83807** body of a TRIGGER.
83808*/
83809SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
83810  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
83811  if( pTriggerStep==0 ) {
83812    sqlite3SelectDelete(db, pSelect);
83813    return 0;
83814  }
83815  pTriggerStep->op = TK_SELECT;
83816  pTriggerStep->pSelect = pSelect;
83817  pTriggerStep->orconf = OE_Default;
83818  return pTriggerStep;
83819}
83820
83821/*
83822** Allocate space to hold a new trigger step.  The allocated space
83823** holds both the TriggerStep object and the TriggerStep.target.z string.
83824**
83825** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
83826*/
83827static TriggerStep *triggerStepAllocate(
83828  sqlite3 *db,                /* Database connection */
83829  u8 op,                      /* Trigger opcode */
83830  Token *pName                /* The target name */
83831){
83832  TriggerStep *pTriggerStep;
83833
83834  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
83835  if( pTriggerStep ){
83836    char *z = (char*)&pTriggerStep[1];
83837    memcpy(z, pName->z, pName->n);
83838    pTriggerStep->target.z = z;
83839    pTriggerStep->target.n = pName->n;
83840    pTriggerStep->op = op;
83841  }
83842  return pTriggerStep;
83843}
83844
83845/*
83846** Build a trigger step out of an INSERT statement.  Return a pointer
83847** to the new trigger step.
83848**
83849** The parser calls this routine when it sees an INSERT inside the
83850** body of a trigger.
83851*/
83852SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
83853  sqlite3 *db,        /* The database connection */
83854  Token *pTableName,  /* Name of the table into which we insert */
83855  IdList *pColumn,    /* List of columns in pTableName to insert into */
83856  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
83857  Select *pSelect,    /* A SELECT statement that supplies values */
83858  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
83859){
83860  TriggerStep *pTriggerStep;
83861
83862  assert(pEList == 0 || pSelect == 0);
83863  assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
83864
83865  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
83866  if( pTriggerStep ){
83867    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
83868    pTriggerStep->pIdList = pColumn;
83869    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
83870    pTriggerStep->orconf = orconf;
83871  }else{
83872    sqlite3IdListDelete(db, pColumn);
83873  }
83874  sqlite3ExprListDelete(db, pEList);
83875  sqlite3SelectDelete(db, pSelect);
83876
83877  return pTriggerStep;
83878}
83879
83880/*
83881** Construct a trigger step that implements an UPDATE statement and return
83882** a pointer to that trigger step.  The parser calls this routine when it
83883** sees an UPDATE statement inside the body of a CREATE TRIGGER.
83884*/
83885SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
83886  sqlite3 *db,         /* The database connection */
83887  Token *pTableName,   /* Name of the table to be updated */
83888  ExprList *pEList,    /* The SET clause: list of column and new values */
83889  Expr *pWhere,        /* The WHERE clause */
83890  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
83891){
83892  TriggerStep *pTriggerStep;
83893
83894  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
83895  if( pTriggerStep ){
83896    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
83897    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
83898    pTriggerStep->orconf = orconf;
83899  }
83900  sqlite3ExprListDelete(db, pEList);
83901  sqlite3ExprDelete(db, pWhere);
83902  return pTriggerStep;
83903}
83904
83905/*
83906** Construct a trigger step that implements a DELETE statement and return
83907** a pointer to that trigger step.  The parser calls this routine when it
83908** sees a DELETE statement inside the body of a CREATE TRIGGER.
83909*/
83910SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
83911  sqlite3 *db,            /* Database connection */
83912  Token *pTableName,      /* The table from which rows are deleted */
83913  Expr *pWhere            /* The WHERE clause */
83914){
83915  TriggerStep *pTriggerStep;
83916
83917  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
83918  if( pTriggerStep ){
83919    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
83920    pTriggerStep->orconf = OE_Default;
83921  }
83922  sqlite3ExprDelete(db, pWhere);
83923  return pTriggerStep;
83924}
83925
83926/*
83927** Recursively delete a Trigger structure
83928*/
83929SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
83930  if( pTrigger==0 ) return;
83931  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
83932  sqlite3DbFree(db, pTrigger->zName);
83933  sqlite3DbFree(db, pTrigger->table);
83934  sqlite3ExprDelete(db, pTrigger->pWhen);
83935  sqlite3IdListDelete(db, pTrigger->pColumns);
83936  sqlite3DbFree(db, pTrigger);
83937}
83938
83939/*
83940** This function is called to drop a trigger from the database schema.
83941**
83942** This may be called directly from the parser and therefore identifies
83943** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
83944** same job as this routine except it takes a pointer to the trigger
83945** instead of the trigger name.
83946**/
83947SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
83948  Trigger *pTrigger = 0;
83949  int i;
83950  const char *zDb;
83951  const char *zName;
83952  int nName;
83953  sqlite3 *db = pParse->db;
83954
83955  if( db->mallocFailed ) goto drop_trigger_cleanup;
83956  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83957    goto drop_trigger_cleanup;
83958  }
83959
83960  assert( pName->nSrc==1 );
83961  zDb = pName->a[0].zDatabase;
83962  zName = pName->a[0].zName;
83963  nName = sqlite3Strlen30(zName);
83964  for(i=OMIT_TEMPDB; i<db->nDb; i++){
83965    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
83966    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
83967    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
83968    if( pTrigger ) break;
83969  }
83970  if( !pTrigger ){
83971    if( !noErr ){
83972      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
83973    }
83974    goto drop_trigger_cleanup;
83975  }
83976  sqlite3DropTriggerPtr(pParse, pTrigger);
83977
83978drop_trigger_cleanup:
83979  sqlite3SrcListDelete(db, pName);
83980}
83981
83982/*
83983** Return a pointer to the Table structure for the table that a trigger
83984** is set on.
83985*/
83986static Table *tableOfTrigger(Trigger *pTrigger){
83987  int n = sqlite3Strlen30(pTrigger->table);
83988  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
83989}
83990
83991
83992/*
83993** Drop a trigger given a pointer to that trigger.
83994*/
83995SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
83996  Table   *pTable;
83997  Vdbe *v;
83998  sqlite3 *db = pParse->db;
83999  int iDb;
84000
84001  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
84002  assert( iDb>=0 && iDb<db->nDb );
84003  pTable = tableOfTrigger(pTrigger);
84004  assert( pTable );
84005  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
84006#ifndef SQLITE_OMIT_AUTHORIZATION
84007  {
84008    int code = SQLITE_DROP_TRIGGER;
84009    const char *zDb = db->aDb[iDb].zName;
84010    const char *zTab = SCHEMA_TABLE(iDb);
84011    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
84012    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
84013      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
84014      return;
84015    }
84016  }
84017#endif
84018
84019  /* Generate code to destroy the database record of the trigger.
84020  */
84021  assert( pTable!=0 );
84022  if( (v = sqlite3GetVdbe(pParse))!=0 ){
84023    int base;
84024    static const VdbeOpList dropTrigger[] = {
84025      { OP_Rewind,     0, ADDR(9),  0},
84026      { OP_String8,    0, 1,        0}, /* 1 */
84027      { OP_Column,     0, 1,        2},
84028      { OP_Ne,         2, ADDR(8),  1},
84029      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
84030      { OP_Column,     0, 0,        2},
84031      { OP_Ne,         2, ADDR(8),  1},
84032      { OP_Delete,     0, 0,        0},
84033      { OP_Next,       0, ADDR(1),  0}, /* 8 */
84034    };
84035
84036    sqlite3BeginWriteOperation(pParse, 0, iDb);
84037    sqlite3OpenMasterTable(pParse, iDb);
84038    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
84039    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
84040    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
84041    sqlite3ChangeCookie(pParse, iDb);
84042    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
84043    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
84044    if( pParse->nMem<3 ){
84045      pParse->nMem = 3;
84046    }
84047  }
84048}
84049
84050/*
84051** Remove a trigger from the hash tables of the sqlite* pointer.
84052*/
84053SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
84054  Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
84055  Trigger *pTrigger;
84056  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
84057  if( ALWAYS(pTrigger) ){
84058    if( pTrigger->pSchema==pTrigger->pTabSchema ){
84059      Table *pTab = tableOfTrigger(pTrigger);
84060      Trigger **pp;
84061      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
84062      *pp = (*pp)->pNext;
84063    }
84064    sqlite3DeleteTrigger(db, pTrigger);
84065    db->flags |= SQLITE_InternChanges;
84066  }
84067}
84068
84069/*
84070** pEList is the SET clause of an UPDATE statement.  Each entry
84071** in pEList is of the format <id>=<expr>.  If any of the entries
84072** in pEList have an <id> which matches an identifier in pIdList,
84073** then return TRUE.  If pIdList==NULL, then it is considered a
84074** wildcard that matches anything.  Likewise if pEList==NULL then
84075** it matches anything so always return true.  Return false only
84076** if there is no match.
84077*/
84078static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
84079  int e;
84080  if( pIdList==0 || NEVER(pEList==0) ) return 1;
84081  for(e=0; e<pEList->nExpr; e++){
84082    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
84083  }
84084  return 0;
84085}
84086
84087/*
84088** Return a list of all triggers on table pTab if there exists at least
84089** one trigger that must be fired when an operation of type 'op' is
84090** performed on the table, and, if that operation is an UPDATE, if at
84091** least one of the columns in pChanges is being modified.
84092*/
84093SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
84094  Parse *pParse,          /* Parse context */
84095  Table *pTab,            /* The table the contains the triggers */
84096  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
84097  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
84098  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84099){
84100  int mask = 0;
84101  Trigger *pList = sqlite3TriggerList(pParse, pTab);
84102  Trigger *p;
84103  assert( pList==0 || IsVirtual(pTab)==0 );
84104  for(p=pList; p; p=p->pNext){
84105    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
84106      mask |= p->tr_tm;
84107    }
84108  }
84109  if( pMask ){
84110    *pMask = mask;
84111  }
84112  return (mask ? pList : 0);
84113}
84114
84115/*
84116** Convert the pStep->target token into a SrcList and return a pointer
84117** to that SrcList.
84118**
84119** This routine adds a specific database name, if needed, to the target when
84120** forming the SrcList.  This prevents a trigger in one database from
84121** referring to a target in another database.  An exception is when the
84122** trigger is in TEMP in which case it can refer to any other database it
84123** wants.
84124*/
84125static SrcList *targetSrcList(
84126  Parse *pParse,       /* The parsing context */
84127  TriggerStep *pStep   /* The trigger containing the target token */
84128){
84129  int iDb;             /* Index of the database to use */
84130  SrcList *pSrc;       /* SrcList to be returned */
84131
84132  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
84133  if( pSrc ){
84134    assert( pSrc->nSrc>0 );
84135    assert( pSrc->a!=0 );
84136    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
84137    if( iDb==0 || iDb>=2 ){
84138      sqlite3 *db = pParse->db;
84139      assert( iDb<pParse->db->nDb );
84140      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
84141    }
84142  }
84143  return pSrc;
84144}
84145
84146/*
84147** Generate VDBE code for the statements inside the body of a single
84148** trigger.
84149*/
84150static int codeTriggerProgram(
84151  Parse *pParse,            /* The parser context */
84152  TriggerStep *pStepList,   /* List of statements inside the trigger body */
84153  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
84154){
84155  TriggerStep *pStep;
84156  Vdbe *v = pParse->pVdbe;
84157  sqlite3 *db = pParse->db;
84158
84159  assert( pParse->pTriggerTab && pParse->pToplevel );
84160  assert( pStepList );
84161  assert( v!=0 );
84162  for(pStep=pStepList; pStep; pStep=pStep->pNext){
84163    /* Figure out the ON CONFLICT policy that will be used for this step
84164    ** of the trigger program. If the statement that caused this trigger
84165    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
84166    ** the ON CONFLICT policy that was specified as part of the trigger
84167    ** step statement. Example:
84168    **
84169    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
84170    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
84171    **   END;
84172    **
84173    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
84174    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
84175    */
84176    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
84177
84178    switch( pStep->op ){
84179      case TK_UPDATE: {
84180        sqlite3Update(pParse,
84181          targetSrcList(pParse, pStep),
84182          sqlite3ExprListDup(db, pStep->pExprList, 0),
84183          sqlite3ExprDup(db, pStep->pWhere, 0),
84184          pParse->eOrconf
84185        );
84186        break;
84187      }
84188      case TK_INSERT: {
84189        sqlite3Insert(pParse,
84190          targetSrcList(pParse, pStep),
84191          sqlite3ExprListDup(db, pStep->pExprList, 0),
84192          sqlite3SelectDup(db, pStep->pSelect, 0),
84193          sqlite3IdListDup(db, pStep->pIdList),
84194          pParse->eOrconf
84195        );
84196        break;
84197      }
84198      case TK_DELETE: {
84199        sqlite3DeleteFrom(pParse,
84200          targetSrcList(pParse, pStep),
84201          sqlite3ExprDup(db, pStep->pWhere, 0)
84202        );
84203        break;
84204      }
84205      default: assert( pStep->op==TK_SELECT ); {
84206        SelectDest sDest;
84207        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
84208        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
84209        sqlite3Select(pParse, pSelect, &sDest);
84210        sqlite3SelectDelete(db, pSelect);
84211        break;
84212      }
84213    }
84214    if( pStep->op!=TK_SELECT ){
84215      sqlite3VdbeAddOp0(v, OP_ResetCount);
84216    }
84217  }
84218
84219  return 0;
84220}
84221
84222#ifdef SQLITE_DEBUG
84223/*
84224** This function is used to add VdbeComment() annotations to a VDBE
84225** program. It is not used in production code, only for debugging.
84226*/
84227static const char *onErrorText(int onError){
84228  switch( onError ){
84229    case OE_Abort:    return "abort";
84230    case OE_Rollback: return "rollback";
84231    case OE_Fail:     return "fail";
84232    case OE_Replace:  return "replace";
84233    case OE_Ignore:   return "ignore";
84234    case OE_Default:  return "default";
84235  }
84236  return "n/a";
84237}
84238#endif
84239
84240/*
84241** Parse context structure pFrom has just been used to create a sub-vdbe
84242** (trigger program). If an error has occurred, transfer error information
84243** from pFrom to pTo.
84244*/
84245static void transferParseError(Parse *pTo, Parse *pFrom){
84246  assert( pFrom->zErrMsg==0 || pFrom->nErr );
84247  assert( pTo->zErrMsg==0 || pTo->nErr );
84248  if( pTo->nErr==0 ){
84249    pTo->zErrMsg = pFrom->zErrMsg;
84250    pTo->nErr = pFrom->nErr;
84251  }else{
84252    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
84253  }
84254}
84255
84256/*
84257** Create and populate a new TriggerPrg object with a sub-program
84258** implementing trigger pTrigger with ON CONFLICT policy orconf.
84259*/
84260static TriggerPrg *codeRowTrigger(
84261  Parse *pParse,       /* Current parse context */
84262  Trigger *pTrigger,   /* Trigger to code */
84263  Table *pTab,         /* The table pTrigger is attached to */
84264  int orconf           /* ON CONFLICT policy to code trigger program with */
84265){
84266  Parse *pTop = sqlite3ParseToplevel(pParse);
84267  sqlite3 *db = pParse->db;   /* Database handle */
84268  TriggerPrg *pPrg;           /* Value to return */
84269  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
84270  Vdbe *v;                    /* Temporary VM */
84271  NameContext sNC;            /* Name context for sub-vdbe */
84272  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
84273  Parse *pSubParse;           /* Parse context for sub-vdbe */
84274  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
84275
84276  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
84277
84278  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
84279  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
84280  ** list of the top-level Parse object sooner rather than later.  */
84281  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
84282  if( !pPrg ) return 0;
84283  pPrg->pNext = pTop->pTriggerPrg;
84284  pTop->pTriggerPrg = pPrg;
84285  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
84286  if( !pProgram ) return 0;
84287  pProgram->nRef = 1;
84288  pPrg->pTrigger = pTrigger;
84289  pPrg->orconf = orconf;
84290  pPrg->aColmask[0] = 0xffffffff;
84291  pPrg->aColmask[1] = 0xffffffff;
84292
84293  /* Allocate and populate a new Parse context to use for coding the
84294  ** trigger sub-program.  */
84295  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
84296  if( !pSubParse ) return 0;
84297  memset(&sNC, 0, sizeof(sNC));
84298  sNC.pParse = pSubParse;
84299  pSubParse->db = db;
84300  pSubParse->pTriggerTab = pTab;
84301  pSubParse->pToplevel = pTop;
84302  pSubParse->zAuthContext = pTrigger->zName;
84303  pSubParse->eTriggerOp = pTrigger->op;
84304
84305  v = sqlite3GetVdbe(pSubParse);
84306  if( v ){
84307    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
84308      pTrigger->zName, onErrorText(orconf),
84309      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
84310        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
84311        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
84312        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
84313      pTab->zName
84314    ));
84315#ifndef SQLITE_OMIT_TRACE
84316    sqlite3VdbeChangeP4(v, -1,
84317      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
84318    );
84319#endif
84320
84321    /* If one was specified, code the WHEN clause. If it evaluates to false
84322    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
84323    ** OP_Halt inserted at the end of the program.  */
84324    if( pTrigger->pWhen ){
84325      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
84326      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
84327       && db->mallocFailed==0
84328      ){
84329        iEndTrigger = sqlite3VdbeMakeLabel(v);
84330        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
84331      }
84332      sqlite3ExprDelete(db, pWhen);
84333    }
84334
84335    /* Code the trigger program into the sub-vdbe. */
84336    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
84337
84338    /* Insert an OP_Halt at the end of the sub-program. */
84339    if( iEndTrigger ){
84340      sqlite3VdbeResolveLabel(v, iEndTrigger);
84341    }
84342    sqlite3VdbeAddOp0(v, OP_Halt);
84343    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
84344
84345    transferParseError(pParse, pSubParse);
84346    if( db->mallocFailed==0 ){
84347      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
84348    }
84349    pProgram->nMem = pSubParse->nMem;
84350    pProgram->nCsr = pSubParse->nTab;
84351    pProgram->token = (void *)pTrigger;
84352    pPrg->aColmask[0] = pSubParse->oldmask;
84353    pPrg->aColmask[1] = pSubParse->newmask;
84354    sqlite3VdbeDelete(v);
84355  }
84356
84357  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
84358  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
84359  sqlite3StackFree(db, pSubParse);
84360
84361  return pPrg;
84362}
84363
84364/*
84365** Return a pointer to a TriggerPrg object containing the sub-program for
84366** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
84367** TriggerPrg object exists, a new object is allocated and populated before
84368** being returned.
84369*/
84370static TriggerPrg *getRowTrigger(
84371  Parse *pParse,       /* Current parse context */
84372  Trigger *pTrigger,   /* Trigger to code */
84373  Table *pTab,         /* The table trigger pTrigger is attached to */
84374  int orconf           /* ON CONFLICT algorithm. */
84375){
84376  Parse *pRoot = sqlite3ParseToplevel(pParse);
84377  TriggerPrg *pPrg;
84378
84379  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
84380
84381  /* It may be that this trigger has already been coded (or is in the
84382  ** process of being coded). If this is the case, then an entry with
84383  ** a matching TriggerPrg.pTrigger field will be present somewhere
84384  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
84385  for(pPrg=pRoot->pTriggerPrg;
84386      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
84387      pPrg=pPrg->pNext
84388  );
84389
84390  /* If an existing TriggerPrg could not be located, create a new one. */
84391  if( !pPrg ){
84392    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
84393  }
84394
84395  return pPrg;
84396}
84397
84398/*
84399** Generate code for the trigger program associated with trigger p on
84400** table pTab. The reg, orconf and ignoreJump parameters passed to this
84401** function are the same as those described in the header function for
84402** sqlite3CodeRowTrigger()
84403*/
84404SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
84405  Parse *pParse,       /* Parse context */
84406  Trigger *p,          /* Trigger to code */
84407  Table *pTab,         /* The table to code triggers from */
84408  int reg,             /* Reg array containing OLD.* and NEW.* values */
84409  int orconf,          /* ON CONFLICT policy */
84410  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
84411){
84412  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
84413  TriggerPrg *pPrg;
84414  pPrg = getRowTrigger(pParse, p, pTab, orconf);
84415  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
84416
84417  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
84418  ** is a pointer to the sub-vdbe containing the trigger program.  */
84419  if( pPrg ){
84420    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
84421    pPrg->pProgram->nRef++;
84422    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
84423    VdbeComment(
84424        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
84425
84426    /* Set the P5 operand of the OP_Program instruction to non-zero if
84427    ** recursive invocation of this trigger program is disallowed. Recursive
84428    ** invocation is disallowed if (a) the sub-program is really a trigger,
84429    ** not a foreign key action, and (b) the flag to enable recursive triggers
84430    ** is clear.  */
84431    sqlite3VdbeChangeP5(v, (u8)(p->zName && !(pParse->db->flags&SQLITE_RecTriggers)));
84432  }
84433}
84434
84435/*
84436** This is called to code the required FOR EACH ROW triggers for an operation
84437** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
84438** is given by the op paramater. The tr_tm parameter determines whether the
84439** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
84440** parameter pChanges is passed the list of columns being modified.
84441**
84442** If there are no triggers that fire at the specified time for the specified
84443** operation on pTab, this function is a no-op.
84444**
84445** The reg argument is the address of the first in an array of registers
84446** that contain the values substituted for the new.* and old.* references
84447** in the trigger program. If N is the number of columns in table pTab
84448** (a copy of pTab->nCol), then registers are populated as follows:
84449**
84450**   Register       Contains
84451**   ------------------------------------------------------
84452**   reg+0          OLD.rowid
84453**   reg+1          OLD.* value of left-most column of pTab
84454**   ...            ...
84455**   reg+N          OLD.* value of right-most column of pTab
84456**   reg+N+1        NEW.rowid
84457**   reg+N+2        OLD.* value of left-most column of pTab
84458**   ...            ...
84459**   reg+N+N+1      NEW.* value of right-most column of pTab
84460**
84461** For ON DELETE triggers, the registers containing the NEW.* values will
84462** never be accessed by the trigger program, so they are not allocated or
84463** populated by the caller (there is no data to populate them with anyway).
84464** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
84465** are never accessed, and so are not allocated by the caller. So, for an
84466** ON INSERT trigger, the value passed to this function as parameter reg
84467** is not a readable register, although registers (reg+N) through
84468** (reg+N+N+1) are.
84469**
84470** Parameter orconf is the default conflict resolution algorithm for the
84471** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
84472** is the instruction that control should jump to if a trigger program
84473** raises an IGNORE exception.
84474*/
84475SQLITE_PRIVATE void sqlite3CodeRowTrigger(
84476  Parse *pParse,       /* Parse context */
84477  Trigger *pTrigger,   /* List of triggers on table pTab */
84478  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
84479  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
84480  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
84481  Table *pTab,         /* The table to code triggers from */
84482  int reg,             /* The first in an array of registers (see above) */
84483  int orconf,          /* ON CONFLICT policy */
84484  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
84485){
84486  Trigger *p;          /* Used to iterate through pTrigger list */
84487
84488  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
84489  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
84490  assert( (op==TK_UPDATE)==(pChanges!=0) );
84491
84492  for(p=pTrigger; p; p=p->pNext){
84493
84494    /* Sanity checking:  The schema for the trigger and for the table are
84495    ** always defined.  The trigger must be in the same schema as the table
84496    ** or else it must be a TEMP trigger. */
84497    assert( p->pSchema!=0 );
84498    assert( p->pTabSchema!=0 );
84499    assert( p->pSchema==p->pTabSchema
84500         || p->pSchema==pParse->db->aDb[1].pSchema );
84501
84502    /* Determine whether we should code this trigger */
84503    if( p->op==op
84504     && p->tr_tm==tr_tm
84505     && checkColumnOverlap(p->pColumns, pChanges)
84506    ){
84507      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
84508    }
84509  }
84510}
84511
84512/*
84513** Triggers may access values stored in the old.* or new.* pseudo-table.
84514** This function returns a 32-bit bitmask indicating which columns of the
84515** old.* or new.* tables actually are used by triggers. This information
84516** may be used by the caller, for example, to avoid having to load the entire
84517** old.* record into memory when executing an UPDATE or DELETE command.
84518**
84519** Bit 0 of the returned mask is set if the left-most column of the
84520** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
84521** the second leftmost column value is required, and so on. If there
84522** are more than 32 columns in the table, and at least one of the columns
84523** with an index greater than 32 may be accessed, 0xffffffff is returned.
84524**
84525** It is not possible to determine if the old.rowid or new.rowid column is
84526** accessed by triggers. The caller must always assume that it is.
84527**
84528** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
84529** applies to the old.* table. If 1, the new.* table.
84530**
84531** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
84532** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
84533** included in the returned mask if the TRIGGER_BEFORE bit is set in the
84534** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
84535** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
84536*/
84537SQLITE_PRIVATE u32 sqlite3TriggerColmask(
84538  Parse *pParse,       /* Parse context */
84539  Trigger *pTrigger,   /* List of triggers on table pTab */
84540  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
84541  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
84542  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84543  Table *pTab,         /* The table to code triggers from */
84544  int orconf           /* Default ON CONFLICT policy for trigger steps */
84545){
84546  const int op = pChanges ? TK_UPDATE : TK_DELETE;
84547  u32 mask = 0;
84548  Trigger *p;
84549
84550  assert( isNew==1 || isNew==0 );
84551  for(p=pTrigger; p; p=p->pNext){
84552    if( p->op==op && (tr_tm&p->tr_tm)
84553     && checkColumnOverlap(p->pColumns,pChanges)
84554    ){
84555      TriggerPrg *pPrg;
84556      pPrg = getRowTrigger(pParse, p, pTab, orconf);
84557      if( pPrg ){
84558        mask |= pPrg->aColmask[isNew];
84559      }
84560    }
84561  }
84562
84563  return mask;
84564}
84565
84566#endif /* !defined(SQLITE_OMIT_TRIGGER) */
84567
84568/************** End of trigger.c *********************************************/
84569/************** Begin file update.c ******************************************/
84570/*
84571** 2001 September 15
84572**
84573** The author disclaims copyright to this source code.  In place of
84574** a legal notice, here is a blessing:
84575**
84576**    May you do good and not evil.
84577**    May you find forgiveness for yourself and forgive others.
84578**    May you share freely, never taking more than you give.
84579**
84580*************************************************************************
84581** This file contains C code routines that are called by the parser
84582** to handle UPDATE statements.
84583*/
84584
84585#ifndef SQLITE_OMIT_VIRTUALTABLE
84586/* Forward declaration */
84587static void updateVirtualTable(
84588  Parse *pParse,       /* The parsing context */
84589  SrcList *pSrc,       /* The virtual table to be modified */
84590  Table *pTab,         /* The virtual table */
84591  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
84592  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
84593  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
84594  Expr *pWhere         /* WHERE clause of the UPDATE statement */
84595);
84596#endif /* SQLITE_OMIT_VIRTUALTABLE */
84597
84598/*
84599** The most recently coded instruction was an OP_Column to retrieve the
84600** i-th column of table pTab. This routine sets the P4 parameter of the
84601** OP_Column to the default value, if any.
84602**
84603** The default value of a column is specified by a DEFAULT clause in the
84604** column definition. This was either supplied by the user when the table
84605** was created, or added later to the table definition by an ALTER TABLE
84606** command. If the latter, then the row-records in the table btree on disk
84607** may not contain a value for the column and the default value, taken
84608** from the P4 parameter of the OP_Column instruction, is returned instead.
84609** If the former, then all row-records are guaranteed to include a value
84610** for the column and the P4 value is not required.
84611**
84612** Column definitions created by an ALTER TABLE command may only have
84613** literal default values specified: a number, null or a string. (If a more
84614** complicated default expression value was provided, it is evaluated
84615** when the ALTER TABLE is executed and one of the literal values written
84616** into the sqlite_master table.)
84617**
84618** Therefore, the P4 parameter is only required if the default value for
84619** the column is a literal number, string or null. The sqlite3ValueFromExpr()
84620** function is capable of transforming these types of expressions into
84621** sqlite3_value objects.
84622**
84623** If parameter iReg is not negative, code an OP_RealAffinity instruction
84624** on register iReg. This is used when an equivalent integer value is
84625** stored in place of an 8-byte floating point value in order to save
84626** space.
84627*/
84628SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
84629  assert( pTab!=0 );
84630  if( !pTab->pSelect ){
84631    sqlite3_value *pValue;
84632    u8 enc = ENC(sqlite3VdbeDb(v));
84633    Column *pCol = &pTab->aCol[i];
84634    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
84635    assert( i<pTab->nCol );
84636    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
84637                         pCol->affinity, &pValue);
84638    if( pValue ){
84639      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
84640    }
84641#ifndef SQLITE_OMIT_FLOATING_POINT
84642    if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
84643      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
84644    }
84645#endif
84646  }
84647}
84648
84649/*
84650** Process an UPDATE statement.
84651**
84652**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
84653**          \_______/ \________/     \______/       \________________/
84654*            onError   pTabList      pChanges             pWhere
84655*/
84656SQLITE_PRIVATE void sqlite3Update(
84657  Parse *pParse,         /* The parser context */
84658  SrcList *pTabList,     /* The table in which we should change things */
84659  ExprList *pChanges,    /* Things to be changed */
84660  Expr *pWhere,          /* The WHERE clause.  May be null */
84661  int onError            /* How to handle constraint errors */
84662){
84663  int i, j;              /* Loop counters */
84664  Table *pTab;           /* The table to be updated */
84665  int addr = 0;          /* VDBE instruction address of the start of the loop */
84666  WhereInfo *pWInfo;     /* Information about the WHERE clause */
84667  Vdbe *v;               /* The virtual database engine */
84668  Index *pIdx;           /* For looping over indices */
84669  int nIdx;              /* Number of indices that need updating */
84670  int iCur;              /* VDBE Cursor number of pTab */
84671  sqlite3 *db;           /* The database structure */
84672  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
84673  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
84674                         ** an expression for the i-th column of the table.
84675                         ** aXRef[i]==-1 if the i-th column is not changed. */
84676  int chngRowid;         /* True if the record number is being changed */
84677  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
84678  int openAll = 0;       /* True if all indices need to be opened */
84679  AuthContext sContext;  /* The authorization context */
84680  NameContext sNC;       /* The name-context to resolve expressions in */
84681  int iDb;               /* Database containing the table being updated */
84682  int okOnePass;         /* True for one-pass algorithm without the FIFO */
84683  int hasFK;             /* True if foreign key processing is required */
84684
84685#ifndef SQLITE_OMIT_TRIGGER
84686  int isView;            /* True when updating a view (INSTEAD OF trigger) */
84687  Trigger *pTrigger;     /* List of triggers on pTab, if required */
84688  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
84689#endif
84690  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
84691
84692  /* Register Allocations */
84693  int regRowCount = 0;   /* A count of rows changed */
84694  int regOldRowid;       /* The old rowid */
84695  int regNewRowid;       /* The new rowid */
84696  int regNew;
84697  int regOld = 0;
84698  int regRowSet = 0;     /* Rowset of rows to be updated */
84699  int regRec;            /* Register used for new table record to insert */
84700
84701  memset(&sContext, 0, sizeof(sContext));
84702  db = pParse->db;
84703  if( pParse->nErr || db->mallocFailed ){
84704    goto update_cleanup;
84705  }
84706  assert( pTabList->nSrc==1 );
84707
84708  /* Locate the table which we want to update.
84709  */
84710  pTab = sqlite3SrcListLookup(pParse, pTabList);
84711  if( pTab==0 ) goto update_cleanup;
84712  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84713
84714  /* Figure out if we have any triggers and if the table being
84715  ** updated is a view.
84716  */
84717#ifndef SQLITE_OMIT_TRIGGER
84718  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
84719  isView = pTab->pSelect!=0;
84720  assert( pTrigger || tmask==0 );
84721#else
84722# define pTrigger 0
84723# define isView 0
84724# define tmask 0
84725#endif
84726#ifdef SQLITE_OMIT_VIEW
84727# undef isView
84728# define isView 0
84729#endif
84730
84731  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
84732    goto update_cleanup;
84733  }
84734  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
84735    goto update_cleanup;
84736  }
84737  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
84738  if( aXRef==0 ) goto update_cleanup;
84739  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
84740
84741  /* Allocate a cursors for the main database table and for all indices.
84742  ** The index cursors might not be used, but if they are used they
84743  ** need to occur right after the database cursor.  So go ahead and
84744  ** allocate enough space, just in case.
84745  */
84746  pTabList->a[0].iCursor = iCur = pParse->nTab++;
84747  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84748    pParse->nTab++;
84749  }
84750
84751  /* Initialize the name-context */
84752  memset(&sNC, 0, sizeof(sNC));
84753  sNC.pParse = pParse;
84754  sNC.pSrcList = pTabList;
84755
84756  /* Resolve the column names in all the expressions of the
84757  ** of the UPDATE statement.  Also find the column index
84758  ** for each column to be updated in the pChanges array.  For each
84759  ** column to be updated, make sure we have authorization to change
84760  ** that column.
84761  */
84762  chngRowid = 0;
84763  for(i=0; i<pChanges->nExpr; i++){
84764    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
84765      goto update_cleanup;
84766    }
84767    for(j=0; j<pTab->nCol; j++){
84768      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
84769        if( j==pTab->iPKey ){
84770          chngRowid = 1;
84771          pRowidExpr = pChanges->a[i].pExpr;
84772        }
84773        aXRef[j] = i;
84774        break;
84775      }
84776    }
84777    if( j>=pTab->nCol ){
84778      if( sqlite3IsRowid(pChanges->a[i].zName) ){
84779        chngRowid = 1;
84780        pRowidExpr = pChanges->a[i].pExpr;
84781      }else{
84782        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
84783        goto update_cleanup;
84784      }
84785    }
84786#ifndef SQLITE_OMIT_AUTHORIZATION
84787    {
84788      int rc;
84789      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
84790                           pTab->aCol[j].zName, db->aDb[iDb].zName);
84791      if( rc==SQLITE_DENY ){
84792        goto update_cleanup;
84793      }else if( rc==SQLITE_IGNORE ){
84794        aXRef[j] = -1;
84795      }
84796    }
84797#endif
84798  }
84799
84800  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
84801
84802  /* Allocate memory for the array aRegIdx[].  There is one entry in the
84803  ** array for each index associated with table being updated.  Fill in
84804  ** the value with a register number for indices that are to be used
84805  ** and with zero for unused indices.
84806  */
84807  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
84808  if( nIdx>0 ){
84809    aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
84810    if( aRegIdx==0 ) goto update_cleanup;
84811  }
84812  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
84813    int reg;
84814    if( chngRowid ){
84815      reg = ++pParse->nMem;
84816    }else{
84817      reg = 0;
84818      for(i=0; i<pIdx->nColumn; i++){
84819        if( aXRef[pIdx->aiColumn[i]]>=0 ){
84820          reg = ++pParse->nMem;
84821          break;
84822        }
84823      }
84824    }
84825    aRegIdx[j] = reg;
84826  }
84827
84828  /* Begin generating code. */
84829  v = sqlite3GetVdbe(pParse);
84830  if( v==0 ) goto update_cleanup;
84831  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
84832  sqlite3BeginWriteOperation(pParse, 1, iDb);
84833
84834#ifndef SQLITE_OMIT_VIRTUALTABLE
84835  /* Virtual tables must be handled separately */
84836  if( IsVirtual(pTab) ){
84837    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
84838                       pWhere);
84839    pWhere = 0;
84840    pTabList = 0;
84841    goto update_cleanup;
84842  }
84843#endif
84844
84845  /* Allocate required registers. */
84846  regOldRowid = regNewRowid = ++pParse->nMem;
84847  if( pTrigger || hasFK ){
84848    regOld = pParse->nMem + 1;
84849    pParse->nMem += pTab->nCol;
84850  }
84851  if( chngRowid || pTrigger || hasFK ){
84852    regNewRowid = ++pParse->nMem;
84853  }
84854  regNew = pParse->nMem + 1;
84855  pParse->nMem += pTab->nCol;
84856  regRec = ++pParse->nMem;
84857
84858  /* Start the view context. */
84859  if( isView ){
84860    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
84861  }
84862
84863  /* If we are trying to update a view, realize that view into
84864  ** a ephemeral table.
84865  */
84866#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
84867  if( isView ){
84868    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
84869  }
84870#endif
84871
84872  /* Resolve the column names in all the expressions in the
84873  ** WHERE clause.
84874  */
84875  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
84876    goto update_cleanup;
84877  }
84878
84879  /* Begin the database scan
84880  */
84881  sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
84882  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
84883  if( pWInfo==0 ) goto update_cleanup;
84884  okOnePass = pWInfo->okOnePass;
84885
84886  /* Remember the rowid of every item to be updated.
84887  */
84888  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
84889  if( !okOnePass ){
84890    regRowSet = ++pParse->nMem;
84891    sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
84892  }
84893
84894  /* End the database scan loop.
84895  */
84896  sqlite3WhereEnd(pWInfo);
84897
84898  /* Initialize the count of updated rows
84899  */
84900  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
84901    regRowCount = ++pParse->nMem;
84902    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
84903  }
84904
84905  if( !isView ){
84906    /*
84907    ** Open every index that needs updating.  Note that if any
84908    ** index could potentially invoke a REPLACE conflict resolution
84909    ** action, then we need to open all indices because we might need
84910    ** to be deleting some records.
84911    */
84912    if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
84913    if( onError==OE_Replace ){
84914      openAll = 1;
84915    }else{
84916      openAll = 0;
84917      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84918        if( pIdx->onError==OE_Replace ){
84919          openAll = 1;
84920          break;
84921        }
84922      }
84923    }
84924    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
84925      if( openAll || aRegIdx[i]>0 ){
84926        KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
84927        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
84928                       (char*)pKey, P4_KEYINFO_HANDOFF);
84929        assert( pParse->nTab>iCur+i+1 );
84930      }
84931    }
84932  }
84933
84934  /* Top of the update loop */
84935  if( okOnePass ){
84936    int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
84937    addr = sqlite3VdbeAddOp0(v, OP_Goto);
84938    sqlite3VdbeJumpHere(v, a1);
84939  }else{
84940    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
84941  }
84942
84943  /* Make cursor iCur point to the record that is being updated. If
84944  ** this record does not exist for some reason (deleted by a trigger,
84945  ** for example, then jump to the next iteration of the RowSet loop.  */
84946  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
84947
84948  /* If the record number will change, set register regNewRowid to
84949  ** contain the new value. If the record number is not being modified,
84950  ** then regNewRowid is the same register as regOldRowid, which is
84951  ** already populated.  */
84952  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
84953  if( chngRowid ){
84954    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
84955    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
84956  }
84957
84958  /* If there are triggers on this table, populate an array of registers
84959  ** with the required old.* column data.  */
84960  if( hasFK || pTrigger ){
84961    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
84962    oldmask |= sqlite3TriggerColmask(pParse,
84963        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
84964    );
84965    for(i=0; i<pTab->nCol; i++){
84966      if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
84967        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regOld+i);
84968        sqlite3ColumnDefault(v, pTab, i, regOld+i);
84969      }else{
84970        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
84971      }
84972    }
84973    if( chngRowid==0 ){
84974      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
84975    }
84976  }
84977
84978  /* Populate the array of registers beginning at regNew with the new
84979  ** row data. This array is used to check constaints, create the new
84980  ** table and index records, and as the values for any new.* references
84981  ** made by triggers.
84982  **
84983  ** If there are one or more BEFORE triggers, then do not populate the
84984  ** registers associated with columns that are (a) not modified by
84985  ** this UPDATE statement and (b) not accessed by new.* references. The
84986  ** values for registers not modified by the UPDATE must be reloaded from
84987  ** the database after the BEFORE triggers are fired anyway (as the trigger
84988  ** may have modified them). So not loading those that are not going to
84989  ** be used eliminates some redundant opcodes.
84990  */
84991  newmask = sqlite3TriggerColmask(
84992      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
84993  );
84994  for(i=0; i<pTab->nCol; i++){
84995    if( i==pTab->iPKey ){
84996      sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
84997    }else{
84998      j = aXRef[i];
84999      if( j>=0 ){
85000        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
85001      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
85002        /* This branch loads the value of a column that will not be changed
85003        ** into a register. This is done if there are no BEFORE triggers, or
85004        ** if there are one or more BEFORE triggers that use this value via
85005        ** a new.* reference in a trigger program.
85006        */
85007        testcase( i==31 );
85008        testcase( i==32 );
85009        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
85010        sqlite3ColumnDefault(v, pTab, i, regNew+i);
85011      }
85012    }
85013  }
85014
85015  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
85016  ** verified. One could argue that this is wrong.
85017  */
85018  if( tmask&TRIGGER_BEFORE ){
85019    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
85020    sqlite3TableAffinityStr(v, pTab);
85021    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
85022        TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
85023
85024    /* The row-trigger may have deleted the row being updated. In this
85025    ** case, jump to the next row. No updates or AFTER triggers are
85026    ** required. This behaviour - what happens when the row being updated
85027    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
85028    ** documentation.
85029    */
85030    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
85031
85032    /* If it did not delete it, the row-trigger may still have modified
85033    ** some of the columns of the row being updated. Load the values for
85034    ** all columns not modified by the update statement into their
85035    ** registers in case this has happened.
85036    */
85037    for(i=0; i<pTab->nCol; i++){
85038      if( aXRef[i]<0 && i!=pTab->iPKey ){
85039        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
85040        sqlite3ColumnDefault(v, pTab, i, regNew+i);
85041      }
85042    }
85043  }
85044
85045  if( !isView ){
85046    int j1;                       /* Address of jump instruction */
85047
85048    /* Do constraint checks. */
85049    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
85050        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
85051
85052    /* Do FK constraint checks. */
85053    if( hasFK ){
85054      sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
85055    }
85056
85057    /* Delete the index entries associated with the current record.  */
85058    j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
85059    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
85060
85061    /* If changing the record number, delete the old record.  */
85062    if( hasFK || chngRowid ){
85063      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
85064    }
85065    sqlite3VdbeJumpHere(v, j1);
85066
85067    if( hasFK ){
85068      sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
85069    }
85070
85071    /* Insert the new index entries and the new record. */
85072    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
85073
85074    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
85075    ** handle rows (possibly in other tables) that refer via a foreign key
85076    ** to the row just updated. */
85077    if( hasFK ){
85078      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
85079    }
85080  }
85081
85082  /* Increment the row counter
85083  */
85084  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
85085    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
85086  }
85087
85088  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
85089      TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
85090
85091  /* Repeat the above with the next record to be updated, until
85092  ** all record selected by the WHERE clause have been updated.
85093  */
85094  sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
85095  sqlite3VdbeJumpHere(v, addr);
85096
85097  /* Close all tables */
85098  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
85099    if( openAll || aRegIdx[i]>0 ){
85100      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
85101    }
85102  }
85103  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
85104
85105  /* Update the sqlite_sequence table by storing the content of the
85106  ** maximum rowid counter values recorded while inserting into
85107  ** autoincrement tables.
85108  */
85109  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85110    sqlite3AutoincrementEnd(pParse);
85111  }
85112
85113  /*
85114  ** Return the number of rows that were changed. If this routine is
85115  ** generating code because of a call to sqlite3NestedParse(), do not
85116  ** invoke the callback function.
85117  */
85118  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
85119    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
85120    sqlite3VdbeSetNumCols(v, 1);
85121    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
85122  }
85123
85124update_cleanup:
85125  sqlite3AuthContextPop(&sContext);
85126  sqlite3DbFree(db, aRegIdx);
85127  sqlite3DbFree(db, aXRef);
85128  sqlite3SrcListDelete(db, pTabList);
85129  sqlite3ExprListDelete(db, pChanges);
85130  sqlite3ExprDelete(db, pWhere);
85131  return;
85132}
85133/* Make sure "isView" and other macros defined above are undefined. Otherwise
85134** thely may interfere with compilation of other functions in this file
85135** (or in another file, if this file becomes part of the amalgamation).  */
85136#ifdef isView
85137 #undef isView
85138#endif
85139#ifdef pTrigger
85140 #undef pTrigger
85141#endif
85142
85143#ifndef SQLITE_OMIT_VIRTUALTABLE
85144/*
85145** Generate code for an UPDATE of a virtual table.
85146**
85147** The strategy is that we create an ephemerial table that contains
85148** for each row to be changed:
85149**
85150**   (A)  The original rowid of that row.
85151**   (B)  The revised rowid for the row. (note1)
85152**   (C)  The content of every column in the row.
85153**
85154** Then we loop over this ephemeral table and for each row in
85155** the ephermeral table call VUpdate.
85156**
85157** When finished, drop the ephemeral table.
85158**
85159** (note1) Actually, if we know in advance that (A) is always the same
85160** as (B) we only store (A), then duplicate (A) when pulling
85161** it out of the ephemeral table before calling VUpdate.
85162*/
85163static void updateVirtualTable(
85164  Parse *pParse,       /* The parsing context */
85165  SrcList *pSrc,       /* The virtual table to be modified */
85166  Table *pTab,         /* The virtual table */
85167  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
85168  Expr *pRowid,        /* Expression used to recompute the rowid */
85169  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
85170  Expr *pWhere         /* WHERE clause of the UPDATE statement */
85171){
85172  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
85173  ExprList *pEList = 0;     /* The result set of the SELECT statement */
85174  Select *pSelect = 0;      /* The SELECT statement */
85175  Expr *pExpr;              /* Temporary expression */
85176  int ephemTab;             /* Table holding the result of the SELECT */
85177  int i;                    /* Loop counter */
85178  int addr;                 /* Address of top of loop */
85179  int iReg;                 /* First register in set passed to OP_VUpdate */
85180  sqlite3 *db = pParse->db; /* Database connection */
85181  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
85182  SelectDest dest;
85183
85184  /* Construct the SELECT statement that will find the new values for
85185  ** all updated rows.
85186  */
85187  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
85188  if( pRowid ){
85189    pEList = sqlite3ExprListAppend(pParse, pEList,
85190                                   sqlite3ExprDup(db, pRowid, 0));
85191  }
85192  assert( pTab->iPKey<0 );
85193  for(i=0; i<pTab->nCol; i++){
85194    if( aXRef[i]>=0 ){
85195      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
85196    }else{
85197      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
85198    }
85199    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
85200  }
85201  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
85202
85203  /* Create the ephemeral table into which the update results will
85204  ** be stored.
85205  */
85206  assert( v );
85207  ephemTab = pParse->nTab++;
85208  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
85209
85210  /* fill the ephemeral table
85211  */
85212  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
85213  sqlite3Select(pParse, pSelect, &dest);
85214
85215  /* Generate code to scan the ephemeral table and call VUpdate. */
85216  iReg = ++pParse->nMem;
85217  pParse->nMem += pTab->nCol+1;
85218  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
85219  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
85220  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
85221  for(i=0; i<pTab->nCol; i++){
85222    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
85223  }
85224  sqlite3VtabMakeWritable(pParse, pTab);
85225  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
85226  sqlite3MayAbort(pParse);
85227  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
85228  sqlite3VdbeJumpHere(v, addr);
85229  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
85230
85231  /* Cleanup */
85232  sqlite3SelectDelete(db, pSelect);
85233}
85234#endif /* SQLITE_OMIT_VIRTUALTABLE */
85235
85236/************** End of update.c **********************************************/
85237/************** Begin file vacuum.c ******************************************/
85238/*
85239** 2003 April 6
85240**
85241** The author disclaims copyright to this source code.  In place of
85242** a legal notice, here is a blessing:
85243**
85244**    May you do good and not evil.
85245**    May you find forgiveness for yourself and forgive others.
85246**    May you share freely, never taking more than you give.
85247**
85248*************************************************************************
85249** This file contains code used to implement the VACUUM command.
85250**
85251** Most of the code in this file may be omitted by defining the
85252** SQLITE_OMIT_VACUUM macro.
85253*/
85254
85255#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
85256/*
85257** Execute zSql on database db. Return an error code.
85258*/
85259static int execSql(sqlite3 *db, const char *zSql){
85260  sqlite3_stmt *pStmt;
85261  VVA_ONLY( int rc; )
85262  if( !zSql ){
85263    return SQLITE_NOMEM;
85264  }
85265  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
85266    return sqlite3_errcode(db);
85267  }
85268  VVA_ONLY( rc = ) sqlite3_step(pStmt);
85269  assert( rc!=SQLITE_ROW );
85270  return sqlite3_finalize(pStmt);
85271}
85272
85273/*
85274** Execute zSql on database db. The statement returns exactly
85275** one column. Execute this as SQL on the same database.
85276*/
85277static int execExecSql(sqlite3 *db, const char *zSql){
85278  sqlite3_stmt *pStmt;
85279  int rc;
85280
85281  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
85282  if( rc!=SQLITE_OK ) return rc;
85283
85284  while( SQLITE_ROW==sqlite3_step(pStmt) ){
85285    rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
85286    if( rc!=SQLITE_OK ){
85287      sqlite3_finalize(pStmt);
85288      return rc;
85289    }
85290  }
85291
85292  return sqlite3_finalize(pStmt);
85293}
85294
85295/*
85296** The non-standard VACUUM command is used to clean up the database,
85297** collapse free space, etc.  It is modelled after the VACUUM command
85298** in PostgreSQL.
85299**
85300** In version 1.0.x of SQLite, the VACUUM command would call
85301** gdbm_reorganize() on all the database tables.  But beginning
85302** with 2.0.0, SQLite no longer uses GDBM so this command has
85303** become a no-op.
85304*/
85305SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
85306  Vdbe *v = sqlite3GetVdbe(pParse);
85307  if( v ){
85308    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
85309  }
85310  return;
85311}
85312
85313/*
85314** This routine implements the OP_Vacuum opcode of the VDBE.
85315*/
85316SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
85317  int rc = SQLITE_OK;     /* Return code from service routines */
85318  Btree *pMain;           /* The database being vacuumed */
85319  Btree *pTemp;           /* The temporary database we vacuum into */
85320  char *zSql = 0;         /* SQL statements */
85321  int saved_flags;        /* Saved value of the db->flags */
85322  int saved_nChange;      /* Saved value of db->nChange */
85323  int saved_nTotalChange; /* Saved value of db->nTotalChange */
85324  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
85325  Db *pDb = 0;            /* Database to detach at end of vacuum */
85326  int isMemDb;            /* True if vacuuming a :memory: database */
85327  int nRes;
85328
85329  if( !db->autoCommit ){
85330    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
85331    return SQLITE_ERROR;
85332  }
85333
85334  /* Save the current value of the database flags so that it can be
85335  ** restored before returning. Then set the writable-schema flag, and
85336  ** disable CHECK and foreign key constraints.  */
85337  saved_flags = db->flags;
85338  saved_nChange = db->nChange;
85339  saved_nTotalChange = db->nTotalChange;
85340  saved_xTrace = db->xTrace;
85341  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
85342  db->flags &= ~SQLITE_ForeignKeys;
85343  db->xTrace = 0;
85344
85345  pMain = db->aDb[0].pBt;
85346  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
85347
85348  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
85349  ** can be set to 'off' for this file, as it is not recovered if a crash
85350  ** occurs anyway. The integrity of the database is maintained by a
85351  ** (possibly synchronous) transaction opened on the main database before
85352  ** sqlite3BtreeCopyFile() is called.
85353  **
85354  ** An optimisation would be to use a non-journaled pager.
85355  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
85356  ** that actually made the VACUUM run slower.  Very little journalling
85357  ** actually occurs when doing a vacuum since the vacuum_db is initially
85358  ** empty.  Only the journal header is written.  Apparently it takes more
85359  ** time to parse and run the PRAGMA to turn journalling off than it does
85360  ** to write the journal header file.
85361  */
85362  zSql = "ATTACH '' AS vacuum_db;";
85363  rc = execSql(db, zSql);
85364  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85365  pDb = &db->aDb[db->nDb-1];
85366  assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
85367  pTemp = db->aDb[db->nDb-1].pBt;
85368
85369  /* The call to execSql() to attach the temp database has left the file
85370  ** locked (as there was more than one active statement when the transaction
85371  ** to read the schema was concluded. Unlock it here so that this doesn't
85372  ** cause problems for the call to BtreeSetPageSize() below.  */
85373  sqlite3BtreeCommit(pTemp);
85374
85375  nRes = sqlite3BtreeGetReserve(pMain);
85376
85377  /* A VACUUM cannot change the pagesize of an encrypted database. */
85378#ifdef SQLITE_HAS_CODEC
85379  if( db->nextPagesize ){
85380    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
85381    int nKey;
85382    char *zKey;
85383    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
85384    if( nKey ) db->nextPagesize = 0;
85385  }
85386#endif
85387
85388  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
85389   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
85390   || NEVER(db->mallocFailed)
85391  ){
85392    rc = SQLITE_NOMEM;
85393    goto end_of_vacuum;
85394  }
85395  rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
85396  if( rc!=SQLITE_OK ){
85397    goto end_of_vacuum;
85398  }
85399
85400#ifndef SQLITE_OMIT_AUTOVACUUM
85401  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
85402                                           sqlite3BtreeGetAutoVacuum(pMain));
85403#endif
85404
85405  /* Begin a transaction */
85406  rc = execSql(db, "BEGIN EXCLUSIVE;");
85407  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85408
85409  /* Query the schema of the main database. Create a mirror schema
85410  ** in the temporary database.
85411  */
85412  rc = execExecSql(db,
85413      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
85414      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
85415      "   AND rootpage>0"
85416  );
85417  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85418  rc = execExecSql(db,
85419      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
85420      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
85421  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85422  rc = execExecSql(db,
85423      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
85424      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
85425  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85426
85427  /* Loop through the tables in the main database. For each, do
85428  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
85429  ** the contents to the temporary database.
85430  */
85431  rc = execExecSql(db,
85432      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
85433      "|| ' SELECT * FROM main.' || quote(name) || ';'"
85434      "FROM main.sqlite_master "
85435      "WHERE type = 'table' AND name!='sqlite_sequence' "
85436      "  AND rootpage>0"
85437
85438  );
85439  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85440
85441  /* Copy over the sequence table
85442  */
85443  rc = execExecSql(db,
85444      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
85445      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
85446  );
85447  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85448  rc = execExecSql(db,
85449      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
85450      "|| ' SELECT * FROM main.' || quote(name) || ';' "
85451      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
85452  );
85453  if( rc!=SQLITE_OK ) goto end_of_vacuum;
85454
85455
85456  /* Copy the triggers, views, and virtual tables from the main database
85457  ** over to the temporary database.  None of these objects has any
85458  ** associated storage, so all we have to do is copy their entries
85459  ** from the SQLITE_MASTER table.
85460  */
85461  rc = execSql(db,
85462      "INSERT INTO vacuum_db.sqlite_master "
85463      "  SELECT type, name, tbl_name, rootpage, sql"
85464      "    FROM main.sqlite_master"
85465      "   WHERE type='view' OR type='trigger'"
85466      "      OR (type='table' AND rootpage=0)"
85467  );
85468  if( rc ) goto end_of_vacuum;
85469
85470  /* At this point, unless the main db was completely empty, there is now a
85471  ** transaction open on the vacuum database, but not on the main database.
85472  ** Open a btree level transaction on the main database. This allows a
85473  ** call to sqlite3BtreeCopyFile(). The main database btree level
85474  ** transaction is then committed, so the SQL level never knows it was
85475  ** opened for writing. This way, the SQL transaction used to create the
85476  ** temporary database never needs to be committed.
85477  */
85478  {
85479    u32 meta;
85480    int i;
85481
85482    /* This array determines which meta meta values are preserved in the
85483    ** vacuum.  Even entries are the meta value number and odd entries
85484    ** are an increment to apply to the meta value after the vacuum.
85485    ** The increment is used to increase the schema cookie so that other
85486    ** connections to the same database will know to reread the schema.
85487    */
85488    static const unsigned char aCopy[] = {
85489       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
85490       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
85491       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
85492       BTREE_USER_VERSION,       0,  /* Preserve the user version */
85493    };
85494
85495    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
85496    assert( 1==sqlite3BtreeIsInTrans(pMain) );
85497
85498    /* Copy Btree meta values */
85499    for(i=0; i<ArraySize(aCopy); i+=2){
85500      /* GetMeta() and UpdateMeta() cannot fail in this context because
85501      ** we already have page 1 loaded into cache and marked dirty. */
85502      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
85503      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
85504      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
85505    }
85506
85507    rc = sqlite3BtreeCopyFile(pMain, pTemp);
85508    if( rc!=SQLITE_OK ) goto end_of_vacuum;
85509    rc = sqlite3BtreeCommit(pTemp);
85510    if( rc!=SQLITE_OK ) goto end_of_vacuum;
85511#ifndef SQLITE_OMIT_AUTOVACUUM
85512    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
85513#endif
85514  }
85515
85516  assert( rc==SQLITE_OK );
85517  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
85518
85519end_of_vacuum:
85520  /* Restore the original value of db->flags */
85521  db->flags = saved_flags;
85522  db->nChange = saved_nChange;
85523  db->nTotalChange = saved_nTotalChange;
85524  db->xTrace = saved_xTrace;
85525
85526  /* Currently there is an SQL level transaction open on the vacuum
85527  ** database. No locks are held on any other files (since the main file
85528  ** was committed at the btree level). So it safe to end the transaction
85529  ** by manually setting the autoCommit flag to true and detaching the
85530  ** vacuum database. The vacuum_db journal file is deleted when the pager
85531  ** is closed by the DETACH.
85532  */
85533  db->autoCommit = 1;
85534
85535  if( pDb ){
85536    sqlite3BtreeClose(pDb->pBt);
85537    pDb->pBt = 0;
85538    pDb->pSchema = 0;
85539  }
85540
85541  sqlite3ResetInternalSchema(db, 0);
85542
85543  return rc;
85544}
85545#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
85546
85547/************** End of vacuum.c **********************************************/
85548/************** Begin file vtab.c ********************************************/
85549/*
85550** 2006 June 10
85551**
85552** The author disclaims copyright to this source code.  In place of
85553** a legal notice, here is a blessing:
85554**
85555**    May you do good and not evil.
85556**    May you find forgiveness for yourself and forgive others.
85557**    May you share freely, never taking more than you give.
85558**
85559*************************************************************************
85560** This file contains code used to help implement virtual tables.
85561*/
85562#ifndef SQLITE_OMIT_VIRTUALTABLE
85563
85564/*
85565** The actual function that does the work of creating a new module.
85566** This function implements the sqlite3_create_module() and
85567** sqlite3_create_module_v2() interfaces.
85568*/
85569static int createModule(
85570  sqlite3 *db,                    /* Database in which module is registered */
85571  const char *zName,              /* Name assigned to this module */
85572  const sqlite3_module *pModule,  /* The definition of the module */
85573  void *pAux,                     /* Context pointer for xCreate/xConnect */
85574  void (*xDestroy)(void *)        /* Module destructor function */
85575){
85576  int rc, nName;
85577  Module *pMod;
85578
85579  sqlite3_mutex_enter(db->mutex);
85580  nName = sqlite3Strlen30(zName);
85581  pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
85582  if( pMod ){
85583    Module *pDel;
85584    char *zCopy = (char *)(&pMod[1]);
85585    memcpy(zCopy, zName, nName+1);
85586    pMod->zName = zCopy;
85587    pMod->pModule = pModule;
85588    pMod->pAux = pAux;
85589    pMod->xDestroy = xDestroy;
85590    pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
85591    if( pDel && pDel->xDestroy ){
85592      pDel->xDestroy(pDel->pAux);
85593    }
85594    sqlite3DbFree(db, pDel);
85595    if( pDel==pMod ){
85596      db->mallocFailed = 1;
85597    }
85598    sqlite3ResetInternalSchema(db, 0);
85599  }else if( xDestroy ){
85600    xDestroy(pAux);
85601  }
85602  rc = sqlite3ApiExit(db, SQLITE_OK);
85603  sqlite3_mutex_leave(db->mutex);
85604  return rc;
85605}
85606
85607
85608/*
85609** External API function used to create a new virtual-table module.
85610*/
85611SQLITE_API int sqlite3_create_module(
85612  sqlite3 *db,                    /* Database in which module is registered */
85613  const char *zName,              /* Name assigned to this module */
85614  const sqlite3_module *pModule,  /* The definition of the module */
85615  void *pAux                      /* Context pointer for xCreate/xConnect */
85616){
85617  return createModule(db, zName, pModule, pAux, 0);
85618}
85619
85620/*
85621** External API function used to create a new virtual-table module.
85622*/
85623SQLITE_API int sqlite3_create_module_v2(
85624  sqlite3 *db,                    /* Database in which module is registered */
85625  const char *zName,              /* Name assigned to this module */
85626  const sqlite3_module *pModule,  /* The definition of the module */
85627  void *pAux,                     /* Context pointer for xCreate/xConnect */
85628  void (*xDestroy)(void *)        /* Module destructor function */
85629){
85630  return createModule(db, zName, pModule, pAux, xDestroy);
85631}
85632
85633/*
85634** Lock the virtual table so that it cannot be disconnected.
85635** Locks nest.  Every lock should have a corresponding unlock.
85636** If an unlock is omitted, resources leaks will occur.
85637**
85638** If a disconnect is attempted while a virtual table is locked,
85639** the disconnect is deferred until all locks have been removed.
85640*/
85641SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
85642  pVTab->nRef++;
85643}
85644
85645
85646/*
85647** pTab is a pointer to a Table structure representing a virtual-table.
85648** Return a pointer to the VTable object used by connection db to access
85649** this virtual-table, if one has been created, or NULL otherwise.
85650*/
85651SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
85652  VTable *pVtab;
85653  assert( IsVirtual(pTab) );
85654  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
85655  return pVtab;
85656}
85657
85658/*
85659** Decrement the ref-count on a virtual table object. When the ref-count
85660** reaches zero, call the xDisconnect() method to delete the object.
85661*/
85662SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
85663  sqlite3 *db = pVTab->db;
85664
85665  assert( db );
85666  assert( pVTab->nRef>0 );
85667  assert( sqlite3SafetyCheckOk(db) );
85668
85669  pVTab->nRef--;
85670  if( pVTab->nRef==0 ){
85671    sqlite3_vtab *p = pVTab->pVtab;
85672    if( p ){
85673#ifdef SQLITE_DEBUG
85674      if( pVTab->db->magic==SQLITE_MAGIC_BUSY ){
85675        (void)sqlite3SafetyOff(db);
85676        p->pModule->xDisconnect(p);
85677        (void)sqlite3SafetyOn(db);
85678      } else
85679#endif
85680      {
85681        p->pModule->xDisconnect(p);
85682      }
85683    }
85684    sqlite3DbFree(db, pVTab);
85685  }
85686}
85687
85688/*
85689** Table p is a virtual table. This function moves all elements in the
85690** p->pVTable list to the sqlite3.pDisconnect lists of their associated
85691** database connections to be disconnected at the next opportunity.
85692** Except, if argument db is not NULL, then the entry associated with
85693** connection db is left in the p->pVTable list.
85694*/
85695static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
85696  VTable *pRet = 0;
85697  VTable *pVTable = p->pVTable;
85698  p->pVTable = 0;
85699
85700  /* Assert that the mutex (if any) associated with the BtShared database
85701  ** that contains table p is held by the caller. See header comments
85702  ** above function sqlite3VtabUnlockList() for an explanation of why
85703  ** this makes it safe to access the sqlite3.pDisconnect list of any
85704  ** database connection that may have an entry in the p->pVTable list.  */
85705  assert( db==0 ||
85706    sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt)
85707  );
85708
85709  while( pVTable ){
85710    sqlite3 *db2 = pVTable->db;
85711    VTable *pNext = pVTable->pNext;
85712    assert( db2 );
85713    if( db2==db ){
85714      pRet = pVTable;
85715      p->pVTable = pRet;
85716      pRet->pNext = 0;
85717    }else{
85718      pVTable->pNext = db2->pDisconnect;
85719      db2->pDisconnect = pVTable;
85720    }
85721    pVTable = pNext;
85722  }
85723
85724  assert( !db || pRet );
85725  return pRet;
85726}
85727
85728
85729/*
85730** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
85731**
85732** This function may only be called when the mutexes associated with all
85733** shared b-tree databases opened using connection db are held by the
85734** caller. This is done to protect the sqlite3.pDisconnect list. The
85735** sqlite3.pDisconnect list is accessed only as follows:
85736**
85737**   1) By this function. In this case, all BtShared mutexes and the mutex
85738**      associated with the database handle itself must be held.
85739**
85740**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
85741**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
85742**      associated with the database the virtual table is stored in is held
85743**      or, if the virtual table is stored in a non-sharable database, then
85744**      the database handle mutex is held.
85745**
85746** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
85747** by multiple threads. It is thread-safe.
85748*/
85749SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
85750  VTable *p = db->pDisconnect;
85751  db->pDisconnect = 0;
85752
85753  assert( sqlite3BtreeHoldsAllMutexes(db) );
85754  assert( sqlite3_mutex_held(db->mutex) );
85755
85756  if( p ){
85757    sqlite3ExpirePreparedStatements(db);
85758    do {
85759      VTable *pNext = p->pNext;
85760      sqlite3VtabUnlock(p);
85761      p = pNext;
85762    }while( p );
85763  }
85764}
85765
85766/*
85767** Clear any and all virtual-table information from the Table record.
85768** This routine is called, for example, just before deleting the Table
85769** record.
85770**
85771** Since it is a virtual-table, the Table structure contains a pointer
85772** to the head of a linked list of VTable structures. Each VTable
85773** structure is associated with a single sqlite3* user of the schema.
85774** The reference count of the VTable structure associated with database
85775** connection db is decremented immediately (which may lead to the
85776** structure being xDisconnected and free). Any other VTable structures
85777** in the list are moved to the sqlite3.pDisconnect list of the associated
85778** database connection.
85779*/
85780SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
85781  vtabDisconnectAll(0, p);
85782  if( p->azModuleArg ){
85783    int i;
85784    for(i=0; i<p->nModuleArg; i++){
85785      sqlite3DbFree(p->dbMem, p->azModuleArg[i]);
85786    }
85787    sqlite3DbFree(p->dbMem, p->azModuleArg);
85788  }
85789}
85790
85791/*
85792** Add a new module argument to pTable->azModuleArg[].
85793** The string is not copied - the pointer is stored.  The
85794** string will be freed automatically when the table is
85795** deleted.
85796*/
85797static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
85798  int i = pTable->nModuleArg++;
85799  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
85800  char **azModuleArg;
85801  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
85802  if( azModuleArg==0 ){
85803    int j;
85804    for(j=0; j<i; j++){
85805      sqlite3DbFree(db, pTable->azModuleArg[j]);
85806    }
85807    sqlite3DbFree(db, zArg);
85808    sqlite3DbFree(db, pTable->azModuleArg);
85809    pTable->nModuleArg = 0;
85810  }else{
85811    azModuleArg[i] = zArg;
85812    azModuleArg[i+1] = 0;
85813  }
85814  pTable->azModuleArg = azModuleArg;
85815}
85816
85817/*
85818** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
85819** statement.  The module name has been parsed, but the optional list
85820** of parameters that follow the module name are still pending.
85821*/
85822SQLITE_PRIVATE void sqlite3VtabBeginParse(
85823  Parse *pParse,        /* Parsing context */
85824  Token *pName1,        /* Name of new table, or database name */
85825  Token *pName2,        /* Name of new table or NULL */
85826  Token *pModuleName    /* Name of the module for the virtual table */
85827){
85828  int iDb;              /* The database the table is being created in */
85829  Table *pTable;        /* The new virtual table */
85830  sqlite3 *db;          /* Database connection */
85831
85832  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
85833  pTable = pParse->pNewTable;
85834  if( pTable==0 ) return;
85835  assert( 0==pTable->pIndex );
85836
85837  db = pParse->db;
85838  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
85839  assert( iDb>=0 );
85840
85841  pTable->tabFlags |= TF_Virtual;
85842  pTable->nModuleArg = 0;
85843  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
85844  addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
85845  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
85846  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
85847
85848#ifndef SQLITE_OMIT_AUTHORIZATION
85849  /* Creating a virtual table invokes the authorization callback twice.
85850  ** The first invocation, to obtain permission to INSERT a row into the
85851  ** sqlite_master table, has already been made by sqlite3StartTable().
85852  ** The second call, to obtain permission to create the table, is made now.
85853  */
85854  if( pTable->azModuleArg ){
85855    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
85856            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
85857  }
85858#endif
85859}
85860
85861/*
85862** This routine takes the module argument that has been accumulating
85863** in pParse->zArg[] and appends it to the list of arguments on the
85864** virtual table currently under construction in pParse->pTable.
85865*/
85866static void addArgumentToVtab(Parse *pParse){
85867  if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
85868    const char *z = (const char*)pParse->sArg.z;
85869    int n = pParse->sArg.n;
85870    sqlite3 *db = pParse->db;
85871    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
85872  }
85873}
85874
85875/*
85876** The parser calls this routine after the CREATE VIRTUAL TABLE statement
85877** has been completely parsed.
85878*/
85879SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
85880  Table *pTab = pParse->pNewTable;  /* The table being constructed */
85881  sqlite3 *db = pParse->db;         /* The database connection */
85882
85883  if( pTab==0 ) return;
85884  addArgumentToVtab(pParse);
85885  pParse->sArg.z = 0;
85886  if( pTab->nModuleArg<1 ) return;
85887
85888  /* If the CREATE VIRTUAL TABLE statement is being entered for the
85889  ** first time (in other words if the virtual table is actually being
85890  ** created now instead of just being read out of sqlite_master) then
85891  ** do additional initialization work and store the statement text
85892  ** in the sqlite_master table.
85893  */
85894  if( !db->init.busy ){
85895    char *zStmt;
85896    char *zWhere;
85897    int iDb;
85898    Vdbe *v;
85899
85900    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
85901    if( pEnd ){
85902      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
85903    }
85904    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
85905
85906    /* A slot for the record has already been allocated in the
85907    ** SQLITE_MASTER table.  We just need to update that slot with all
85908    ** the information we've collected.
85909    **
85910    ** The VM register number pParse->regRowid holds the rowid of an
85911    ** entry in the sqlite_master table tht was created for this vtab
85912    ** by sqlite3StartTable().
85913    */
85914    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85915    sqlite3NestedParse(pParse,
85916      "UPDATE %Q.%s "
85917         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
85918       "WHERE rowid=#%d",
85919      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
85920      pTab->zName,
85921      pTab->zName,
85922      zStmt,
85923      pParse->regRowid
85924    );
85925    sqlite3DbFree(db, zStmt);
85926    v = sqlite3GetVdbe(pParse);
85927    sqlite3ChangeCookie(pParse, iDb);
85928
85929    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
85930    zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
85931    sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
85932    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
85933                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
85934  }
85935
85936  /* If we are rereading the sqlite_master table create the in-memory
85937  ** record of the table. The xConnect() method is not called until
85938  ** the first time the virtual table is used in an SQL statement. This
85939  ** allows a schema that contains virtual tables to be loaded before
85940  ** the required virtual table implementations are registered.  */
85941  else {
85942    Table *pOld;
85943    Schema *pSchema = pTab->pSchema;
85944    const char *zName = pTab->zName;
85945    int nName = sqlite3Strlen30(zName);
85946    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
85947    if( pOld ){
85948      db->mallocFailed = 1;
85949      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
85950      return;
85951    }
85952    pSchema->db = pParse->db;
85953    pParse->pNewTable = 0;
85954  }
85955}
85956
85957/*
85958** The parser calls this routine when it sees the first token
85959** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
85960*/
85961SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
85962  addArgumentToVtab(pParse);
85963  pParse->sArg.z = 0;
85964  pParse->sArg.n = 0;
85965}
85966
85967/*
85968** The parser calls this routine for each token after the first token
85969** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
85970*/
85971SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
85972  Token *pArg = &pParse->sArg;
85973  if( pArg->z==0 ){
85974    pArg->z = p->z;
85975    pArg->n = p->n;
85976  }else{
85977    assert(pArg->z < p->z);
85978    pArg->n = (int)(&p->z[p->n] - pArg->z);
85979  }
85980}
85981
85982/*
85983** Invoke a virtual table constructor (either xCreate or xConnect). The
85984** pointer to the function to invoke is passed as the fourth parameter
85985** to this procedure.
85986*/
85987static int vtabCallConstructor(
85988  sqlite3 *db,
85989  Table *pTab,
85990  Module *pMod,
85991  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
85992  char **pzErr
85993){
85994  VTable *pVTable;
85995  int rc;
85996  const char *const*azArg = (const char *const*)pTab->azModuleArg;
85997  int nArg = pTab->nModuleArg;
85998  char *zErr = 0;
85999  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
86000
86001  if( !zModuleName ){
86002    return SQLITE_NOMEM;
86003  }
86004
86005  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
86006  if( !pVTable ){
86007    sqlite3DbFree(db, zModuleName);
86008    return SQLITE_NOMEM;
86009  }
86010  pVTable->db = db;
86011  pVTable->pMod = pMod;
86012
86013  assert( !db->pVTab );
86014  assert( xConstruct );
86015  db->pVTab = pTab;
86016
86017  /* Invoke the virtual table constructor */
86018  (void)sqlite3SafetyOff(db);
86019  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
86020  (void)sqlite3SafetyOn(db);
86021  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
86022
86023  if( SQLITE_OK!=rc ){
86024    if( zErr==0 ){
86025      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
86026    }else {
86027      *pzErr = sqlite3MPrintf(db, "%s", zErr);
86028      sqlite3DbFree(db, zErr);
86029    }
86030    sqlite3DbFree(db, pVTable);
86031  }else if( ALWAYS(pVTable->pVtab) ){
86032    /* Justification of ALWAYS():  A correct vtab constructor must allocate
86033    ** the sqlite3_vtab object if successful.  */
86034    pVTable->pVtab->pModule = pMod->pModule;
86035    pVTable->nRef = 1;
86036    if( db->pVTab ){
86037      const char *zFormat = "vtable constructor did not declare schema: %s";
86038      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
86039      sqlite3VtabUnlock(pVTable);
86040      rc = SQLITE_ERROR;
86041    }else{
86042      int iCol;
86043      /* If everything went according to plan, link the new VTable structure
86044      ** into the linked list headed by pTab->pVTable. Then loop through the
86045      ** columns of the table to see if any of them contain the token "hidden".
86046      ** If so, set the Column.isHidden flag and remove the token from
86047      ** the type string.  */
86048      pVTable->pNext = pTab->pVTable;
86049      pTab->pVTable = pVTable;
86050
86051      for(iCol=0; iCol<pTab->nCol; iCol++){
86052        char *zType = pTab->aCol[iCol].zType;
86053        int nType;
86054        int i = 0;
86055        if( !zType ) continue;
86056        nType = sqlite3Strlen30(zType);
86057        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
86058          for(i=0; i<nType; i++){
86059            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
86060             && (zType[i+7]=='\0' || zType[i+7]==' ')
86061            ){
86062              i++;
86063              break;
86064            }
86065          }
86066        }
86067        if( i<nType ){
86068          int j;
86069          int nDel = 6 + (zType[i+6] ? 1 : 0);
86070          for(j=i; (j+nDel)<=nType; j++){
86071            zType[j] = zType[j+nDel];
86072          }
86073          if( zType[i]=='\0' && i>0 ){
86074            assert(zType[i-1]==' ');
86075            zType[i-1] = '\0';
86076          }
86077          pTab->aCol[iCol].isHidden = 1;
86078        }
86079      }
86080    }
86081  }
86082
86083  sqlite3DbFree(db, zModuleName);
86084  db->pVTab = 0;
86085  return rc;
86086}
86087
86088/*
86089** This function is invoked by the parser to call the xConnect() method
86090** of the virtual table pTab. If an error occurs, an error code is returned
86091** and an error left in pParse.
86092**
86093** This call is a no-op if table pTab is not a virtual table.
86094*/
86095SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
86096  sqlite3 *db = pParse->db;
86097  const char *zMod;
86098  Module *pMod;
86099  int rc;
86100
86101  assert( pTab );
86102  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
86103    return SQLITE_OK;
86104  }
86105
86106  /* Locate the required virtual table module */
86107  zMod = pTab->azModuleArg[0];
86108  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
86109
86110  if( !pMod ){
86111    const char *zModule = pTab->azModuleArg[0];
86112    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
86113    rc = SQLITE_ERROR;
86114  }else{
86115    char *zErr = 0;
86116    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
86117    if( rc!=SQLITE_OK ){
86118      sqlite3ErrorMsg(pParse, "%s", zErr);
86119    }
86120    sqlite3DbFree(db, zErr);
86121  }
86122
86123  return rc;
86124}
86125
86126/*
86127** Add the virtual table pVTab to the array sqlite3.aVTrans[].
86128*/
86129static int addToVTrans(sqlite3 *db, VTable *pVTab){
86130  const int ARRAY_INCR = 5;
86131
86132  /* Grow the sqlite3.aVTrans array if required */
86133  if( (db->nVTrans%ARRAY_INCR)==0 ){
86134    VTable **aVTrans;
86135    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
86136    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
86137    if( !aVTrans ){
86138      return SQLITE_NOMEM;
86139    }
86140    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
86141    db->aVTrans = aVTrans;
86142  }
86143
86144  /* Add pVtab to the end of sqlite3.aVTrans */
86145  db->aVTrans[db->nVTrans++] = pVTab;
86146  sqlite3VtabLock(pVTab);
86147  return SQLITE_OK;
86148}
86149
86150/*
86151** This function is invoked by the vdbe to call the xCreate method
86152** of the virtual table named zTab in database iDb.
86153**
86154** If an error occurs, *pzErr is set to point an an English language
86155** description of the error and an SQLITE_XXX error code is returned.
86156** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
86157*/
86158SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
86159  int rc = SQLITE_OK;
86160  Table *pTab;
86161  Module *pMod;
86162  const char *zMod;
86163
86164  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
86165  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
86166
86167  /* Locate the required virtual table module */
86168  zMod = pTab->azModuleArg[0];
86169  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
86170
86171  /* If the module has been registered and includes a Create method,
86172  ** invoke it now. If the module has not been registered, return an
86173  ** error. Otherwise, do nothing.
86174  */
86175  if( !pMod ){
86176    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
86177    rc = SQLITE_ERROR;
86178  }else{
86179    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
86180  }
86181
86182  /* Justification of ALWAYS():  The xConstructor method is required to
86183  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
86184  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
86185      rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
86186  }
86187
86188  return rc;
86189}
86190
86191/*
86192** This function is used to set the schema of a virtual table.  It is only
86193** valid to call this function from within the xCreate() or xConnect() of a
86194** virtual table module.
86195*/
86196SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
86197  Parse *pParse;
86198
86199  int rc = SQLITE_OK;
86200  Table *pTab;
86201  char *zErr = 0;
86202
86203  sqlite3_mutex_enter(db->mutex);
86204  pTab = db->pVTab;
86205  if( !pTab ){
86206    sqlite3Error(db, SQLITE_MISUSE, 0);
86207    sqlite3_mutex_leave(db->mutex);
86208    return SQLITE_MISUSE;
86209  }
86210  assert( (pTab->tabFlags & TF_Virtual)!=0 );
86211
86212  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
86213  if( pParse==0 ){
86214    rc = SQLITE_NOMEM;
86215  }else{
86216    pParse->declareVtab = 1;
86217    pParse->db = db;
86218
86219    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
86220     && pParse->pNewTable
86221     && !db->mallocFailed
86222     && !pParse->pNewTable->pSelect
86223     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
86224    ){
86225      if( !pTab->aCol ){
86226        pTab->aCol = pParse->pNewTable->aCol;
86227        pTab->nCol = pParse->pNewTable->nCol;
86228        pParse->pNewTable->nCol = 0;
86229        pParse->pNewTable->aCol = 0;
86230      }
86231      db->pVTab = 0;
86232    }else{
86233      sqlite3Error(db, SQLITE_ERROR, zErr);
86234      sqlite3DbFree(db, zErr);
86235      rc = SQLITE_ERROR;
86236    }
86237    pParse->declareVtab = 0;
86238
86239    if( pParse->pVdbe ){
86240      sqlite3VdbeFinalize(pParse->pVdbe);
86241    }
86242    sqlite3DeleteTable(pParse->pNewTable);
86243    sqlite3StackFree(db, pParse);
86244  }
86245
86246  assert( (rc&0xff)==rc );
86247  rc = sqlite3ApiExit(db, rc);
86248  sqlite3_mutex_leave(db->mutex);
86249  return rc;
86250}
86251
86252/*
86253** This function is invoked by the vdbe to call the xDestroy method
86254** of the virtual table named zTab in database iDb. This occurs
86255** when a DROP TABLE is mentioned.
86256**
86257** This call is a no-op if zTab is not a virtual table.
86258*/
86259SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
86260  int rc = SQLITE_OK;
86261  Table *pTab;
86262
86263  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
86264  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
86265    VTable *p = vtabDisconnectAll(db, pTab);
86266
86267    rc = sqlite3SafetyOff(db);
86268    assert( rc==SQLITE_OK );
86269    rc = p->pMod->pModule->xDestroy(p->pVtab);
86270    (void)sqlite3SafetyOn(db);
86271
86272    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
86273    if( rc==SQLITE_OK ){
86274      assert( pTab->pVTable==p && p->pNext==0 );
86275      p->pVtab = 0;
86276      pTab->pVTable = 0;
86277      sqlite3VtabUnlock(p);
86278    }
86279  }
86280
86281  return rc;
86282}
86283
86284/*
86285** This function invokes either the xRollback or xCommit method
86286** of each of the virtual tables in the sqlite3.aVTrans array. The method
86287** called is identified by the second argument, "offset", which is
86288** the offset of the method to call in the sqlite3_module structure.
86289**
86290** The array is cleared after invoking the callbacks.
86291*/
86292static void callFinaliser(sqlite3 *db, int offset){
86293  int i;
86294  if( db->aVTrans ){
86295    for(i=0; i<db->nVTrans; i++){
86296      VTable *pVTab = db->aVTrans[i];
86297      sqlite3_vtab *p = pVTab->pVtab;
86298      if( p ){
86299        int (*x)(sqlite3_vtab *);
86300        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
86301        if( x ) x(p);
86302      }
86303      sqlite3VtabUnlock(pVTab);
86304    }
86305    sqlite3DbFree(db, db->aVTrans);
86306    db->nVTrans = 0;
86307    db->aVTrans = 0;
86308  }
86309}
86310
86311/*
86312** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
86313** array. Return the error code for the first error that occurs, or
86314** SQLITE_OK if all xSync operations are successful.
86315**
86316** Set *pzErrmsg to point to a buffer that should be released using
86317** sqlite3DbFree() containing an error message, if one is available.
86318*/
86319SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
86320  int i;
86321  int rc = SQLITE_OK;
86322  int rcsafety;
86323  VTable **aVTrans = db->aVTrans;
86324
86325  rc = sqlite3SafetyOff(db);
86326  db->aVTrans = 0;
86327  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
86328    int (*x)(sqlite3_vtab *);
86329    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
86330    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
86331      rc = x(pVtab);
86332      sqlite3DbFree(db, *pzErrmsg);
86333      *pzErrmsg = pVtab->zErrMsg;
86334      pVtab->zErrMsg = 0;
86335    }
86336  }
86337  db->aVTrans = aVTrans;
86338  rcsafety = sqlite3SafetyOn(db);
86339
86340  if( rc==SQLITE_OK ){
86341    rc = rcsafety;
86342  }
86343  return rc;
86344}
86345
86346/*
86347** Invoke the xRollback method of all virtual tables in the
86348** sqlite3.aVTrans array. Then clear the array itself.
86349*/
86350SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
86351  callFinaliser(db, offsetof(sqlite3_module,xRollback));
86352  return SQLITE_OK;
86353}
86354
86355/*
86356** Invoke the xCommit method of all virtual tables in the
86357** sqlite3.aVTrans array. Then clear the array itself.
86358*/
86359SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
86360  callFinaliser(db, offsetof(sqlite3_module,xCommit));
86361  return SQLITE_OK;
86362}
86363
86364/*
86365** If the virtual table pVtab supports the transaction interface
86366** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
86367** not currently open, invoke the xBegin method now.
86368**
86369** If the xBegin call is successful, place the sqlite3_vtab pointer
86370** in the sqlite3.aVTrans array.
86371*/
86372SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
86373  int rc = SQLITE_OK;
86374  const sqlite3_module *pModule;
86375
86376  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
86377  ** than zero, then this function is being called from within a
86378  ** virtual module xSync() callback. It is illegal to write to
86379  ** virtual module tables in this case, so return SQLITE_LOCKED.
86380  */
86381  if( sqlite3VtabInSync(db) ){
86382    return SQLITE_LOCKED;
86383  }
86384  if( !pVTab ){
86385    return SQLITE_OK;
86386  }
86387  pModule = pVTab->pVtab->pModule;
86388
86389  if( pModule->xBegin ){
86390    int i;
86391
86392
86393    /* If pVtab is already in the aVTrans array, return early */
86394    for(i=0; i<db->nVTrans; i++){
86395      if( db->aVTrans[i]==pVTab ){
86396        return SQLITE_OK;
86397      }
86398    }
86399
86400    /* Invoke the xBegin method */
86401    rc = pModule->xBegin(pVTab->pVtab);
86402    if( rc==SQLITE_OK ){
86403      rc = addToVTrans(db, pVTab);
86404    }
86405  }
86406  return rc;
86407}
86408
86409/*
86410** The first parameter (pDef) is a function implementation.  The
86411** second parameter (pExpr) is the first argument to this function.
86412** If pExpr is a column in a virtual table, then let the virtual
86413** table implementation have an opportunity to overload the function.
86414**
86415** This routine is used to allow virtual table implementations to
86416** overload MATCH, LIKE, GLOB, and REGEXP operators.
86417**
86418** Return either the pDef argument (indicating no change) or a
86419** new FuncDef structure that is marked as ephemeral using the
86420** SQLITE_FUNC_EPHEM flag.
86421*/
86422SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
86423  sqlite3 *db,    /* Database connection for reporting malloc problems */
86424  FuncDef *pDef,  /* Function to possibly overload */
86425  int nArg,       /* Number of arguments to the function */
86426  Expr *pExpr     /* First argument to the function */
86427){
86428  Table *pTab;
86429  sqlite3_vtab *pVtab;
86430  sqlite3_module *pMod;
86431  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
86432  void *pArg = 0;
86433  FuncDef *pNew;
86434  int rc = 0;
86435  char *zLowerName;
86436  unsigned char *z;
86437
86438
86439  /* Check to see the left operand is a column in a virtual table */
86440  if( NEVER(pExpr==0) ) return pDef;
86441  if( pExpr->op!=TK_COLUMN ) return pDef;
86442  pTab = pExpr->pTab;
86443  if( NEVER(pTab==0) ) return pDef;
86444  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
86445  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
86446  assert( pVtab!=0 );
86447  assert( pVtab->pModule!=0 );
86448  pMod = (sqlite3_module *)pVtab->pModule;
86449  if( pMod->xFindFunction==0 ) return pDef;
86450
86451  /* Call the xFindFunction method on the virtual table implementation
86452  ** to see if the implementation wants to overload this function
86453  */
86454  zLowerName = sqlite3DbStrDup(db, pDef->zName);
86455  if( zLowerName ){
86456    for(z=(unsigned char*)zLowerName; *z; z++){
86457      *z = sqlite3UpperToLower[*z];
86458    }
86459    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
86460    sqlite3DbFree(db, zLowerName);
86461  }
86462  if( rc==0 ){
86463    return pDef;
86464  }
86465
86466  /* Create a new ephemeral function definition for the overloaded
86467  ** function */
86468  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
86469                             + sqlite3Strlen30(pDef->zName) + 1);
86470  if( pNew==0 ){
86471    return pDef;
86472  }
86473  *pNew = *pDef;
86474  pNew->zName = (char *)&pNew[1];
86475  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
86476  pNew->xFunc = xFunc;
86477  pNew->pUserData = pArg;
86478  pNew->flags |= SQLITE_FUNC_EPHEM;
86479  return pNew;
86480}
86481
86482/*
86483** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
86484** array so that an OP_VBegin will get generated for it.  Add pTab to the
86485** array if it is missing.  If pTab is already in the array, this routine
86486** is a no-op.
86487*/
86488SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
86489  Parse *pToplevel = sqlite3ParseToplevel(pParse);
86490  int i, n;
86491  Table **apVtabLock;
86492
86493  assert( IsVirtual(pTab) );
86494  for(i=0; i<pToplevel->nVtabLock; i++){
86495    if( pTab==pToplevel->apVtabLock[i] ) return;
86496  }
86497  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
86498  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
86499  if( apVtabLock ){
86500    pToplevel->apVtabLock = apVtabLock;
86501    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
86502  }else{
86503    pToplevel->db->mallocFailed = 1;
86504  }
86505}
86506
86507#endif /* SQLITE_OMIT_VIRTUALTABLE */
86508
86509/************** End of vtab.c ************************************************/
86510/************** Begin file where.c *******************************************/
86511/*
86512** 2001 September 15
86513**
86514** The author disclaims copyright to this source code.  In place of
86515** a legal notice, here is a blessing:
86516**
86517**    May you do good and not evil.
86518**    May you find forgiveness for yourself and forgive others.
86519**    May you share freely, never taking more than you give.
86520**
86521*************************************************************************
86522** This module contains C code that generates VDBE code used to process
86523** the WHERE clause of SQL statements.  This module is responsible for
86524** generating the code that loops through a table looking for applicable
86525** rows.  Indices are selected and used to speed the search when doing
86526** so is applicable.  Because this module is responsible for selecting
86527** indices, you might also think of this module as the "query optimizer".
86528*/
86529
86530/*
86531** Trace output macros
86532*/
86533#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
86534SQLITE_PRIVATE int sqlite3WhereTrace = 0;
86535#endif
86536#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
86537# define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
86538#else
86539# define WHERETRACE(X)
86540#endif
86541
86542/* Forward reference
86543*/
86544typedef struct WhereClause WhereClause;
86545typedef struct WhereMaskSet WhereMaskSet;
86546typedef struct WhereOrInfo WhereOrInfo;
86547typedef struct WhereAndInfo WhereAndInfo;
86548typedef struct WhereCost WhereCost;
86549
86550/*
86551** The query generator uses an array of instances of this structure to
86552** help it analyze the subexpressions of the WHERE clause.  Each WHERE
86553** clause subexpression is separated from the others by AND operators,
86554** usually, or sometimes subexpressions separated by OR.
86555**
86556** All WhereTerms are collected into a single WhereClause structure.
86557** The following identity holds:
86558**
86559**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
86560**
86561** When a term is of the form:
86562**
86563**              X <op> <expr>
86564**
86565** where X is a column name and <op> is one of certain operators,
86566** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
86567** cursor number and column number for X.  WhereTerm.eOperator records
86568** the <op> using a bitmask encoding defined by WO_xxx below.  The
86569** use of a bitmask encoding for the operator allows us to search
86570** quickly for terms that match any of several different operators.
86571**
86572** A WhereTerm might also be two or more subterms connected by OR:
86573**
86574**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
86575**
86576** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
86577** and the WhereTerm.u.pOrInfo field points to auxiliary information that
86578** is collected about the
86579**
86580** If a term in the WHERE clause does not match either of the two previous
86581** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
86582** to the original subexpression content and wtFlags is set up appropriately
86583** but no other fields in the WhereTerm object are meaningful.
86584**
86585** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
86586** but they do so indirectly.  A single WhereMaskSet structure translates
86587** cursor number into bits and the translated bit is stored in the prereq
86588** fields.  The translation is used in order to maximize the number of
86589** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
86590** spread out over the non-negative integers.  For example, the cursor
86591** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
86592** translates these sparse cursor numbers into consecutive integers
86593** beginning with 0 in order to make the best possible use of the available
86594** bits in the Bitmask.  So, in the example above, the cursor numbers
86595** would be mapped into integers 0 through 7.
86596**
86597** The number of terms in a join is limited by the number of bits
86598** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
86599** is only able to process joins with 64 or fewer tables.
86600*/
86601typedef struct WhereTerm WhereTerm;
86602struct WhereTerm {
86603  Expr *pExpr;            /* Pointer to the subexpression that is this term */
86604  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
86605  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
86606  union {
86607    int leftColumn;         /* Column number of X in "X <op> <expr>" */
86608    WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
86609    WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
86610  } u;
86611  u16 eOperator;          /* A WO_xx value describing <op> */
86612  u8 wtFlags;             /* TERM_xxx bit flags.  See below */
86613  u8 nChild;              /* Number of children that must disable us */
86614  WhereClause *pWC;       /* The clause this term is part of */
86615  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
86616  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
86617};
86618
86619/*
86620** Allowed values of WhereTerm.wtFlags
86621*/
86622#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
86623#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
86624#define TERM_CODED      0x04   /* This term is already coded */
86625#define TERM_COPIED     0x08   /* Has a child */
86626#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
86627#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
86628#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
86629
86630/*
86631** An instance of the following structure holds all information about a
86632** WHERE clause.  Mostly this is a container for one or more WhereTerms.
86633*/
86634struct WhereClause {
86635  Parse *pParse;           /* The parser context */
86636  WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
86637  Bitmask vmask;           /* Bitmask identifying virtual table cursors */
86638  u8 op;                   /* Split operator.  TK_AND or TK_OR */
86639  int nTerm;               /* Number of terms */
86640  int nSlot;               /* Number of entries in a[] */
86641  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
86642#if defined(SQLITE_SMALL_STACK)
86643  WhereTerm aStatic[1];    /* Initial static space for a[] */
86644#else
86645  WhereTerm aStatic[8];    /* Initial static space for a[] */
86646#endif
86647};
86648
86649/*
86650** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
86651** a dynamically allocated instance of the following structure.
86652*/
86653struct WhereOrInfo {
86654  WhereClause wc;          /* Decomposition into subterms */
86655  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
86656};
86657
86658/*
86659** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
86660** a dynamically allocated instance of the following structure.
86661*/
86662struct WhereAndInfo {
86663  WhereClause wc;          /* The subexpression broken out */
86664};
86665
86666/*
86667** An instance of the following structure keeps track of a mapping
86668** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
86669**
86670** The VDBE cursor numbers are small integers contained in
86671** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
86672** clause, the cursor numbers might not begin with 0 and they might
86673** contain gaps in the numbering sequence.  But we want to make maximum
86674** use of the bits in our bitmasks.  This structure provides a mapping
86675** from the sparse cursor numbers into consecutive integers beginning
86676** with 0.
86677**
86678** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
86679** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
86680**
86681** For example, if the WHERE clause expression used these VDBE
86682** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
86683** would map those cursor numbers into bits 0 through 5.
86684**
86685** Note that the mapping is not necessarily ordered.  In the example
86686** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
86687** 57->5, 73->4.  Or one of 719 other combinations might be used. It
86688** does not really matter.  What is important is that sparse cursor
86689** numbers all get mapped into bit numbers that begin with 0 and contain
86690** no gaps.
86691*/
86692struct WhereMaskSet {
86693  int n;                        /* Number of assigned cursor values */
86694  int ix[BMS];                  /* Cursor assigned to each bit */
86695};
86696
86697/*
86698** A WhereCost object records a lookup strategy and the estimated
86699** cost of pursuing that strategy.
86700*/
86701struct WhereCost {
86702  WherePlan plan;    /* The lookup strategy */
86703  double rCost;      /* Overall cost of pursuing this search strategy */
86704  double nRow;       /* Estimated number of output rows */
86705  Bitmask used;      /* Bitmask of cursors used by this plan */
86706};
86707
86708/*
86709** Bitmasks for the operators that indices are able to exploit.  An
86710** OR-ed combination of these values can be used when searching for
86711** terms in the where clause.
86712*/
86713#define WO_IN     0x001
86714#define WO_EQ     0x002
86715#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
86716#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
86717#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
86718#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
86719#define WO_MATCH  0x040
86720#define WO_ISNULL 0x080
86721#define WO_OR     0x100       /* Two or more OR-connected terms */
86722#define WO_AND    0x200       /* Two or more AND-connected terms */
86723
86724#define WO_ALL    0xfff       /* Mask of all possible WO_* values */
86725#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
86726
86727/*
86728** Value for wsFlags returned by bestIndex() and stored in
86729** WhereLevel.wsFlags.  These flags determine which search
86730** strategies are appropriate.
86731**
86732** The least significant 12 bits is reserved as a mask for WO_ values above.
86733** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
86734** But if the table is the right table of a left join, WhereLevel.wsFlags
86735** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
86736** the "op" parameter to findTerm when we are resolving equality constraints.
86737** ISNULL constraints will then not be used on the right table of a left
86738** join.  Tickets #2177 and #2189.
86739*/
86740#define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
86741#define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
86742#define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
86743#define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
86744#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
86745#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
86746#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
86747#define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
86748#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
86749#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
86750#define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
86751#define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
86752#define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
86753#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
86754#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
86755#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
86756
86757/*
86758** Initialize a preallocated WhereClause structure.
86759*/
86760static void whereClauseInit(
86761  WhereClause *pWC,        /* The WhereClause to be initialized */
86762  Parse *pParse,           /* The parsing context */
86763  WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
86764){
86765  pWC->pParse = pParse;
86766  pWC->pMaskSet = pMaskSet;
86767  pWC->nTerm = 0;
86768  pWC->nSlot = ArraySize(pWC->aStatic);
86769  pWC->a = pWC->aStatic;
86770  pWC->vmask = 0;
86771}
86772
86773/* Forward reference */
86774static void whereClauseClear(WhereClause*);
86775
86776/*
86777** Deallocate all memory associated with a WhereOrInfo object.
86778*/
86779static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
86780  whereClauseClear(&p->wc);
86781  sqlite3DbFree(db, p);
86782}
86783
86784/*
86785** Deallocate all memory associated with a WhereAndInfo object.
86786*/
86787static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
86788  whereClauseClear(&p->wc);
86789  sqlite3DbFree(db, p);
86790}
86791
86792/*
86793** Deallocate a WhereClause structure.  The WhereClause structure
86794** itself is not freed.  This routine is the inverse of whereClauseInit().
86795*/
86796static void whereClauseClear(WhereClause *pWC){
86797  int i;
86798  WhereTerm *a;
86799  sqlite3 *db = pWC->pParse->db;
86800  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
86801    if( a->wtFlags & TERM_DYNAMIC ){
86802      sqlite3ExprDelete(db, a->pExpr);
86803    }
86804    if( a->wtFlags & TERM_ORINFO ){
86805      whereOrInfoDelete(db, a->u.pOrInfo);
86806    }else if( a->wtFlags & TERM_ANDINFO ){
86807      whereAndInfoDelete(db, a->u.pAndInfo);
86808    }
86809  }
86810  if( pWC->a!=pWC->aStatic ){
86811    sqlite3DbFree(db, pWC->a);
86812  }
86813}
86814
86815/*
86816** Add a single new WhereTerm entry to the WhereClause object pWC.
86817** The new WhereTerm object is constructed from Expr p and with wtFlags.
86818** The index in pWC->a[] of the new WhereTerm is returned on success.
86819** 0 is returned if the new WhereTerm could not be added due to a memory
86820** allocation error.  The memory allocation failure will be recorded in
86821** the db->mallocFailed flag so that higher-level functions can detect it.
86822**
86823** This routine will increase the size of the pWC->a[] array as necessary.
86824**
86825** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
86826** for freeing the expression p is assumed by the WhereClause object pWC.
86827** This is true even if this routine fails to allocate a new WhereTerm.
86828**
86829** WARNING:  This routine might reallocate the space used to store
86830** WhereTerms.  All pointers to WhereTerms should be invalidated after
86831** calling this routine.  Such pointers may be reinitialized by referencing
86832** the pWC->a[] array.
86833*/
86834static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
86835  WhereTerm *pTerm;
86836  int idx;
86837  if( pWC->nTerm>=pWC->nSlot ){
86838    WhereTerm *pOld = pWC->a;
86839    sqlite3 *db = pWC->pParse->db;
86840    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
86841    if( pWC->a==0 ){
86842      if( wtFlags & TERM_DYNAMIC ){
86843        sqlite3ExprDelete(db, p);
86844      }
86845      pWC->a = pOld;
86846      return 0;
86847    }
86848    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
86849    if( pOld!=pWC->aStatic ){
86850      sqlite3DbFree(db, pOld);
86851    }
86852    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
86853  }
86854  pTerm = &pWC->a[idx = pWC->nTerm++];
86855  pTerm->pExpr = p;
86856  pTerm->wtFlags = wtFlags;
86857  pTerm->pWC = pWC;
86858  pTerm->iParent = -1;
86859  return idx;
86860}
86861
86862/*
86863** This routine identifies subexpressions in the WHERE clause where
86864** each subexpression is separated by the AND operator or some other
86865** operator specified in the op parameter.  The WhereClause structure
86866** is filled with pointers to subexpressions.  For example:
86867**
86868**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
86869**           \________/     \_______________/     \________________/
86870**            slot[0]            slot[1]               slot[2]
86871**
86872** The original WHERE clause in pExpr is unaltered.  All this routine
86873** does is make slot[] entries point to substructure within pExpr.
86874**
86875** In the previous sentence and in the diagram, "slot[]" refers to
86876** the WhereClause.a[] array.  The slot[] array grows as needed to contain
86877** all terms of the WHERE clause.
86878*/
86879static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
86880  pWC->op = (u8)op;
86881  if( pExpr==0 ) return;
86882  if( pExpr->op!=op ){
86883    whereClauseInsert(pWC, pExpr, 0);
86884  }else{
86885    whereSplit(pWC, pExpr->pLeft, op);
86886    whereSplit(pWC, pExpr->pRight, op);
86887  }
86888}
86889
86890/*
86891** Initialize an expression mask set (a WhereMaskSet object)
86892*/
86893#define initMaskSet(P)  memset(P, 0, sizeof(*P))
86894
86895/*
86896** Return the bitmask for the given cursor number.  Return 0 if
86897** iCursor is not in the set.
86898*/
86899static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
86900  int i;
86901  assert( pMaskSet->n<=sizeof(Bitmask)*8 );
86902  for(i=0; i<pMaskSet->n; i++){
86903    if( pMaskSet->ix[i]==iCursor ){
86904      return ((Bitmask)1)<<i;
86905    }
86906  }
86907  return 0;
86908}
86909
86910/*
86911** Create a new mask for cursor iCursor.
86912**
86913** There is one cursor per table in the FROM clause.  The number of
86914** tables in the FROM clause is limited by a test early in the
86915** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
86916** array will never overflow.
86917*/
86918static void createMask(WhereMaskSet *pMaskSet, int iCursor){
86919  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
86920  pMaskSet->ix[pMaskSet->n++] = iCursor;
86921}
86922
86923/*
86924** This routine walks (recursively) an expression tree and generates
86925** a bitmask indicating which tables are used in that expression
86926** tree.
86927**
86928** In order for this routine to work, the calling function must have
86929** previously invoked sqlite3ResolveExprNames() on the expression.  See
86930** the header comment on that routine for additional information.
86931** The sqlite3ResolveExprNames() routines looks for column names and
86932** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
86933** the VDBE cursor number of the table.  This routine just has to
86934** translate the cursor numbers into bitmask values and OR all
86935** the bitmasks together.
86936*/
86937static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
86938static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
86939static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
86940  Bitmask mask = 0;
86941  if( p==0 ) return 0;
86942  if( p->op==TK_COLUMN ){
86943    mask = getMask(pMaskSet, p->iTable);
86944    return mask;
86945  }
86946  mask = exprTableUsage(pMaskSet, p->pRight);
86947  mask |= exprTableUsage(pMaskSet, p->pLeft);
86948  if( ExprHasProperty(p, EP_xIsSelect) ){
86949    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
86950  }else{
86951    mask |= exprListTableUsage(pMaskSet, p->x.pList);
86952  }
86953  return mask;
86954}
86955static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
86956  int i;
86957  Bitmask mask = 0;
86958  if( pList ){
86959    for(i=0; i<pList->nExpr; i++){
86960      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
86961    }
86962  }
86963  return mask;
86964}
86965static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
86966  Bitmask mask = 0;
86967  while( pS ){
86968    mask |= exprListTableUsage(pMaskSet, pS->pEList);
86969    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
86970    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
86971    mask |= exprTableUsage(pMaskSet, pS->pWhere);
86972    mask |= exprTableUsage(pMaskSet, pS->pHaving);
86973    pS = pS->pPrior;
86974  }
86975  return mask;
86976}
86977
86978/*
86979** Return TRUE if the given operator is one of the operators that is
86980** allowed for an indexable WHERE clause term.  The allowed operators are
86981** "=", "<", ">", "<=", ">=", and "IN".
86982*/
86983static int allowedOp(int op){
86984  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
86985  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
86986  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
86987  assert( TK_GE==TK_EQ+4 );
86988  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
86989}
86990
86991/*
86992** Swap two objects of type TYPE.
86993*/
86994#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
86995
86996/*
86997** Commute a comparison operator.  Expressions of the form "X op Y"
86998** are converted into "Y op X".
86999**
87000** If a collation sequence is associated with either the left or right
87001** side of the comparison, it remains associated with the same side after
87002** the commutation. So "Y collate NOCASE op X" becomes
87003** "X collate NOCASE op Y". This is because any collation sequence on
87004** the left hand side of a comparison overrides any collation sequence
87005** attached to the right. For the same reason the EP_ExpCollate flag
87006** is not commuted.
87007*/
87008static void exprCommute(Parse *pParse, Expr *pExpr){
87009  u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
87010  u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
87011  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
87012  pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
87013  pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
87014  SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
87015  pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
87016  pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
87017  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
87018  if( pExpr->op>=TK_GT ){
87019    assert( TK_LT==TK_GT+2 );
87020    assert( TK_GE==TK_LE+2 );
87021    assert( TK_GT>TK_EQ );
87022    assert( TK_GT<TK_LE );
87023    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
87024    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
87025  }
87026}
87027
87028/*
87029** Translate from TK_xx operator to WO_xx bitmask.
87030*/
87031static u16 operatorMask(int op){
87032  u16 c;
87033  assert( allowedOp(op) );
87034  if( op==TK_IN ){
87035    c = WO_IN;
87036  }else if( op==TK_ISNULL ){
87037    c = WO_ISNULL;
87038  }else{
87039    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
87040    c = (u16)(WO_EQ<<(op-TK_EQ));
87041  }
87042  assert( op!=TK_ISNULL || c==WO_ISNULL );
87043  assert( op!=TK_IN || c==WO_IN );
87044  assert( op!=TK_EQ || c==WO_EQ );
87045  assert( op!=TK_LT || c==WO_LT );
87046  assert( op!=TK_LE || c==WO_LE );
87047  assert( op!=TK_GT || c==WO_GT );
87048  assert( op!=TK_GE || c==WO_GE );
87049  return c;
87050}
87051
87052/*
87053** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
87054** where X is a reference to the iColumn of table iCur and <op> is one of
87055** the WO_xx operator codes specified by the op parameter.
87056** Return a pointer to the term.  Return 0 if not found.
87057*/
87058static WhereTerm *findTerm(
87059  WhereClause *pWC,     /* The WHERE clause to be searched */
87060  int iCur,             /* Cursor number of LHS */
87061  int iColumn,          /* Column number of LHS */
87062  Bitmask notReady,     /* RHS must not overlap with this mask */
87063  u32 op,               /* Mask of WO_xx values describing operator */
87064  Index *pIdx           /* Must be compatible with this index, if not NULL */
87065){
87066  WhereTerm *pTerm;
87067  int k;
87068  assert( iCur>=0 );
87069  op &= WO_ALL;
87070  for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
87071    if( pTerm->leftCursor==iCur
87072       && (pTerm->prereqRight & notReady)==0
87073       && pTerm->u.leftColumn==iColumn
87074       && (pTerm->eOperator & op)!=0
87075    ){
87076      if( pIdx && pTerm->eOperator!=WO_ISNULL ){
87077        Expr *pX = pTerm->pExpr;
87078        CollSeq *pColl;
87079        char idxaff;
87080        int j;
87081        Parse *pParse = pWC->pParse;
87082
87083        idxaff = pIdx->pTable->aCol[iColumn].affinity;
87084        if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
87085
87086        /* Figure out the collation sequence required from an index for
87087        ** it to be useful for optimising expression pX. Store this
87088        ** value in variable pColl.
87089        */
87090        assert(pX->pLeft);
87091        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
87092        assert(pColl || pParse->nErr);
87093
87094        for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
87095          if( NEVER(j>=pIdx->nColumn) ) return 0;
87096        }
87097        if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
87098      }
87099      return pTerm;
87100    }
87101  }
87102  return 0;
87103}
87104
87105/* Forward reference */
87106static void exprAnalyze(SrcList*, WhereClause*, int);
87107
87108/*
87109** Call exprAnalyze on all terms in a WHERE clause.
87110**
87111**
87112*/
87113static void exprAnalyzeAll(
87114  SrcList *pTabList,       /* the FROM clause */
87115  WhereClause *pWC         /* the WHERE clause to be analyzed */
87116){
87117  int i;
87118  for(i=pWC->nTerm-1; i>=0; i--){
87119    exprAnalyze(pTabList, pWC, i);
87120  }
87121}
87122
87123#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
87124/*
87125** Check to see if the given expression is a LIKE or GLOB operator that
87126** can be optimized using inequality constraints.  Return TRUE if it is
87127** so and false if not.
87128**
87129** In order for the operator to be optimizible, the RHS must be a string
87130** literal that does not begin with a wildcard.
87131*/
87132static int isLikeOrGlob(
87133  Parse *pParse,    /* Parsing and code generating context */
87134  Expr *pExpr,      /* Test this expression */
87135  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
87136  int *pisComplete, /* True if the only wildcard is % in the last character */
87137  int *pnoCase      /* True if uppercase is equivalent to lowercase */
87138){
87139  const char *z = 0;         /* String on RHS of LIKE operator */
87140  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
87141  ExprList *pList;           /* List of operands to the LIKE operator */
87142  int c;                     /* One character in z[] */
87143  int cnt;                   /* Number of non-wildcard prefix characters */
87144  char wc[3];                /* Wildcard characters */
87145  CollSeq *pColl;            /* Collating sequence for LHS */
87146  sqlite3 *db = pParse->db;  /* Database connection */
87147  sqlite3_value *pVal = 0;
87148  int op;                    /* Opcode of pRight */
87149
87150  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
87151    return 0;
87152  }
87153#ifdef SQLITE_EBCDIC
87154  if( *pnoCase ) return 0;
87155#endif
87156  pList = pExpr->x.pList;
87157  pLeft = pList->a[1].pExpr;
87158  if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
87159    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
87160    ** be the name of an indexed column with TEXT affinity. */
87161    return 0;
87162  }
87163  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
87164  pColl = sqlite3ExprCollSeq(pParse, pLeft);
87165  assert( pColl!=0 );  /* Every non-IPK column has a collating sequence */
87166  if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
87167      (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
87168    /* IMP: R-09003-32046 For the GLOB operator, the column must use the
87169    ** default BINARY collating sequence.
87170    ** IMP: R-41408-28306 For the LIKE operator, if case_sensitive_like mode
87171    ** is enabled then the column must use the default BINARY collating
87172    ** sequence, or if case_sensitive_like mode is disabled then the column
87173    ** must use the built-in NOCASE collating sequence.
87174    */
87175    return 0;
87176  }
87177
87178  pRight = pList->a[0].pExpr;
87179  op = pRight->op;
87180  if( op==TK_REGISTER ){
87181    op = pRight->op2;
87182  }
87183  if( op==TK_VARIABLE ){
87184    Vdbe *pReprepare = pParse->pReprepare;
87185    pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
87186    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
87187      z = (char *)sqlite3_value_text(pVal);
87188    }
87189    sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
87190    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
87191  }else if( op==TK_STRING ){
87192    z = pRight->u.zToken;
87193  }
87194  if( z ){
87195    cnt = 0;
87196    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
87197      cnt++;
87198    }
87199    if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
87200      Expr *pPrefix;
87201      *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
87202      pPrefix = sqlite3Expr(db, TK_STRING, z);
87203      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
87204      *ppPrefix = pPrefix;
87205      if( op==TK_VARIABLE ){
87206        Vdbe *v = pParse->pVdbe;
87207        sqlite3VdbeSetVarmask(v, pRight->iColumn);
87208        if( *pisComplete && pRight->u.zToken[1] ){
87209          /* If the rhs of the LIKE expression is a variable, and the current
87210          ** value of the variable means there is no need to invoke the LIKE
87211          ** function, then no OP_Variable will be added to the program.
87212          ** This causes problems for the sqlite3_bind_parameter_name()
87213          ** API. To workaround them, add a dummy OP_Variable here.
87214          */
87215          int r1 = sqlite3GetTempReg(pParse);
87216          sqlite3ExprCodeTarget(pParse, pRight, r1);
87217          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
87218          sqlite3ReleaseTempReg(pParse, r1);
87219        }
87220      }
87221    }else{
87222      z = 0;
87223    }
87224  }
87225
87226  sqlite3ValueFree(pVal);
87227  return (z!=0);
87228}
87229#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
87230
87231
87232#ifndef SQLITE_OMIT_VIRTUALTABLE
87233/*
87234** Check to see if the given expression is of the form
87235**
87236**         column MATCH expr
87237**
87238** If it is then return TRUE.  If not, return FALSE.
87239*/
87240static int isMatchOfColumn(
87241  Expr *pExpr      /* Test this expression */
87242){
87243  ExprList *pList;
87244
87245  if( pExpr->op!=TK_FUNCTION ){
87246    return 0;
87247  }
87248  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
87249    return 0;
87250  }
87251  pList = pExpr->x.pList;
87252  if( pList->nExpr!=2 ){
87253    return 0;
87254  }
87255  if( pList->a[1].pExpr->op != TK_COLUMN ){
87256    return 0;
87257  }
87258  return 1;
87259}
87260#endif /* SQLITE_OMIT_VIRTUALTABLE */
87261
87262/*
87263** If the pBase expression originated in the ON or USING clause of
87264** a join, then transfer the appropriate markings over to derived.
87265*/
87266static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
87267  pDerived->flags |= pBase->flags & EP_FromJoin;
87268  pDerived->iRightJoinTable = pBase->iRightJoinTable;
87269}
87270
87271#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
87272/*
87273** Analyze a term that consists of two or more OR-connected
87274** subterms.  So in:
87275**
87276**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
87277**                          ^^^^^^^^^^^^^^^^^^^^
87278**
87279** This routine analyzes terms such as the middle term in the above example.
87280** A WhereOrTerm object is computed and attached to the term under
87281** analysis, regardless of the outcome of the analysis.  Hence:
87282**
87283**     WhereTerm.wtFlags   |=  TERM_ORINFO
87284**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
87285**
87286** The term being analyzed must have two or more of OR-connected subterms.
87287** A single subterm might be a set of AND-connected sub-subterms.
87288** Examples of terms under analysis:
87289**
87290**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
87291**     (B)     x=expr1 OR expr2=x OR x=expr3
87292**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
87293**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
87294**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
87295**
87296** CASE 1:
87297**
87298** If all subterms are of the form T.C=expr for some single column of C
87299** a single table T (as shown in example B above) then create a new virtual
87300** term that is an equivalent IN expression.  In other words, if the term
87301** being analyzed is:
87302**
87303**      x = expr1  OR  expr2 = x  OR  x = expr3
87304**
87305** then create a new virtual term like this:
87306**
87307**      x IN (expr1,expr2,expr3)
87308**
87309** CASE 2:
87310**
87311** If all subterms are indexable by a single table T, then set
87312**
87313**     WhereTerm.eOperator              =  WO_OR
87314**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
87315**
87316** A subterm is "indexable" if it is of the form
87317** "T.C <op> <expr>" where C is any column of table T and
87318** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
87319** A subterm is also indexable if it is an AND of two or more
87320** subsubterms at least one of which is indexable.  Indexable AND
87321** subterms have their eOperator set to WO_AND and they have
87322** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
87323**
87324** From another point of view, "indexable" means that the subterm could
87325** potentially be used with an index if an appropriate index exists.
87326** This analysis does not consider whether or not the index exists; that
87327** is something the bestIndex() routine will determine.  This analysis
87328** only looks at whether subterms appropriate for indexing exist.
87329**
87330** All examples A through E above all satisfy case 2.  But if a term
87331** also statisfies case 1 (such as B) we know that the optimizer will
87332** always prefer case 1, so in that case we pretend that case 2 is not
87333** satisfied.
87334**
87335** It might be the case that multiple tables are indexable.  For example,
87336** (E) above is indexable on tables P, Q, and R.
87337**
87338** Terms that satisfy case 2 are candidates for lookup by using
87339** separate indices to find rowids for each subterm and composing
87340** the union of all rowids using a RowSet object.  This is similar
87341** to "bitmap indices" in other database engines.
87342**
87343** OTHERWISE:
87344**
87345** If neither case 1 nor case 2 apply, then leave the eOperator set to
87346** zero.  This term is not useful for search.
87347*/
87348static void exprAnalyzeOrTerm(
87349  SrcList *pSrc,            /* the FROM clause */
87350  WhereClause *pWC,         /* the complete WHERE clause */
87351  int idxTerm               /* Index of the OR-term to be analyzed */
87352){
87353  Parse *pParse = pWC->pParse;            /* Parser context */
87354  sqlite3 *db = pParse->db;               /* Database connection */
87355  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
87356  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
87357  WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
87358  int i;                                  /* Loop counters */
87359  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
87360  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
87361  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
87362  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
87363  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
87364
87365  /*
87366  ** Break the OR clause into its separate subterms.  The subterms are
87367  ** stored in a WhereClause structure containing within the WhereOrInfo
87368  ** object that is attached to the original OR clause term.
87369  */
87370  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
87371  assert( pExpr->op==TK_OR );
87372  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
87373  if( pOrInfo==0 ) return;
87374  pTerm->wtFlags |= TERM_ORINFO;
87375  pOrWc = &pOrInfo->wc;
87376  whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
87377  whereSplit(pOrWc, pExpr, TK_OR);
87378  exprAnalyzeAll(pSrc, pOrWc);
87379  if( db->mallocFailed ) return;
87380  assert( pOrWc->nTerm>=2 );
87381
87382  /*
87383  ** Compute the set of tables that might satisfy cases 1 or 2.
87384  */
87385  indexable = ~(Bitmask)0;
87386  chngToIN = ~(pWC->vmask);
87387  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
87388    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
87389      WhereAndInfo *pAndInfo;
87390      assert( pOrTerm->eOperator==0 );
87391      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
87392      chngToIN = 0;
87393      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
87394      if( pAndInfo ){
87395        WhereClause *pAndWC;
87396        WhereTerm *pAndTerm;
87397        int j;
87398        Bitmask b = 0;
87399        pOrTerm->u.pAndInfo = pAndInfo;
87400        pOrTerm->wtFlags |= TERM_ANDINFO;
87401        pOrTerm->eOperator = WO_AND;
87402        pAndWC = &pAndInfo->wc;
87403        whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
87404        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
87405        exprAnalyzeAll(pSrc, pAndWC);
87406        testcase( db->mallocFailed );
87407        if( !db->mallocFailed ){
87408          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
87409            assert( pAndTerm->pExpr );
87410            if( allowedOp(pAndTerm->pExpr->op) ){
87411              b |= getMask(pMaskSet, pAndTerm->leftCursor);
87412            }
87413          }
87414        }
87415        indexable &= b;
87416      }
87417    }else if( pOrTerm->wtFlags & TERM_COPIED ){
87418      /* Skip this term for now.  We revisit it when we process the
87419      ** corresponding TERM_VIRTUAL term */
87420    }else{
87421      Bitmask b;
87422      b = getMask(pMaskSet, pOrTerm->leftCursor);
87423      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
87424        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
87425        b |= getMask(pMaskSet, pOther->leftCursor);
87426      }
87427      indexable &= b;
87428      if( pOrTerm->eOperator!=WO_EQ ){
87429        chngToIN = 0;
87430      }else{
87431        chngToIN &= b;
87432      }
87433    }
87434  }
87435
87436  /*
87437  ** Record the set of tables that satisfy case 2.  The set might be
87438  ** empty.
87439  */
87440  pOrInfo->indexable = indexable;
87441  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
87442
87443  /*
87444  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
87445  ** we have to do some additional checking to see if case 1 really
87446  ** is satisfied.
87447  **
87448  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
87449  ** that there is no possibility of transforming the OR clause into an
87450  ** IN operator because one or more terms in the OR clause contain
87451  ** something other than == on a column in the single table.  The 1-bit
87452  ** case means that every term of the OR clause is of the form
87453  ** "table.column=expr" for some single table.  The one bit that is set
87454  ** will correspond to the common table.  We still need to check to make
87455  ** sure the same column is used on all terms.  The 2-bit case is when
87456  ** the all terms are of the form "table1.column=table2.column".  It
87457  ** might be possible to form an IN operator with either table1.column
87458  ** or table2.column as the LHS if either is common to every term of
87459  ** the OR clause.
87460  **
87461  ** Note that terms of the form "table.column1=table.column2" (the
87462  ** same table on both sizes of the ==) cannot be optimized.
87463  */
87464  if( chngToIN ){
87465    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
87466    int iColumn = -1;         /* Column index on lhs of IN operator */
87467    int iCursor = -1;         /* Table cursor common to all terms */
87468    int j = 0;                /* Loop counter */
87469
87470    /* Search for a table and column that appears on one side or the
87471    ** other of the == operator in every subterm.  That table and column
87472    ** will be recorded in iCursor and iColumn.  There might not be any
87473    ** such table and column.  Set okToChngToIN if an appropriate table
87474    ** and column is found but leave okToChngToIN false if not found.
87475    */
87476    for(j=0; j<2 && !okToChngToIN; j++){
87477      pOrTerm = pOrWc->a;
87478      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
87479        assert( pOrTerm->eOperator==WO_EQ );
87480        pOrTerm->wtFlags &= ~TERM_OR_OK;
87481        if( pOrTerm->leftCursor==iCursor ){
87482          /* This is the 2-bit case and we are on the second iteration and
87483          ** current term is from the first iteration.  So skip this term. */
87484          assert( j==1 );
87485          continue;
87486        }
87487        if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
87488          /* This term must be of the form t1.a==t2.b where t2 is in the
87489          ** chngToIN set but t1 is not.  This term will be either preceeded
87490          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
87491          ** and use its inversion. */
87492          testcase( pOrTerm->wtFlags & TERM_COPIED );
87493          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
87494          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
87495          continue;
87496        }
87497        iColumn = pOrTerm->u.leftColumn;
87498        iCursor = pOrTerm->leftCursor;
87499        break;
87500      }
87501      if( i<0 ){
87502        /* No candidate table+column was found.  This can only occur
87503        ** on the second iteration */
87504        assert( j==1 );
87505        assert( (chngToIN&(chngToIN-1))==0 );
87506        assert( chngToIN==getMask(pMaskSet, iCursor) );
87507        break;
87508      }
87509      testcase( j==1 );
87510
87511      /* We have found a candidate table and column.  Check to see if that
87512      ** table and column is common to every term in the OR clause */
87513      okToChngToIN = 1;
87514      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
87515        assert( pOrTerm->eOperator==WO_EQ );
87516        if( pOrTerm->leftCursor!=iCursor ){
87517          pOrTerm->wtFlags &= ~TERM_OR_OK;
87518        }else if( pOrTerm->u.leftColumn!=iColumn ){
87519          okToChngToIN = 0;
87520        }else{
87521          int affLeft, affRight;
87522          /* If the right-hand side is also a column, then the affinities
87523          ** of both right and left sides must be such that no type
87524          ** conversions are required on the right.  (Ticket #2249)
87525          */
87526          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
87527          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
87528          if( affRight!=0 && affRight!=affLeft ){
87529            okToChngToIN = 0;
87530          }else{
87531            pOrTerm->wtFlags |= TERM_OR_OK;
87532          }
87533        }
87534      }
87535    }
87536
87537    /* At this point, okToChngToIN is true if original pTerm satisfies
87538    ** case 1.  In that case, construct a new virtual term that is
87539    ** pTerm converted into an IN operator.
87540    */
87541    if( okToChngToIN ){
87542      Expr *pDup;            /* A transient duplicate expression */
87543      ExprList *pList = 0;   /* The RHS of the IN operator */
87544      Expr *pLeft = 0;       /* The LHS of the IN operator */
87545      Expr *pNew;            /* The complete IN operator */
87546
87547      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
87548        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
87549        assert( pOrTerm->eOperator==WO_EQ );
87550        assert( pOrTerm->leftCursor==iCursor );
87551        assert( pOrTerm->u.leftColumn==iColumn );
87552        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
87553        pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
87554        pLeft = pOrTerm->pExpr->pLeft;
87555      }
87556      assert( pLeft!=0 );
87557      pDup = sqlite3ExprDup(db, pLeft, 0);
87558      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
87559      if( pNew ){
87560        int idxNew;
87561        transferJoinMarkings(pNew, pExpr);
87562        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
87563        pNew->x.pList = pList;
87564        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
87565        testcase( idxNew==0 );
87566        exprAnalyze(pSrc, pWC, idxNew);
87567        pTerm = &pWC->a[idxTerm];
87568        pWC->a[idxNew].iParent = idxTerm;
87569        pTerm->nChild = 1;
87570      }else{
87571        sqlite3ExprListDelete(db, pList);
87572      }
87573      pTerm->eOperator = 0;  /* case 1 trumps case 2 */
87574    }
87575  }
87576}
87577#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
87578
87579
87580/*
87581** The input to this routine is an WhereTerm structure with only the
87582** "pExpr" field filled in.  The job of this routine is to analyze the
87583** subexpression and populate all the other fields of the WhereTerm
87584** structure.
87585**
87586** If the expression is of the form "<expr> <op> X" it gets commuted
87587** to the standard form of "X <op> <expr>".
87588**
87589** If the expression is of the form "X <op> Y" where both X and Y are
87590** columns, then the original expression is unchanged and a new virtual
87591** term of the form "Y <op> X" is added to the WHERE clause and
87592** analyzed separately.  The original term is marked with TERM_COPIED
87593** and the new term is marked with TERM_DYNAMIC (because it's pExpr
87594** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
87595** is a commuted copy of a prior term.)  The original term has nChild=1
87596** and the copy has idxParent set to the index of the original term.
87597*/
87598static void exprAnalyze(
87599  SrcList *pSrc,            /* the FROM clause */
87600  WhereClause *pWC,         /* the WHERE clause */
87601  int idxTerm               /* Index of the term to be analyzed */
87602){
87603  WhereTerm *pTerm;                /* The term to be analyzed */
87604  WhereMaskSet *pMaskSet;          /* Set of table index masks */
87605  Expr *pExpr;                     /* The expression to be analyzed */
87606  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
87607  Bitmask prereqAll;               /* Prerequesites of pExpr */
87608  Bitmask extraRight = 0;          /* */
87609  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
87610  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
87611  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
87612  int op;                          /* Top-level operator.  pExpr->op */
87613  Parse *pParse = pWC->pParse;     /* Parsing context */
87614  sqlite3 *db = pParse->db;        /* Database connection */
87615
87616  if( db->mallocFailed ){
87617    return;
87618  }
87619  pTerm = &pWC->a[idxTerm];
87620  pMaskSet = pWC->pMaskSet;
87621  pExpr = pTerm->pExpr;
87622  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
87623  op = pExpr->op;
87624  if( op==TK_IN ){
87625    assert( pExpr->pRight==0 );
87626    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
87627      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
87628    }else{
87629      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
87630    }
87631  }else if( op==TK_ISNULL ){
87632    pTerm->prereqRight = 0;
87633  }else{
87634    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
87635  }
87636  prereqAll = exprTableUsage(pMaskSet, pExpr);
87637  if( ExprHasProperty(pExpr, EP_FromJoin) ){
87638    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
87639    prereqAll |= x;
87640    extraRight = x-1;  /* ON clause terms may not be used with an index
87641                       ** on left table of a LEFT JOIN.  Ticket #3015 */
87642  }
87643  pTerm->prereqAll = prereqAll;
87644  pTerm->leftCursor = -1;
87645  pTerm->iParent = -1;
87646  pTerm->eOperator = 0;
87647  if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
87648    Expr *pLeft = pExpr->pLeft;
87649    Expr *pRight = pExpr->pRight;
87650    if( pLeft->op==TK_COLUMN ){
87651      pTerm->leftCursor = pLeft->iTable;
87652      pTerm->u.leftColumn = pLeft->iColumn;
87653      pTerm->eOperator = operatorMask(op);
87654    }
87655    if( pRight && pRight->op==TK_COLUMN ){
87656      WhereTerm *pNew;
87657      Expr *pDup;
87658      if( pTerm->leftCursor>=0 ){
87659        int idxNew;
87660        pDup = sqlite3ExprDup(db, pExpr, 0);
87661        if( db->mallocFailed ){
87662          sqlite3ExprDelete(db, pDup);
87663          return;
87664        }
87665        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
87666        if( idxNew==0 ) return;
87667        pNew = &pWC->a[idxNew];
87668        pNew->iParent = idxTerm;
87669        pTerm = &pWC->a[idxTerm];
87670        pTerm->nChild = 1;
87671        pTerm->wtFlags |= TERM_COPIED;
87672      }else{
87673        pDup = pExpr;
87674        pNew = pTerm;
87675      }
87676      exprCommute(pParse, pDup);
87677      pLeft = pDup->pLeft;
87678      pNew->leftCursor = pLeft->iTable;
87679      pNew->u.leftColumn = pLeft->iColumn;
87680      pNew->prereqRight = prereqLeft;
87681      pNew->prereqAll = prereqAll;
87682      pNew->eOperator = operatorMask(pDup->op);
87683    }
87684  }
87685
87686#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
87687  /* If a term is the BETWEEN operator, create two new virtual terms
87688  ** that define the range that the BETWEEN implements.  For example:
87689  **
87690  **      a BETWEEN b AND c
87691  **
87692  ** is converted into:
87693  **
87694  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
87695  **
87696  ** The two new terms are added onto the end of the WhereClause object.
87697  ** The new terms are "dynamic" and are children of the original BETWEEN
87698  ** term.  That means that if the BETWEEN term is coded, the children are
87699  ** skipped.  Or, if the children are satisfied by an index, the original
87700  ** BETWEEN term is skipped.
87701  */
87702  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
87703    ExprList *pList = pExpr->x.pList;
87704    int i;
87705    static const u8 ops[] = {TK_GE, TK_LE};
87706    assert( pList!=0 );
87707    assert( pList->nExpr==2 );
87708    for(i=0; i<2; i++){
87709      Expr *pNewExpr;
87710      int idxNew;
87711      pNewExpr = sqlite3PExpr(pParse, ops[i],
87712                             sqlite3ExprDup(db, pExpr->pLeft, 0),
87713                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
87714      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
87715      testcase( idxNew==0 );
87716      exprAnalyze(pSrc, pWC, idxNew);
87717      pTerm = &pWC->a[idxTerm];
87718      pWC->a[idxNew].iParent = idxTerm;
87719    }
87720    pTerm->nChild = 2;
87721  }
87722#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
87723
87724#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
87725  /* Analyze a term that is composed of two or more subterms connected by
87726  ** an OR operator.
87727  */
87728  else if( pExpr->op==TK_OR ){
87729    assert( pWC->op==TK_AND );
87730    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
87731    pTerm = &pWC->a[idxTerm];
87732  }
87733#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
87734
87735#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
87736  /* Add constraints to reduce the search space on a LIKE or GLOB
87737  ** operator.
87738  **
87739  ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
87740  **
87741  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
87742  **
87743  ** The last character of the prefix "abc" is incremented to form the
87744  ** termination condition "abd".
87745  */
87746  if( pWC->op==TK_AND
87747   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
87748  ){
87749    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
87750    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
87751    Expr *pNewExpr1;
87752    Expr *pNewExpr2;
87753    int idxNew1;
87754    int idxNew2;
87755
87756    pLeft = pExpr->x.pList->a[1].pExpr;
87757    pStr2 = sqlite3ExprDup(db, pStr1, 0);
87758    if( !db->mallocFailed ){
87759      u8 c, *pC;       /* Last character before the first wildcard */
87760      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
87761      c = *pC;
87762      if( noCase ){
87763        /* The point is to increment the last character before the first
87764        ** wildcard.  But if we increment '@', that will push it into the
87765        ** alphabetic range where case conversions will mess up the
87766        ** inequality.  To avoid this, make sure to also run the full
87767        ** LIKE on all candidate expressions by clearing the isComplete flag
87768        */
87769        if( c=='A'-1 ) isComplete = 0;
87770
87771        c = sqlite3UpperToLower[c];
87772      }
87773      *pC = c + 1;
87774    }
87775    pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
87776    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
87777    testcase( idxNew1==0 );
87778    exprAnalyze(pSrc, pWC, idxNew1);
87779    pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
87780    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
87781    testcase( idxNew2==0 );
87782    exprAnalyze(pSrc, pWC, idxNew2);
87783    pTerm = &pWC->a[idxTerm];
87784    if( isComplete ){
87785      pWC->a[idxNew1].iParent = idxTerm;
87786      pWC->a[idxNew2].iParent = idxTerm;
87787      pTerm->nChild = 2;
87788    }
87789  }
87790#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
87791
87792#ifndef SQLITE_OMIT_VIRTUALTABLE
87793  /* Add a WO_MATCH auxiliary term to the constraint set if the
87794  ** current expression is of the form:  column MATCH expr.
87795  ** This information is used by the xBestIndex methods of
87796  ** virtual tables.  The native query optimizer does not attempt
87797  ** to do anything with MATCH functions.
87798  */
87799  if( isMatchOfColumn(pExpr) ){
87800    int idxNew;
87801    Expr *pRight, *pLeft;
87802    WhereTerm *pNewTerm;
87803    Bitmask prereqColumn, prereqExpr;
87804
87805    pRight = pExpr->x.pList->a[0].pExpr;
87806    pLeft = pExpr->x.pList->a[1].pExpr;
87807    prereqExpr = exprTableUsage(pMaskSet, pRight);
87808    prereqColumn = exprTableUsage(pMaskSet, pLeft);
87809    if( (prereqExpr & prereqColumn)==0 ){
87810      Expr *pNewExpr;
87811      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
87812                              0, sqlite3ExprDup(db, pRight, 0), 0);
87813      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
87814      testcase( idxNew==0 );
87815      pNewTerm = &pWC->a[idxNew];
87816      pNewTerm->prereqRight = prereqExpr;
87817      pNewTerm->leftCursor = pLeft->iTable;
87818      pNewTerm->u.leftColumn = pLeft->iColumn;
87819      pNewTerm->eOperator = WO_MATCH;
87820      pNewTerm->iParent = idxTerm;
87821      pTerm = &pWC->a[idxTerm];
87822      pTerm->nChild = 1;
87823      pTerm->wtFlags |= TERM_COPIED;
87824      pNewTerm->prereqAll = pTerm->prereqAll;
87825    }
87826  }
87827#endif /* SQLITE_OMIT_VIRTUALTABLE */
87828
87829  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
87830  ** an index for tables to the left of the join.
87831  */
87832  pTerm->prereqRight |= extraRight;
87833}
87834
87835/*
87836** Return TRUE if any of the expressions in pList->a[iFirst...] contain
87837** a reference to any table other than the iBase table.
87838*/
87839static int referencesOtherTables(
87840  ExprList *pList,          /* Search expressions in ths list */
87841  WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
87842  int iFirst,               /* Be searching with the iFirst-th expression */
87843  int iBase                 /* Ignore references to this table */
87844){
87845  Bitmask allowed = ~getMask(pMaskSet, iBase);
87846  while( iFirst<pList->nExpr ){
87847    if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
87848      return 1;
87849    }
87850  }
87851  return 0;
87852}
87853
87854
87855/*
87856** This routine decides if pIdx can be used to satisfy the ORDER BY
87857** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
87858** ORDER BY clause, this routine returns 0.
87859**
87860** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
87861** left-most table in the FROM clause of that same SELECT statement and
87862** the table has a cursor number of "base".  pIdx is an index on pTab.
87863**
87864** nEqCol is the number of columns of pIdx that are used as equality
87865** constraints.  Any of these columns may be missing from the ORDER BY
87866** clause and the match can still be a success.
87867**
87868** All terms of the ORDER BY that match against the index must be either
87869** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
87870** index do not need to satisfy this constraint.)  The *pbRev value is
87871** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
87872** the ORDER BY clause is all ASC.
87873*/
87874static int isSortingIndex(
87875  Parse *pParse,          /* Parsing context */
87876  WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
87877  Index *pIdx,            /* The index we are testing */
87878  int base,               /* Cursor number for the table to be sorted */
87879  ExprList *pOrderBy,     /* The ORDER BY clause */
87880  int nEqCol,             /* Number of index columns with == constraints */
87881  int *pbRev              /* Set to 1 if ORDER BY is DESC */
87882){
87883  int i, j;                       /* Loop counters */
87884  int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
87885  int nTerm;                      /* Number of ORDER BY terms */
87886  struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
87887  sqlite3 *db = pParse->db;
87888
87889  assert( pOrderBy!=0 );
87890  nTerm = pOrderBy->nExpr;
87891  assert( nTerm>0 );
87892
87893  /* Argument pIdx must either point to a 'real' named index structure,
87894  ** or an index structure allocated on the stack by bestBtreeIndex() to
87895  ** represent the rowid index that is part of every table.  */
87896  assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
87897
87898  /* Match terms of the ORDER BY clause against columns of
87899  ** the index.
87900  **
87901  ** Note that indices have pIdx->nColumn regular columns plus
87902  ** one additional column containing the rowid.  The rowid column
87903  ** of the index is also allowed to match against the ORDER BY
87904  ** clause.
87905  */
87906  for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
87907    Expr *pExpr;       /* The expression of the ORDER BY pTerm */
87908    CollSeq *pColl;    /* The collating sequence of pExpr */
87909    int termSortOrder; /* Sort order for this term */
87910    int iColumn;       /* The i-th column of the index.  -1 for rowid */
87911    int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
87912    const char *zColl; /* Name of the collating sequence for i-th index term */
87913
87914    pExpr = pTerm->pExpr;
87915    if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
87916      /* Can not use an index sort on anything that is not a column in the
87917      ** left-most table of the FROM clause */
87918      break;
87919    }
87920    pColl = sqlite3ExprCollSeq(pParse, pExpr);
87921    if( !pColl ){
87922      pColl = db->pDfltColl;
87923    }
87924    if( pIdx->zName && i<pIdx->nColumn ){
87925      iColumn = pIdx->aiColumn[i];
87926      if( iColumn==pIdx->pTable->iPKey ){
87927        iColumn = -1;
87928      }
87929      iSortOrder = pIdx->aSortOrder[i];
87930      zColl = pIdx->azColl[i];
87931    }else{
87932      iColumn = -1;
87933      iSortOrder = 0;
87934      zColl = pColl->zName;
87935    }
87936    if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
87937      /* Term j of the ORDER BY clause does not match column i of the index */
87938      if( i<nEqCol ){
87939        /* If an index column that is constrained by == fails to match an
87940        ** ORDER BY term, that is OK.  Just ignore that column of the index
87941        */
87942        continue;
87943      }else if( i==pIdx->nColumn ){
87944        /* Index column i is the rowid.  All other terms match. */
87945        break;
87946      }else{
87947        /* If an index column fails to match and is not constrained by ==
87948        ** then the index cannot satisfy the ORDER BY constraint.
87949        */
87950        return 0;
87951      }
87952    }
87953    assert( pIdx->aSortOrder!=0 || iColumn==-1 );
87954    assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
87955    assert( iSortOrder==0 || iSortOrder==1 );
87956    termSortOrder = iSortOrder ^ pTerm->sortOrder;
87957    if( i>nEqCol ){
87958      if( termSortOrder!=sortOrder ){
87959        /* Indices can only be used if all ORDER BY terms past the
87960        ** equality constraints are all either DESC or ASC. */
87961        return 0;
87962      }
87963    }else{
87964      sortOrder = termSortOrder;
87965    }
87966    j++;
87967    pTerm++;
87968    if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
87969      /* If the indexed column is the primary key and everything matches
87970      ** so far and none of the ORDER BY terms to the right reference other
87971      ** tables in the join, then we are assured that the index can be used
87972      ** to sort because the primary key is unique and so none of the other
87973      ** columns will make any difference
87974      */
87975      j = nTerm;
87976    }
87977  }
87978
87979  *pbRev = sortOrder!=0;
87980  if( j>=nTerm ){
87981    /* All terms of the ORDER BY clause are covered by this index so
87982    ** this index can be used for sorting. */
87983    return 1;
87984  }
87985  if( pIdx->onError!=OE_None && i==pIdx->nColumn
87986      && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
87987    /* All terms of this index match some prefix of the ORDER BY clause
87988    ** and the index is UNIQUE and no terms on the tail of the ORDER BY
87989    ** clause reference other tables in a join.  If this is all true then
87990    ** the order by clause is superfluous. */
87991    return 1;
87992  }
87993  return 0;
87994}
87995
87996/*
87997** Prepare a crude estimate of the logarithm of the input value.
87998** The results need not be exact.  This is only used for estimating
87999** the total cost of performing operations with O(logN) or O(NlogN)
88000** complexity.  Because N is just a guess, it is no great tragedy if
88001** logN is a little off.
88002*/
88003static double estLog(double N){
88004  double logN = 1;
88005  double x = 10;
88006  while( N>x ){
88007    logN += 1;
88008    x *= 10;
88009  }
88010  return logN;
88011}
88012
88013/*
88014** Two routines for printing the content of an sqlite3_index_info
88015** structure.  Used for testing and debugging only.  If neither
88016** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
88017** are no-ops.
88018*/
88019#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
88020static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
88021  int i;
88022  if( !sqlite3WhereTrace ) return;
88023  for(i=0; i<p->nConstraint; i++){
88024    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
88025       i,
88026       p->aConstraint[i].iColumn,
88027       p->aConstraint[i].iTermOffset,
88028       p->aConstraint[i].op,
88029       p->aConstraint[i].usable);
88030  }
88031  for(i=0; i<p->nOrderBy; i++){
88032    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
88033       i,
88034       p->aOrderBy[i].iColumn,
88035       p->aOrderBy[i].desc);
88036  }
88037}
88038static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
88039  int i;
88040  if( !sqlite3WhereTrace ) return;
88041  for(i=0; i<p->nConstraint; i++){
88042    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
88043       i,
88044       p->aConstraintUsage[i].argvIndex,
88045       p->aConstraintUsage[i].omit);
88046  }
88047  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
88048  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
88049  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
88050  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
88051}
88052#else
88053#define TRACE_IDX_INPUTS(A)
88054#define TRACE_IDX_OUTPUTS(A)
88055#endif
88056
88057/*
88058** Required because bestIndex() is called by bestOrClauseIndex()
88059*/
88060static void bestIndex(
88061    Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
88062
88063/*
88064** This routine attempts to find an scanning strategy that can be used
88065** to optimize an 'OR' expression that is part of a WHERE clause.
88066**
88067** The table associated with FROM clause term pSrc may be either a
88068** regular B-Tree table or a virtual table.
88069*/
88070static void bestOrClauseIndex(
88071  Parse *pParse,              /* The parsing context */
88072  WhereClause *pWC,           /* The WHERE clause */
88073  struct SrcList_item *pSrc,  /* The FROM clause term to search */
88074  Bitmask notReady,           /* Mask of cursors that are not available */
88075  ExprList *pOrderBy,         /* The ORDER BY clause */
88076  WhereCost *pCost            /* Lowest cost query plan */
88077){
88078#ifndef SQLITE_OMIT_OR_OPTIMIZATION
88079  const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
88080  const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
88081  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
88082  WhereTerm *pTerm;                 /* A single term of the WHERE clause */
88083
88084  /* Search the WHERE clause terms for a usable WO_OR term. */
88085  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
88086    if( pTerm->eOperator==WO_OR
88087     && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
88088     && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
88089    ){
88090      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
88091      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
88092      WhereTerm *pOrTerm;
88093      int flags = WHERE_MULTI_OR;
88094      double rTotal = 0;
88095      double nRow = 0;
88096      Bitmask used = 0;
88097
88098      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
88099        WhereCost sTermCost;
88100        WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
88101          (pOrTerm - pOrWC->a), (pTerm - pWC->a)
88102        ));
88103        if( pOrTerm->eOperator==WO_AND ){
88104          WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
88105          bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
88106        }else if( pOrTerm->leftCursor==iCur ){
88107          WhereClause tempWC;
88108          tempWC.pParse = pWC->pParse;
88109          tempWC.pMaskSet = pWC->pMaskSet;
88110          tempWC.op = TK_AND;
88111          tempWC.a = pOrTerm;
88112          tempWC.nTerm = 1;
88113          bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
88114        }else{
88115          continue;
88116        }
88117        rTotal += sTermCost.rCost;
88118        nRow += sTermCost.nRow;
88119        used |= sTermCost.used;
88120        if( rTotal>=pCost->rCost ) break;
88121      }
88122
88123      /* If there is an ORDER BY clause, increase the scan cost to account
88124      ** for the cost of the sort. */
88125      if( pOrderBy!=0 ){
88126        rTotal += nRow*estLog(nRow);
88127        WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
88128      }
88129
88130      /* If the cost of scanning using this OR term for optimization is
88131      ** less than the current cost stored in pCost, replace the contents
88132      ** of pCost. */
88133      WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
88134      if( rTotal<pCost->rCost ){
88135        pCost->rCost = rTotal;
88136        pCost->nRow = nRow;
88137        pCost->used = used;
88138        pCost->plan.wsFlags = flags;
88139        pCost->plan.u.pTerm = pTerm;
88140      }
88141    }
88142  }
88143#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
88144}
88145
88146#ifndef SQLITE_OMIT_VIRTUALTABLE
88147/*
88148** Allocate and populate an sqlite3_index_info structure. It is the
88149** responsibility of the caller to eventually release the structure
88150** by passing the pointer returned by this function to sqlite3_free().
88151*/
88152static sqlite3_index_info *allocateIndexInfo(
88153  Parse *pParse,
88154  WhereClause *pWC,
88155  struct SrcList_item *pSrc,
88156  ExprList *pOrderBy
88157){
88158  int i, j;
88159  int nTerm;
88160  struct sqlite3_index_constraint *pIdxCons;
88161  struct sqlite3_index_orderby *pIdxOrderBy;
88162  struct sqlite3_index_constraint_usage *pUsage;
88163  WhereTerm *pTerm;
88164  int nOrderBy;
88165  sqlite3_index_info *pIdxInfo;
88166
88167  WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
88168
88169  /* Count the number of possible WHERE clause constraints referring
88170  ** to this virtual table */
88171  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
88172    if( pTerm->leftCursor != pSrc->iCursor ) continue;
88173    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
88174    testcase( pTerm->eOperator==WO_IN );
88175    testcase( pTerm->eOperator==WO_ISNULL );
88176    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
88177    nTerm++;
88178  }
88179
88180  /* If the ORDER BY clause contains only columns in the current
88181  ** virtual table then allocate space for the aOrderBy part of
88182  ** the sqlite3_index_info structure.
88183  */
88184  nOrderBy = 0;
88185  if( pOrderBy ){
88186    for(i=0; i<pOrderBy->nExpr; i++){
88187      Expr *pExpr = pOrderBy->a[i].pExpr;
88188      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
88189    }
88190    if( i==pOrderBy->nExpr ){
88191      nOrderBy = pOrderBy->nExpr;
88192    }
88193  }
88194
88195  /* Allocate the sqlite3_index_info structure
88196  */
88197  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
88198                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
88199                           + sizeof(*pIdxOrderBy)*nOrderBy );
88200  if( pIdxInfo==0 ){
88201    sqlite3ErrorMsg(pParse, "out of memory");
88202    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
88203    return 0;
88204  }
88205
88206  /* Initialize the structure.  The sqlite3_index_info structure contains
88207  ** many fields that are declared "const" to prevent xBestIndex from
88208  ** changing them.  We have to do some funky casting in order to
88209  ** initialize those fields.
88210  */
88211  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
88212  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
88213  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
88214  *(int*)&pIdxInfo->nConstraint = nTerm;
88215  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
88216  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
88217  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
88218  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
88219                                                                   pUsage;
88220
88221  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
88222    if( pTerm->leftCursor != pSrc->iCursor ) continue;
88223    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
88224    testcase( pTerm->eOperator==WO_IN );
88225    testcase( pTerm->eOperator==WO_ISNULL );
88226    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
88227    pIdxCons[j].iColumn = pTerm->u.leftColumn;
88228    pIdxCons[j].iTermOffset = i;
88229    pIdxCons[j].op = (u8)pTerm->eOperator;
88230    /* The direct assignment in the previous line is possible only because
88231    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
88232    ** following asserts verify this fact. */
88233    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
88234    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
88235    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
88236    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
88237    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
88238    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
88239    assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
88240    j++;
88241  }
88242  for(i=0; i<nOrderBy; i++){
88243    Expr *pExpr = pOrderBy->a[i].pExpr;
88244    pIdxOrderBy[i].iColumn = pExpr->iColumn;
88245    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
88246  }
88247
88248  return pIdxInfo;
88249}
88250
88251/*
88252** The table object reference passed as the second argument to this function
88253** must represent a virtual table. This function invokes the xBestIndex()
88254** method of the virtual table with the sqlite3_index_info pointer passed
88255** as the argument.
88256**
88257** If an error occurs, pParse is populated with an error message and a
88258** non-zero value is returned. Otherwise, 0 is returned and the output
88259** part of the sqlite3_index_info structure is left populated.
88260**
88261** Whether or not an error is returned, it is the responsibility of the
88262** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
88263** that this is required.
88264*/
88265static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
88266  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
88267  int i;
88268  int rc;
88269
88270  (void)sqlite3SafetyOff(pParse->db);
88271  WHERETRACE(("xBestIndex for %s\n", pTab->zName));
88272  TRACE_IDX_INPUTS(p);
88273  rc = pVtab->pModule->xBestIndex(pVtab, p);
88274  TRACE_IDX_OUTPUTS(p);
88275  (void)sqlite3SafetyOn(pParse->db);
88276
88277  if( rc!=SQLITE_OK ){
88278    if( rc==SQLITE_NOMEM ){
88279      pParse->db->mallocFailed = 1;
88280    }else if( !pVtab->zErrMsg ){
88281      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
88282    }else{
88283      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
88284    }
88285  }
88286  sqlite3DbFree(pParse->db, pVtab->zErrMsg);
88287  pVtab->zErrMsg = 0;
88288
88289  for(i=0; i<p->nConstraint; i++){
88290    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
88291      sqlite3ErrorMsg(pParse,
88292          "table %s: xBestIndex returned an invalid plan", pTab->zName);
88293    }
88294  }
88295
88296  return pParse->nErr;
88297}
88298
88299
88300/*
88301** Compute the best index for a virtual table.
88302**
88303** The best index is computed by the xBestIndex method of the virtual
88304** table module.  This routine is really just a wrapper that sets up
88305** the sqlite3_index_info structure that is used to communicate with
88306** xBestIndex.
88307**
88308** In a join, this routine might be called multiple times for the
88309** same virtual table.  The sqlite3_index_info structure is created
88310** and initialized on the first invocation and reused on all subsequent
88311** invocations.  The sqlite3_index_info structure is also used when
88312** code is generated to access the virtual table.  The whereInfoDelete()
88313** routine takes care of freeing the sqlite3_index_info structure after
88314** everybody has finished with it.
88315*/
88316static void bestVirtualIndex(
88317  Parse *pParse,                  /* The parsing context */
88318  WhereClause *pWC,               /* The WHERE clause */
88319  struct SrcList_item *pSrc,      /* The FROM clause term to search */
88320  Bitmask notReady,               /* Mask of cursors that are not available */
88321  ExprList *pOrderBy,             /* The order by clause */
88322  WhereCost *pCost,               /* Lowest cost query plan */
88323  sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
88324){
88325  Table *pTab = pSrc->pTab;
88326  sqlite3_index_info *pIdxInfo;
88327  struct sqlite3_index_constraint *pIdxCons;
88328  struct sqlite3_index_constraint_usage *pUsage;
88329  WhereTerm *pTerm;
88330  int i, j;
88331  int nOrderBy;
88332
88333  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
88334  ** malloc in allocateIndexInfo() fails and this function returns leaving
88335  ** wsFlags in an uninitialized state, the caller may behave unpredictably.
88336  */
88337  memset(pCost, 0, sizeof(*pCost));
88338  pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
88339
88340  /* If the sqlite3_index_info structure has not been previously
88341  ** allocated and initialized, then allocate and initialize it now.
88342  */
88343  pIdxInfo = *ppIdxInfo;
88344  if( pIdxInfo==0 ){
88345    *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
88346  }
88347  if( pIdxInfo==0 ){
88348    return;
88349  }
88350
88351  /* At this point, the sqlite3_index_info structure that pIdxInfo points
88352  ** to will have been initialized, either during the current invocation or
88353  ** during some prior invocation.  Now we just have to customize the
88354  ** details of pIdxInfo for the current invocation and pass it to
88355  ** xBestIndex.
88356  */
88357
88358  /* The module name must be defined. Also, by this point there must
88359  ** be a pointer to an sqlite3_vtab structure. Otherwise
88360  ** sqlite3ViewGetColumnNames() would have picked up the error.
88361  */
88362  assert( pTab->azModuleArg && pTab->azModuleArg[0] );
88363  assert( sqlite3GetVTable(pParse->db, pTab) );
88364
88365  /* Set the aConstraint[].usable fields and initialize all
88366  ** output variables to zero.
88367  **
88368  ** aConstraint[].usable is true for constraints where the right-hand
88369  ** side contains only references to tables to the left of the current
88370  ** table.  In other words, if the constraint is of the form:
88371  **
88372  **           column = expr
88373  **
88374  ** and we are evaluating a join, then the constraint on column is
88375  ** only valid if all tables referenced in expr occur to the left
88376  ** of the table containing column.
88377  **
88378  ** The aConstraints[] array contains entries for all constraints
88379  ** on the current table.  That way we only have to compute it once
88380  ** even though we might try to pick the best index multiple times.
88381  ** For each attempt at picking an index, the order of tables in the
88382  ** join might be different so we have to recompute the usable flag
88383  ** each time.
88384  */
88385  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
88386  pUsage = pIdxInfo->aConstraintUsage;
88387  for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
88388    j = pIdxCons->iTermOffset;
88389    pTerm = &pWC->a[j];
88390    pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
88391  }
88392  memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
88393  if( pIdxInfo->needToFreeIdxStr ){
88394    sqlite3_free(pIdxInfo->idxStr);
88395  }
88396  pIdxInfo->idxStr = 0;
88397  pIdxInfo->idxNum = 0;
88398  pIdxInfo->needToFreeIdxStr = 0;
88399  pIdxInfo->orderByConsumed = 0;
88400  /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
88401  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
88402  nOrderBy = pIdxInfo->nOrderBy;
88403  if( !pOrderBy ){
88404    pIdxInfo->nOrderBy = 0;
88405  }
88406
88407  if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
88408    return;
88409  }
88410
88411  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
88412  for(i=0; i<pIdxInfo->nConstraint; i++){
88413    if( pUsage[i].argvIndex>0 ){
88414      pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
88415    }
88416  }
88417
88418  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
88419  ** inital value of lowestCost in this loop. If it is, then the
88420  ** (cost<lowestCost) test below will never be true.
88421  **
88422  ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
88423  ** is defined.
88424  */
88425  if( (SQLITE_BIG_DBL/((double)2))<pIdxInfo->estimatedCost ){
88426    pCost->rCost = (SQLITE_BIG_DBL/((double)2));
88427  }else{
88428    pCost->rCost = pIdxInfo->estimatedCost;
88429  }
88430  pCost->plan.u.pVtabIdx = pIdxInfo;
88431  if( pIdxInfo->orderByConsumed ){
88432    pCost->plan.wsFlags |= WHERE_ORDERBY;
88433  }
88434  pCost->plan.nEq = 0;
88435  pIdxInfo->nOrderBy = nOrderBy;
88436
88437  /* Try to find a more efficient access pattern by using multiple indexes
88438  ** to optimize an OR expression within the WHERE clause.
88439  */
88440  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
88441}
88442#endif /* SQLITE_OMIT_VIRTUALTABLE */
88443
88444/*
88445** Argument pIdx is a pointer to an index structure that has an array of
88446** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
88447** stored in Index.aSample. The domain of values stored in said column
88448** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
88449** Region 0 contains all values smaller than the first sample value. Region
88450** 1 contains values larger than or equal to the value of the first sample,
88451** but smaller than the value of the second. And so on.
88452**
88453** If successful, this function determines which of the regions value
88454** pVal lies in, sets *piRegion to the region index (a value between 0
88455** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
88456** Or, if an OOM occurs while converting text values between encodings,
88457** SQLITE_NOMEM is returned and *piRegion is undefined.
88458*/
88459#ifdef SQLITE_ENABLE_STAT2
88460static int whereRangeRegion(
88461  Parse *pParse,              /* Database connection */
88462  Index *pIdx,                /* Index to consider domain of */
88463  sqlite3_value *pVal,        /* Value to consider */
88464  int *piRegion               /* OUT: Region of domain in which value lies */
88465){
88466  if( ALWAYS(pVal) ){
88467    IndexSample *aSample = pIdx->aSample;
88468    int i = 0;
88469    int eType = sqlite3_value_type(pVal);
88470
88471    if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
88472      double r = sqlite3_value_double(pVal);
88473      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
88474        if( aSample[i].eType==SQLITE_NULL ) continue;
88475        if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
88476      }
88477    }else{
88478      sqlite3 *db = pParse->db;
88479      CollSeq *pColl;
88480      const u8 *z;
88481      int n;
88482
88483      /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
88484      assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
88485
88486      if( eType==SQLITE_BLOB ){
88487        z = (const u8 *)sqlite3_value_blob(pVal);
88488        pColl = db->pDfltColl;
88489        assert( pColl->enc==SQLITE_UTF8 );
88490      }else{
88491        pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
88492        if( pColl==0 ){
88493          sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
88494                          *pIdx->azColl);
88495          return SQLITE_ERROR;
88496        }
88497        z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
88498        if( !z ){
88499          return SQLITE_NOMEM;
88500        }
88501        assert( z && pColl && pColl->xCmp );
88502      }
88503      n = sqlite3ValueBytes(pVal, pColl->enc);
88504
88505      for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
88506        int r;
88507        int eSampletype = aSample[i].eType;
88508        if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
88509        if( (eSampletype!=eType) ) break;
88510#ifndef SQLITE_OMIT_UTF16
88511        if( pColl->enc!=SQLITE_UTF8 ){
88512          int nSample;
88513          char *zSample = sqlite3Utf8to16(
88514              db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
88515          );
88516          if( !zSample ){
88517            assert( db->mallocFailed );
88518            return SQLITE_NOMEM;
88519          }
88520          r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
88521          sqlite3DbFree(db, zSample);
88522        }else
88523#endif
88524        {
88525          r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
88526        }
88527        if( r>0 ) break;
88528      }
88529    }
88530
88531    assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
88532    *piRegion = i;
88533  }
88534  return SQLITE_OK;
88535}
88536#endif   /* #ifdef SQLITE_ENABLE_STAT2 */
88537
88538/*
88539** If expression pExpr represents a literal value, set *pp to point to
88540** an sqlite3_value structure containing the same value, with affinity
88541** aff applied to it, before returning. It is the responsibility of the
88542** caller to eventually release this structure by passing it to
88543** sqlite3ValueFree().
88544**
88545** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
88546** is an SQL variable that currently has a non-NULL value bound to it,
88547** create an sqlite3_value structure containing this value, again with
88548** affinity aff applied to it, instead.
88549**
88550** If neither of the above apply, set *pp to NULL.
88551**
88552** If an error occurs, return an error code. Otherwise, SQLITE_OK.
88553*/
88554#ifdef SQLITE_ENABLE_STAT2
88555static int valueFromExpr(
88556  Parse *pParse,
88557  Expr *pExpr,
88558  u8 aff,
88559  sqlite3_value **pp
88560){
88561  /* The evalConstExpr() function will have already converted any TK_VARIABLE
88562  ** expression involved in an comparison into a TK_REGISTER. */
88563  assert( pExpr->op!=TK_VARIABLE );
88564  if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
88565    int iVar = pExpr->iColumn;
88566    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
88567    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
88568    return SQLITE_OK;
88569  }
88570  return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
88571}
88572#endif
88573
88574/*
88575** This function is used to estimate the number of rows that will be visited
88576** by scanning an index for a range of values. The range may have an upper
88577** bound, a lower bound, or both. The WHERE clause terms that set the upper
88578** and lower bounds are represented by pLower and pUpper respectively. For
88579** example, assuming that index p is on t1(a):
88580**
88581**   ... FROM t1 WHERE a > ? AND a < ? ...
88582**                    |_____|   |_____|
88583**                       |         |
88584**                     pLower    pUpper
88585**
88586** If either of the upper or lower bound is not present, then NULL is passed in
88587** place of the corresponding WhereTerm.
88588**
88589** The nEq parameter is passed the index of the index column subject to the
88590** range constraint. Or, equivalently, the number of equality constraints
88591** optimized by the proposed index scan. For example, assuming index p is
88592** on t1(a, b), and the SQL query is:
88593**
88594**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
88595**
88596** then nEq should be passed the value 1 (as the range restricted column,
88597** b, is the second left-most column of the index). Or, if the query is:
88598**
88599**   ... FROM t1 WHERE a > ? AND a < ? ...
88600**
88601** then nEq should be passed 0.
88602**
88603** The returned value is an integer between 1 and 100, inclusive. A return
88604** value of 1 indicates that the proposed range scan is expected to visit
88605** approximately 1/100th (1%) of the rows selected by the nEq equality
88606** constraints (if any). A return value of 100 indicates that it is expected
88607** that the range scan will visit every row (100%) selected by the equality
88608** constraints.
88609**
88610** In the absence of sqlite_stat2 ANALYZE data, each range inequality
88611** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
88612** results in a return of 33 and a range constraint (x>? AND x<?) results
88613** in a return of 11.
88614*/
88615static int whereRangeScanEst(
88616  Parse *pParse,       /* Parsing & code generating context */
88617  Index *p,            /* The index containing the range-compared column; "x" */
88618  int nEq,             /* index into p->aCol[] of the range-compared column */
88619  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
88620  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
88621  int *piEst           /* OUT: Return value */
88622){
88623  int rc = SQLITE_OK;
88624
88625#ifdef SQLITE_ENABLE_STAT2
88626
88627  if( nEq==0 && p->aSample ){
88628    sqlite3_value *pLowerVal = 0;
88629    sqlite3_value *pUpperVal = 0;
88630    int iEst;
88631    int iLower = 0;
88632    int iUpper = SQLITE_INDEX_SAMPLES;
88633    u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
88634
88635    if( pLower ){
88636      Expr *pExpr = pLower->pExpr->pRight;
88637      rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
88638    }
88639    if( rc==SQLITE_OK && pUpper ){
88640      Expr *pExpr = pUpper->pExpr->pRight;
88641      rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
88642    }
88643
88644    if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
88645      sqlite3ValueFree(pLowerVal);
88646      sqlite3ValueFree(pUpperVal);
88647      goto range_est_fallback;
88648    }else if( pLowerVal==0 ){
88649      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
88650      if( pLower ) iLower = iUpper/2;
88651    }else if( pUpperVal==0 ){
88652      rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
88653      if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
88654    }else{
88655      rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
88656      if( rc==SQLITE_OK ){
88657        rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
88658      }
88659    }
88660
88661    iEst = iUpper - iLower;
88662    testcase( iEst==SQLITE_INDEX_SAMPLES );
88663    assert( iEst<=SQLITE_INDEX_SAMPLES );
88664    if( iEst<1 ){
88665      iEst = 1;
88666    }
88667
88668    sqlite3ValueFree(pLowerVal);
88669    sqlite3ValueFree(pUpperVal);
88670    *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
88671    return rc;
88672  }
88673range_est_fallback:
88674#else
88675  UNUSED_PARAMETER(pParse);
88676  UNUSED_PARAMETER(p);
88677  UNUSED_PARAMETER(nEq);
88678#endif
88679  assert( pLower || pUpper );
88680  if( pLower && pUpper ){
88681    *piEst = 11;
88682  }else{
88683    *piEst = 33;
88684  }
88685  return rc;
88686}
88687
88688
88689/*
88690** Find the query plan for accessing a particular table.  Write the
88691** best query plan and its cost into the WhereCost object supplied as the
88692** last parameter.
88693**
88694** The lowest cost plan wins.  The cost is an estimate of the amount of
88695** CPU and disk I/O need to process the request using the selected plan.
88696** Factors that influence cost include:
88697**
88698**    *  The estimated number of rows that will be retrieved.  (The
88699**       fewer the better.)
88700**
88701**    *  Whether or not sorting must occur.
88702**
88703**    *  Whether or not there must be separate lookups in the
88704**       index and in the main table.
88705**
88706** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
88707** the SQL statement, then this function only considers plans using the
88708** named index. If no such plan is found, then the returned cost is
88709** SQLITE_BIG_DBL. If a plan is found that uses the named index,
88710** then the cost is calculated in the usual way.
88711**
88712** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
88713** in the SELECT statement, then no indexes are considered. However, the
88714** selected plan may still take advantage of the tables built-in rowid
88715** index.
88716*/
88717static void bestBtreeIndex(
88718  Parse *pParse,              /* The parsing context */
88719  WhereClause *pWC,           /* The WHERE clause */
88720  struct SrcList_item *pSrc,  /* The FROM clause term to search */
88721  Bitmask notReady,           /* Mask of cursors that are not available */
88722  ExprList *pOrderBy,         /* The ORDER BY clause */
88723  WhereCost *pCost            /* Lowest cost query plan */
88724){
88725  int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
88726  Index *pProbe;              /* An index we are evaluating */
88727  Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
88728  int eqTermMask;             /* Current mask of valid equality operators */
88729  int idxEqTermMask;          /* Index mask of valid equality operators */
88730  Index sPk;                  /* A fake index object for the primary key */
88731  unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
88732  int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
88733  int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
88734
88735  /* Initialize the cost to a worst-case value */
88736  memset(pCost, 0, sizeof(*pCost));
88737  pCost->rCost = SQLITE_BIG_DBL;
88738
88739  /* If the pSrc table is the right table of a LEFT JOIN then we may not
88740  ** use an index to satisfy IS NULL constraints on that table.  This is
88741  ** because columns might end up being NULL if the table does not match -
88742  ** a circumstance which the index cannot help us discover.  Ticket #2177.
88743  */
88744  if( pSrc->jointype & JT_LEFT ){
88745    idxEqTermMask = WO_EQ|WO_IN;
88746  }else{
88747    idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
88748  }
88749
88750  if( pSrc->pIndex ){
88751    /* An INDEXED BY clause specifies a particular index to use */
88752    pIdx = pProbe = pSrc->pIndex;
88753    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
88754    eqTermMask = idxEqTermMask;
88755  }else{
88756    /* There is no INDEXED BY clause.  Create a fake Index object to
88757    ** represent the primary key */
88758    Index *pFirst;                /* Any other index on the table */
88759    memset(&sPk, 0, sizeof(Index));
88760    sPk.nColumn = 1;
88761    sPk.aiColumn = &aiColumnPk;
88762    sPk.aiRowEst = aiRowEstPk;
88763    aiRowEstPk[1] = 1;
88764    sPk.onError = OE_Replace;
88765    sPk.pTable = pSrc->pTab;
88766    pFirst = pSrc->pTab->pIndex;
88767    if( pSrc->notIndexed==0 ){
88768      sPk.pNext = pFirst;
88769    }
88770    /* The aiRowEstPk[0] is an estimate of the total number of rows in the
88771    ** table.  Get this information from the ANALYZE information if it is
88772    ** available.  If not available, assume the table 1 million rows in size.
88773    */
88774    if( pFirst ){
88775      assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
88776      aiRowEstPk[0] = pFirst->aiRowEst[0];
88777    }else{
88778      aiRowEstPk[0] = 1000000;
88779    }
88780    pProbe = &sPk;
88781    wsFlagMask = ~(
88782        WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
88783    );
88784    eqTermMask = WO_EQ|WO_IN;
88785    pIdx = 0;
88786  }
88787
88788  /* Loop over all indices looking for the best one to use
88789  */
88790  for(; pProbe; pIdx=pProbe=pProbe->pNext){
88791    const unsigned int * const aiRowEst = pProbe->aiRowEst;
88792    double cost;                /* Cost of using pProbe */
88793    double nRow;                /* Estimated number of rows in result set */
88794    int rev;                    /* True to scan in reverse order */
88795    int wsFlags = 0;
88796    Bitmask used = 0;
88797
88798    /* The following variables are populated based on the properties of
88799    ** scan being evaluated. They are then used to determine the expected
88800    ** cost and number of rows returned.
88801    **
88802    **  nEq:
88803    **    Number of equality terms that can be implemented using the index.
88804    **
88805    **  nInMul:
88806    **    The "in-multiplier". This is an estimate of how many seek operations
88807    **    SQLite must perform on the index in question. For example, if the
88808    **    WHERE clause is:
88809    **
88810    **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
88811    **
88812    **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
88813    **    set to 9. Given the same schema and either of the following WHERE
88814    **    clauses:
88815    **
88816    **      WHERE a =  1
88817    **      WHERE a >= 2
88818    **
88819    **    nInMul is set to 1.
88820    **
88821    **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
88822    **    the sub-select is assumed to return 25 rows for the purposes of
88823    **    determining nInMul.
88824    **
88825    **  bInEst:
88826    **    Set to true if there was at least one "x IN (SELECT ...)" term used
88827    **    in determining the value of nInMul.
88828    **
88829    **  nBound:
88830    **    An estimate on the amount of the table that must be searched.  A
88831    **    value of 100 means the entire table is searched.  Range constraints
88832    **    might reduce this to a value less than 100 to indicate that only
88833    **    a fraction of the table needs searching.  In the absence of
88834    **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
88835    **    space to 1/3rd its original size.  So an x>? constraint reduces
88836    **    nBound to 33.  Two constraints (x>? AND x<?) reduce nBound to 11.
88837    **
88838    **  bSort:
88839    **    Boolean. True if there is an ORDER BY clause that will require an
88840    **    external sort (i.e. scanning the index being evaluated will not
88841    **    correctly order records).
88842    **
88843    **  bLookup:
88844    **    Boolean. True if for each index entry visited a lookup on the
88845    **    corresponding table b-tree is required. This is always false
88846    **    for the rowid index. For other indexes, it is true unless all the
88847    **    columns of the table used by the SELECT statement are present in
88848    **    the index (such an index is sometimes described as a covering index).
88849    **    For example, given the index on (a, b), the second of the following
88850    **    two queries requires table b-tree lookups, but the first does not.
88851    **
88852    **             SELECT a, b    FROM tbl WHERE a = 1;
88853    **             SELECT a, b, c FROM tbl WHERE a = 1;
88854    */
88855    int nEq;
88856    int bInEst = 0;
88857    int nInMul = 1;
88858    int nBound = 100;
88859    int bSort = 0;
88860    int bLookup = 0;
88861
88862    /* Determine the values of nEq and nInMul */
88863    for(nEq=0; nEq<pProbe->nColumn; nEq++){
88864      WhereTerm *pTerm;           /* A single term of the WHERE clause */
88865      int j = pProbe->aiColumn[nEq];
88866      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
88867      if( pTerm==0 ) break;
88868      wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
88869      if( pTerm->eOperator & WO_IN ){
88870        Expr *pExpr = pTerm->pExpr;
88871        wsFlags |= WHERE_COLUMN_IN;
88872        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88873          nInMul *= 25;
88874          bInEst = 1;
88875        }else if( pExpr->x.pList ){
88876          nInMul *= pExpr->x.pList->nExpr + 1;
88877        }
88878      }else if( pTerm->eOperator & WO_ISNULL ){
88879        wsFlags |= WHERE_COLUMN_NULL;
88880      }
88881      used |= pTerm->prereqRight;
88882    }
88883
88884    /* Determine the value of nBound. */
88885    if( nEq<pProbe->nColumn ){
88886      int j = pProbe->aiColumn[nEq];
88887      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
88888        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
88889        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
88890        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &nBound);
88891        if( pTop ){
88892          wsFlags |= WHERE_TOP_LIMIT;
88893          used |= pTop->prereqRight;
88894        }
88895        if( pBtm ){
88896          wsFlags |= WHERE_BTM_LIMIT;
88897          used |= pBtm->prereqRight;
88898        }
88899        wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
88900      }
88901    }else if( pProbe->onError!=OE_None ){
88902      testcase( wsFlags & WHERE_COLUMN_IN );
88903      testcase( wsFlags & WHERE_COLUMN_NULL );
88904      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
88905        wsFlags |= WHERE_UNIQUE;
88906      }
88907    }
88908
88909    /* If there is an ORDER BY clause and the index being considered will
88910    ** naturally scan rows in the required order, set the appropriate flags
88911    ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
88912    ** will scan rows in a different order, set the bSort variable.  */
88913    if( pOrderBy ){
88914      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
88915        && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
88916      ){
88917        wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
88918        wsFlags |= (rev ? WHERE_REVERSE : 0);
88919      }else{
88920        bSort = 1;
88921      }
88922    }
88923
88924    /* If currently calculating the cost of using an index (not the IPK
88925    ** index), determine if all required column data may be obtained without
88926    ** seeking to entries in the main table (i.e. if the index is a covering
88927    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
88928    ** wsFlags. Otherwise, set the bLookup variable to true.  */
88929    if( pIdx && wsFlags ){
88930      Bitmask m = pSrc->colUsed;
88931      int j;
88932      for(j=0; j<pIdx->nColumn; j++){
88933        int x = pIdx->aiColumn[j];
88934        if( x<BMS-1 ){
88935          m &= ~(((Bitmask)1)<<x);
88936        }
88937      }
88938      if( m==0 ){
88939        wsFlags |= WHERE_IDX_ONLY;
88940      }else{
88941        bLookup = 1;
88942      }
88943    }
88944
88945    /**** Begin adding up the cost of using this index (Needs improvements)
88946    **
88947    ** Estimate the number of rows of output.  For an IN operator,
88948    ** do not let the estimate exceed half the rows in the table.
88949    */
88950    nRow = (double)(aiRowEst[nEq] * nInMul);
88951    if( bInEst && nRow*2>aiRowEst[0] ){
88952      nRow = aiRowEst[0]/2;
88953      nInMul = (int)(nRow / aiRowEst[nEq]);
88954    }
88955
88956    /* Assume constant cost to access a row and logarithmic cost to
88957    ** do a binary search.  Hence, the initial cost is the number of output
88958    ** rows plus log2(table-size) times the number of binary searches.
88959    */
88960    cost = nRow + nInMul*estLog(aiRowEst[0]);
88961
88962    /* Adjust the number of rows and the cost downward to reflect rows
88963    ** that are excluded by range constraints.
88964    */
88965    nRow = (nRow * (double)nBound) / (double)100;
88966    cost = (cost * (double)nBound) / (double)100;
88967
88968    /* Add in the estimated cost of sorting the result
88969    */
88970    if( bSort ){
88971      cost += cost*estLog(cost);
88972    }
88973
88974    /* If all information can be taken directly from the index, we avoid
88975    ** doing table lookups.  This reduces the cost by half.  (Not really -
88976    ** this needs to be fixed.)
88977    */
88978    if( pIdx && bLookup==0 ){
88979      cost /= (double)2;
88980    }
88981    /**** Cost of using this index has now been computed ****/
88982
88983    WHERETRACE((
88984      "tbl=%s idx=%s nEq=%d nInMul=%d nBound=%d bSort=%d bLookup=%d"
88985      " wsFlags=%d   (nRow=%.2f cost=%.2f)\n",
88986      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
88987      nEq, nInMul, nBound, bSort, bLookup, wsFlags, nRow, cost
88988    ));
88989
88990    /* If this index is the best we have seen so far, then record this
88991    ** index and its cost in the pCost structure.
88992    */
88993    if( (!pIdx || wsFlags) && cost<pCost->rCost ){
88994      pCost->rCost = cost;
88995      pCost->nRow = nRow;
88996      pCost->used = used;
88997      pCost->plan.wsFlags = (wsFlags&wsFlagMask);
88998      pCost->plan.nEq = nEq;
88999      pCost->plan.u.pIdx = pIdx;
89000    }
89001
89002    /* If there was an INDEXED BY clause, then only that one index is
89003    ** considered. */
89004    if( pSrc->pIndex ) break;
89005
89006    /* Reset masks for the next index in the loop */
89007    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
89008    eqTermMask = idxEqTermMask;
89009  }
89010
89011  /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
89012  ** is set, then reverse the order that the index will be scanned
89013  ** in. This is used for application testing, to help find cases
89014  ** where application behaviour depends on the (undefined) order that
89015  ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
89016  if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
89017    pCost->plan.wsFlags |= WHERE_REVERSE;
89018  }
89019
89020  assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
89021  assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
89022  assert( pSrc->pIndex==0
89023       || pCost->plan.u.pIdx==0
89024       || pCost->plan.u.pIdx==pSrc->pIndex
89025  );
89026
89027  WHERETRACE(("best index is: %s\n",
89028    (pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
89029  ));
89030
89031  bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
89032  pCost->plan.wsFlags |= eqTermMask;
89033}
89034
89035/*
89036** Find the query plan for accessing table pSrc->pTab. Write the
89037** best query plan and its cost into the WhereCost object supplied
89038** as the last parameter. This function may calculate the cost of
89039** both real and virtual table scans.
89040*/
89041static void bestIndex(
89042  Parse *pParse,              /* The parsing context */
89043  WhereClause *pWC,           /* The WHERE clause */
89044  struct SrcList_item *pSrc,  /* The FROM clause term to search */
89045  Bitmask notReady,           /* Mask of cursors that are not available */
89046  ExprList *pOrderBy,         /* The ORDER BY clause */
89047  WhereCost *pCost            /* Lowest cost query plan */
89048){
89049#ifndef SQLITE_OMIT_VIRTUALTABLE
89050  if( IsVirtual(pSrc->pTab) ){
89051    sqlite3_index_info *p = 0;
89052    bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
89053    if( p->needToFreeIdxStr ){
89054      sqlite3_free(p->idxStr);
89055    }
89056    sqlite3DbFree(pParse->db, p);
89057  }else
89058#endif
89059  {
89060    bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
89061  }
89062}
89063
89064/*
89065** Disable a term in the WHERE clause.  Except, do not disable the term
89066** if it controls a LEFT OUTER JOIN and it did not originate in the ON
89067** or USING clause of that join.
89068**
89069** Consider the term t2.z='ok' in the following queries:
89070**
89071**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
89072**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
89073**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
89074**
89075** The t2.z='ok' is disabled in the in (2) because it originates
89076** in the ON clause.  The term is disabled in (3) because it is not part
89077** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
89078**
89079** Disabling a term causes that term to not be tested in the inner loop
89080** of the join.  Disabling is an optimization.  When terms are satisfied
89081** by indices, we disable them to prevent redundant tests in the inner
89082** loop.  We would get the correct results if nothing were ever disabled,
89083** but joins might run a little slower.  The trick is to disable as much
89084** as we can without disabling too much.  If we disabled in (1), we'd get
89085** the wrong answer.  See ticket #813.
89086*/
89087static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
89088  if( pTerm
89089      && ALWAYS((pTerm->wtFlags & TERM_CODED)==0)
89090      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
89091  ){
89092    pTerm->wtFlags |= TERM_CODED;
89093    if( pTerm->iParent>=0 ){
89094      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
89095      if( (--pOther->nChild)==0 ){
89096        disableTerm(pLevel, pOther);
89097      }
89098    }
89099  }
89100}
89101
89102/*
89103** Code an OP_Affinity opcode to apply the column affinity string zAff
89104** to the n registers starting at base.
89105**
89106** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
89107** beginning and end of zAff are ignored.  If all entries in zAff are
89108** SQLITE_AFF_NONE, then no code gets generated.
89109**
89110** This routine makes its own copy of zAff so that the caller is free
89111** to modify zAff after this routine returns.
89112*/
89113static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
89114  Vdbe *v = pParse->pVdbe;
89115  if( zAff==0 ){
89116    assert( pParse->db->mallocFailed );
89117    return;
89118  }
89119  assert( v!=0 );
89120
89121  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
89122  ** and end of the affinity string.
89123  */
89124  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
89125    n--;
89126    base++;
89127    zAff++;
89128  }
89129  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
89130    n--;
89131  }
89132
89133  /* Code the OP_Affinity opcode if there is anything left to do. */
89134  if( n>0 ){
89135    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
89136    sqlite3VdbeChangeP4(v, -1, zAff, n);
89137    sqlite3ExprCacheAffinityChange(pParse, base, n);
89138  }
89139}
89140
89141
89142/*
89143** Generate code for a single equality term of the WHERE clause.  An equality
89144** term can be either X=expr or X IN (...).   pTerm is the term to be
89145** coded.
89146**
89147** The current value for the constraint is left in register iReg.
89148**
89149** For a constraint of the form X=expr, the expression is evaluated and its
89150** result is left on the stack.  For constraints of the form X IN (...)
89151** this routine sets up a loop that will iterate over all values of X.
89152*/
89153static int codeEqualityTerm(
89154  Parse *pParse,      /* The parsing context */
89155  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
89156  WhereLevel *pLevel, /* When level of the FROM clause we are working on */
89157  int iTarget         /* Attempt to leave results in this register */
89158){
89159  Expr *pX = pTerm->pExpr;
89160  Vdbe *v = pParse->pVdbe;
89161  int iReg;                  /* Register holding results */
89162
89163  assert( iTarget>0 );
89164  if( pX->op==TK_EQ ){
89165    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
89166  }else if( pX->op==TK_ISNULL ){
89167    iReg = iTarget;
89168    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
89169#ifndef SQLITE_OMIT_SUBQUERY
89170  }else{
89171    int eType;
89172    int iTab;
89173    struct InLoop *pIn;
89174
89175    assert( pX->op==TK_IN );
89176    iReg = iTarget;
89177    eType = sqlite3FindInIndex(pParse, pX, 0);
89178    iTab = pX->iTable;
89179    sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
89180    assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
89181    if( pLevel->u.in.nIn==0 ){
89182      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
89183    }
89184    pLevel->u.in.nIn++;
89185    pLevel->u.in.aInLoop =
89186       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
89187                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
89188    pIn = pLevel->u.in.aInLoop;
89189    if( pIn ){
89190      pIn += pLevel->u.in.nIn - 1;
89191      pIn->iCur = iTab;
89192      if( eType==IN_INDEX_ROWID ){
89193        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
89194      }else{
89195        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
89196      }
89197      sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
89198    }else{
89199      pLevel->u.in.nIn = 0;
89200    }
89201#endif
89202  }
89203  disableTerm(pLevel, pTerm);
89204  return iReg;
89205}
89206
89207/*
89208** Generate code that will evaluate all == and IN constraints for an
89209** index.
89210**
89211** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
89212** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
89213** The index has as many as three equality constraints, but in this
89214** example, the third "c" value is an inequality.  So only two
89215** constraints are coded.  This routine will generate code to evaluate
89216** a==5 and b IN (1,2,3).  The current values for a and b will be stored
89217** in consecutive registers and the index of the first register is returned.
89218**
89219** In the example above nEq==2.  But this subroutine works for any value
89220** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
89221** The only thing it does is allocate the pLevel->iMem memory cell and
89222** compute the affinity string.
89223**
89224** This routine always allocates at least one memory cell and returns
89225** the index of that memory cell. The code that
89226** calls this routine will use that memory cell to store the termination
89227** key value of the loop.  If one or more IN operators appear, then
89228** this routine allocates an additional nEq memory cells for internal
89229** use.
89230**
89231** Before returning, *pzAff is set to point to a buffer containing a
89232** copy of the column affinity string of the index allocated using
89233** sqlite3DbMalloc(). Except, entries in the copy of the string associated
89234** with equality constraints that use NONE affinity are set to
89235** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
89236**
89237**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
89238**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
89239**
89240** In the example above, the index on t1(a) has TEXT affinity. But since
89241** the right hand side of the equality constraint (t2.b) has NONE affinity,
89242** no conversion should be attempted before using a t2.b value as part of
89243** a key to search the index. Hence the first byte in the returned affinity
89244** string in this example would be set to SQLITE_AFF_NONE.
89245*/
89246static int codeAllEqualityTerms(
89247  Parse *pParse,        /* Parsing context */
89248  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
89249  WhereClause *pWC,     /* The WHERE clause */
89250  Bitmask notReady,     /* Which parts of FROM have not yet been coded */
89251  int nExtraReg,        /* Number of extra registers to allocate */
89252  char **pzAff          /* OUT: Set to point to affinity string */
89253){
89254  int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
89255  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
89256  Index *pIdx;                  /* The index being used for this loop */
89257  int iCur = pLevel->iTabCur;   /* The cursor of the table */
89258  WhereTerm *pTerm;             /* A single constraint term */
89259  int j;                        /* Loop counter */
89260  int regBase;                  /* Base register */
89261  int nReg;                     /* Number of registers to allocate */
89262  char *zAff;                   /* Affinity string to return */
89263
89264  /* This module is only called on query plans that use an index. */
89265  assert( pLevel->plan.wsFlags & WHERE_INDEXED );
89266  pIdx = pLevel->plan.u.pIdx;
89267
89268  /* Figure out how many memory cells we will need then allocate them.
89269  */
89270  regBase = pParse->nMem + 1;
89271  nReg = pLevel->plan.nEq + nExtraReg;
89272  pParse->nMem += nReg;
89273
89274  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
89275  if( !zAff ){
89276    pParse->db->mallocFailed = 1;
89277  }
89278
89279  /* Evaluate the equality constraints
89280  */
89281  assert( pIdx->nColumn>=nEq );
89282  for(j=0; j<nEq; j++){
89283    int r1;
89284    int k = pIdx->aiColumn[j];
89285    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
89286    if( NEVER(pTerm==0) ) break;
89287    assert( (pTerm->wtFlags & TERM_CODED)==0 );
89288    r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
89289    if( r1!=regBase+j ){
89290      if( nReg==1 ){
89291        sqlite3ReleaseTempReg(pParse, regBase);
89292        regBase = r1;
89293      }else{
89294        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
89295      }
89296    }
89297    testcase( pTerm->eOperator & WO_ISNULL );
89298    testcase( pTerm->eOperator & WO_IN );
89299    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
89300      Expr *pRight = pTerm->pExpr->pRight;
89301      sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
89302      if( zAff ){
89303        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
89304          zAff[j] = SQLITE_AFF_NONE;
89305        }
89306        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
89307          zAff[j] = SQLITE_AFF_NONE;
89308        }
89309      }
89310    }
89311  }
89312  *pzAff = zAff;
89313  return regBase;
89314}
89315
89316/*
89317** Generate code for the start of the iLevel-th loop in the WHERE clause
89318** implementation described by pWInfo.
89319*/
89320static Bitmask codeOneLoopStart(
89321  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
89322  int iLevel,          /* Which level of pWInfo->a[] should be coded */
89323  u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
89324  Bitmask notReady     /* Which tables are currently available */
89325){
89326  int j, k;            /* Loop counters */
89327  int iCur;            /* The VDBE cursor for the table */
89328  int addrNxt;         /* Where to jump to continue with the next IN case */
89329  int omitTable;       /* True if we use the index only */
89330  int bRev;            /* True if we need to scan in reverse order */
89331  WhereLevel *pLevel;  /* The where level to be coded */
89332  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
89333  WhereTerm *pTerm;               /* A WHERE clause term */
89334  Parse *pParse;                  /* Parsing context */
89335  Vdbe *v;                        /* The prepared stmt under constructions */
89336  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
89337  int addrBrk;                    /* Jump here to break out of the loop */
89338  int addrCont;                   /* Jump here to continue with next cycle */
89339  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
89340  int iReleaseReg = 0;      /* Temp register to free before returning */
89341
89342  pParse = pWInfo->pParse;
89343  v = pParse->pVdbe;
89344  pWC = pWInfo->pWC;
89345  pLevel = &pWInfo->a[iLevel];
89346  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
89347  iCur = pTabItem->iCursor;
89348  bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
89349  omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
89350           && (wctrlFlags & WHERE_FORCE_TABLE)==0;
89351
89352  /* Create labels for the "break" and "continue" instructions
89353  ** for the current loop.  Jump to addrBrk to break out of a loop.
89354  ** Jump to cont to go immediately to the next iteration of the
89355  ** loop.
89356  **
89357  ** When there is an IN operator, we also have a "addrNxt" label that
89358  ** means to continue with the next IN value combination.  When
89359  ** there are no IN operators in the constraints, the "addrNxt" label
89360  ** is the same as "addrBrk".
89361  */
89362  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
89363  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
89364
89365  /* If this is the right table of a LEFT OUTER JOIN, allocate and
89366  ** initialize a memory cell that records if this table matches any
89367  ** row of the left table of the join.
89368  */
89369  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
89370    pLevel->iLeftJoin = ++pParse->nMem;
89371    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
89372    VdbeComment((v, "init LEFT JOIN no-match flag"));
89373  }
89374
89375#ifndef SQLITE_OMIT_VIRTUALTABLE
89376  if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
89377    /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
89378    **          to access the data.
89379    */
89380    int iReg;   /* P3 Value for OP_VFilter */
89381    sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
89382    int nConstraint = pVtabIdx->nConstraint;
89383    struct sqlite3_index_constraint_usage *aUsage =
89384                                                pVtabIdx->aConstraintUsage;
89385    const struct sqlite3_index_constraint *aConstraint =
89386                                                pVtabIdx->aConstraint;
89387
89388    sqlite3ExprCachePush(pParse);
89389    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
89390    for(j=1; j<=nConstraint; j++){
89391      for(k=0; k<nConstraint; k++){
89392        if( aUsage[k].argvIndex==j ){
89393          int iTerm = aConstraint[k].iTermOffset;
89394          sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
89395          break;
89396        }
89397      }
89398      if( k==nConstraint ) break;
89399    }
89400    sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
89401    sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
89402    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
89403                      pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
89404    pVtabIdx->needToFreeIdxStr = 0;
89405    for(j=0; j<nConstraint; j++){
89406      if( aUsage[j].omit ){
89407        int iTerm = aConstraint[j].iTermOffset;
89408        disableTerm(pLevel, &pWC->a[iTerm]);
89409      }
89410    }
89411    pLevel->op = OP_VNext;
89412    pLevel->p1 = iCur;
89413    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
89414    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
89415    sqlite3ExprCachePop(pParse, 1);
89416  }else
89417#endif /* SQLITE_OMIT_VIRTUALTABLE */
89418
89419  if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
89420    /* Case 1:  We can directly reference a single row using an
89421    **          equality comparison against the ROWID field.  Or
89422    **          we reference multiple rows using a "rowid IN (...)"
89423    **          construct.
89424    */
89425    iReleaseReg = sqlite3GetTempReg(pParse);
89426    pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
89427    assert( pTerm!=0 );
89428    assert( pTerm->pExpr!=0 );
89429    assert( pTerm->leftCursor==iCur );
89430    assert( omitTable==0 );
89431    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
89432    addrNxt = pLevel->addrNxt;
89433    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
89434    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
89435    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89436    VdbeComment((v, "pk"));
89437    pLevel->op = OP_Noop;
89438  }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
89439    /* Case 2:  We have an inequality comparison against the ROWID field.
89440    */
89441    int testOp = OP_Noop;
89442    int start;
89443    int memEndValue = 0;
89444    WhereTerm *pStart, *pEnd;
89445
89446    assert( omitTable==0 );
89447    pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
89448    pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
89449    if( bRev ){
89450      pTerm = pStart;
89451      pStart = pEnd;
89452      pEnd = pTerm;
89453    }
89454    if( pStart ){
89455      Expr *pX;             /* The expression that defines the start bound */
89456      int r1, rTemp;        /* Registers for holding the start boundary */
89457
89458      /* The following constant maps TK_xx codes into corresponding
89459      ** seek opcodes.  It depends on a particular ordering of TK_xx
89460      */
89461      const u8 aMoveOp[] = {
89462           /* TK_GT */  OP_SeekGt,
89463           /* TK_LE */  OP_SeekLe,
89464           /* TK_LT */  OP_SeekLt,
89465           /* TK_GE */  OP_SeekGe
89466      };
89467      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
89468      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
89469      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
89470
89471      pX = pStart->pExpr;
89472      assert( pX!=0 );
89473      assert( pStart->leftCursor==iCur );
89474      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
89475      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
89476      VdbeComment((v, "pk"));
89477      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
89478      sqlite3ReleaseTempReg(pParse, rTemp);
89479      disableTerm(pLevel, pStart);
89480    }else{
89481      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
89482    }
89483    if( pEnd ){
89484      Expr *pX;
89485      pX = pEnd->pExpr;
89486      assert( pX!=0 );
89487      assert( pEnd->leftCursor==iCur );
89488      memEndValue = ++pParse->nMem;
89489      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
89490      if( pX->op==TK_LT || pX->op==TK_GT ){
89491        testOp = bRev ? OP_Le : OP_Ge;
89492      }else{
89493        testOp = bRev ? OP_Lt : OP_Gt;
89494      }
89495      disableTerm(pLevel, pEnd);
89496    }
89497    start = sqlite3VdbeCurrentAddr(v);
89498    pLevel->op = bRev ? OP_Prev : OP_Next;
89499    pLevel->p1 = iCur;
89500    pLevel->p2 = start;
89501    pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
89502    if( testOp!=OP_Noop ){
89503      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
89504      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
89505      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89506      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
89507      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
89508    }
89509  }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
89510    /* Case 3: A scan using an index.
89511    **
89512    **         The WHERE clause may contain zero or more equality
89513    **         terms ("==" or "IN" operators) that refer to the N
89514    **         left-most columns of the index. It may also contain
89515    **         inequality constraints (>, <, >= or <=) on the indexed
89516    **         column that immediately follows the N equalities. Only
89517    **         the right-most column can be an inequality - the rest must
89518    **         use the "==" and "IN" operators. For example, if the
89519    **         index is on (x,y,z), then the following clauses are all
89520    **         optimized:
89521    **
89522    **            x=5
89523    **            x=5 AND y=10
89524    **            x=5 AND y<10
89525    **            x=5 AND y>5 AND y<10
89526    **            x=5 AND y=5 AND z<=10
89527    **
89528    **         The z<10 term of the following cannot be used, only
89529    **         the x=5 term:
89530    **
89531    **            x=5 AND z<10
89532    **
89533    **         N may be zero if there are inequality constraints.
89534    **         If there are no inequality constraints, then N is at
89535    **         least one.
89536    **
89537    **         This case is also used when there are no WHERE clause
89538    **         constraints but an index is selected anyway, in order
89539    **         to force the output order to conform to an ORDER BY.
89540    */
89541    int aStartOp[] = {
89542      0,
89543      0,
89544      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
89545      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
89546      OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
89547      OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
89548      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
89549      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
89550    };
89551    int aEndOp[] = {
89552      OP_Noop,             /* 0: (!end_constraints) */
89553      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
89554      OP_IdxLT             /* 2: (end_constraints && bRev) */
89555    };
89556    int nEq = pLevel->plan.nEq;
89557    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
89558    int regBase;                 /* Base register holding constraint values */
89559    int r1;                      /* Temp register */
89560    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
89561    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
89562    int startEq;                 /* True if range start uses ==, >= or <= */
89563    int endEq;                   /* True if range end uses ==, >= or <= */
89564    int start_constraints;       /* Start of range is constrained */
89565    int nConstraint;             /* Number of constraint terms */
89566    Index *pIdx;         /* The index we will be using */
89567    int iIdxCur;         /* The VDBE cursor for the index */
89568    int nExtraReg = 0;   /* Number of extra registers needed */
89569    int op;              /* Instruction opcode */
89570    char *zAff;
89571
89572    pIdx = pLevel->plan.u.pIdx;
89573    iIdxCur = pLevel->iIdxCur;
89574    k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
89575
89576    /* If this loop satisfies a sort order (pOrderBy) request that
89577    ** was passed to this function to implement a "SELECT min(x) ..."
89578    ** query, then the caller will only allow the loop to run for
89579    ** a single iteration. This means that the first row returned
89580    ** should not have a NULL value stored in 'x'. If column 'x' is
89581    ** the first one after the nEq equality constraints in the index,
89582    ** this requires some special handling.
89583    */
89584    if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
89585     && (pLevel->plan.wsFlags&WHERE_ORDERBY)
89586     && (pIdx->nColumn>nEq)
89587    ){
89588      /* assert( pOrderBy->nExpr==1 ); */
89589      /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
89590      isMinQuery = 1;
89591      nExtraReg = 1;
89592    }
89593
89594    /* Find any inequality constraint terms for the start and end
89595    ** of the range.
89596    */
89597    if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
89598      pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
89599      nExtraReg = 1;
89600    }
89601    if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
89602      pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
89603      nExtraReg = 1;
89604    }
89605
89606    /* Generate code to evaluate all constraint terms using == or IN
89607    ** and store the values of those terms in an array of registers
89608    ** starting at regBase.
89609    */
89610    regBase = codeAllEqualityTerms(
89611        pParse, pLevel, pWC, notReady, nExtraReg, &zAff
89612    );
89613    addrNxt = pLevel->addrNxt;
89614
89615    /* If we are doing a reverse order scan on an ascending index, or
89616    ** a forward order scan on a descending index, interchange the
89617    ** start and end terms (pRangeStart and pRangeEnd).
89618    */
89619    if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
89620      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
89621    }
89622
89623    testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
89624    testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
89625    testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
89626    testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
89627    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
89628    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
89629    start_constraints = pRangeStart || nEq>0;
89630
89631    /* Seek the index cursor to the start of the range. */
89632    nConstraint = nEq;
89633    if( pRangeStart ){
89634      Expr *pRight = pRangeStart->pExpr->pRight;
89635      sqlite3ExprCode(pParse, pRight, regBase+nEq);
89636      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
89637      if( zAff ){
89638        if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
89639          /* Since the comparison is to be performed with no conversions
89640          ** applied to the operands, set the affinity to apply to pRight to
89641          ** SQLITE_AFF_NONE.  */
89642          zAff[nConstraint] = SQLITE_AFF_NONE;
89643        }
89644        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
89645          zAff[nConstraint] = SQLITE_AFF_NONE;
89646        }
89647      }
89648      nConstraint++;
89649    }else if( isMinQuery ){
89650      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
89651      nConstraint++;
89652      startEq = 0;
89653      start_constraints = 1;
89654    }
89655    codeApplyAffinity(pParse, regBase, nConstraint, zAff);
89656    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
89657    assert( op!=0 );
89658    testcase( op==OP_Rewind );
89659    testcase( op==OP_Last );
89660    testcase( op==OP_SeekGt );
89661    testcase( op==OP_SeekGe );
89662    testcase( op==OP_SeekLe );
89663    testcase( op==OP_SeekLt );
89664    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
89665
89666    /* Load the value for the inequality constraint at the end of the
89667    ** range (if any).
89668    */
89669    nConstraint = nEq;
89670    if( pRangeEnd ){
89671      Expr *pRight = pRangeEnd->pExpr->pRight;
89672      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
89673      sqlite3ExprCode(pParse, pRight, regBase+nEq);
89674      sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
89675      if( zAff ){
89676        if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
89677          /* Since the comparison is to be performed with no conversions
89678          ** applied to the operands, set the affinity to apply to pRight to
89679          ** SQLITE_AFF_NONE.  */
89680          zAff[nConstraint] = SQLITE_AFF_NONE;
89681        }
89682        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
89683          zAff[nConstraint] = SQLITE_AFF_NONE;
89684        }
89685      }
89686      codeApplyAffinity(pParse, regBase, nEq+1, zAff);
89687      nConstraint++;
89688    }
89689    sqlite3DbFree(pParse->db, zAff);
89690
89691    /* Top of the loop body */
89692    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
89693
89694    /* Check if the index cursor is past the end of the range. */
89695    op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
89696    testcase( op==OP_Noop );
89697    testcase( op==OP_IdxGE );
89698    testcase( op==OP_IdxLT );
89699    if( op!=OP_Noop ){
89700      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
89701      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
89702    }
89703
89704    /* If there are inequality constraints, check that the value
89705    ** of the table column that the inequality contrains is not NULL.
89706    ** If it is, jump to the next iteration of the loop.
89707    */
89708    r1 = sqlite3GetTempReg(pParse);
89709    testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
89710    testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
89711    if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
89712      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
89713      sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
89714    }
89715    sqlite3ReleaseTempReg(pParse, r1);
89716
89717    /* Seek the table cursor, if required */
89718    disableTerm(pLevel, pRangeStart);
89719    disableTerm(pLevel, pRangeEnd);
89720    if( !omitTable ){
89721      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
89722      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
89723      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
89724      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
89725    }
89726
89727    /* Record the instruction used to terminate the loop. Disable
89728    ** WHERE clause terms made redundant by the index range scan.
89729    */
89730    pLevel->op = bRev ? OP_Prev : OP_Next;
89731    pLevel->p1 = iIdxCur;
89732  }else
89733
89734#ifndef SQLITE_OMIT_OR_OPTIMIZATION
89735  if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
89736    /* Case 4:  Two or more separately indexed terms connected by OR
89737    **
89738    ** Example:
89739    **
89740    **   CREATE TABLE t1(a,b,c,d);
89741    **   CREATE INDEX i1 ON t1(a);
89742    **   CREATE INDEX i2 ON t1(b);
89743    **   CREATE INDEX i3 ON t1(c);
89744    **
89745    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
89746    **
89747    ** In the example, there are three indexed terms connected by OR.
89748    ** The top of the loop looks like this:
89749    **
89750    **          Null       1                # Zero the rowset in reg 1
89751    **
89752    ** Then, for each indexed term, the following. The arguments to
89753    ** RowSetTest are such that the rowid of the current row is inserted
89754    ** into the RowSet. If it is already present, control skips the
89755    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
89756    **
89757    **        sqlite3WhereBegin(<term>)
89758    **          RowSetTest                  # Insert rowid into rowset
89759    **          Gosub      2 A
89760    **        sqlite3WhereEnd()
89761    **
89762    ** Following the above, code to terminate the loop. Label A, the target
89763    ** of the Gosub above, jumps to the instruction right after the Goto.
89764    **
89765    **          Null       1                # Zero the rowset in reg 1
89766    **          Goto       B                # The loop is finished.
89767    **
89768    **       A: <loop body>                 # Return data, whatever.
89769    **
89770    **          Return     2                # Jump back to the Gosub
89771    **
89772    **       B: <after the loop>
89773    **
89774    */
89775    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
89776    WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
89777    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
89778
89779    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
89780    int regRowset = 0;                        /* Register for RowSet object */
89781    int regRowid = 0;                         /* Register holding rowid */
89782    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
89783    int iRetInit;                             /* Address of regReturn init */
89784    int untestedTerms = 0;             /* Some terms not completely tested */
89785    int ii;
89786
89787    pTerm = pLevel->plan.u.pTerm;
89788    assert( pTerm!=0 );
89789    assert( pTerm->eOperator==WO_OR );
89790    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
89791    pOrWc = &pTerm->u.pOrInfo->wc;
89792    pFinal = &pOrWc->a[pOrWc->nTerm-1];
89793    pLevel->op = OP_Return;
89794    pLevel->p1 = regReturn;
89795
89796    /* Set up a new SrcList ni pOrTab containing the table being scanned
89797    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
89798    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
89799    */
89800    if( pWInfo->nLevel>1 ){
89801      int nNotReady;                 /* The number of notReady tables */
89802      struct SrcList_item *origSrc;     /* Original list of tables */
89803      nNotReady = pWInfo->nLevel - iLevel - 1;
89804      pOrTab = sqlite3StackAllocRaw(pParse->db,
89805                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
89806      if( pOrTab==0 ) return notReady;
89807      pOrTab->nAlloc = (i16)(nNotReady + 1);
89808      pOrTab->nSrc = pOrTab->nAlloc;
89809      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
89810      origSrc = pWInfo->pTabList->a;
89811      for(k=1; k<=nNotReady; k++){
89812        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
89813      }
89814    }else{
89815      pOrTab = pWInfo->pTabList;
89816    }
89817
89818    /* Initialize the rowset register to contain NULL. An SQL NULL is
89819    ** equivalent to an empty rowset.
89820    **
89821    ** Also initialize regReturn to contain the address of the instruction
89822    ** immediately following the OP_Return at the bottom of the loop. This
89823    ** is required in a few obscure LEFT JOIN cases where control jumps
89824    ** over the top of the loop into the body of it. In this case the
89825    ** correct response for the end-of-loop code (the OP_Return) is to
89826    ** fall through to the next instruction, just as an OP_Next does if
89827    ** called on an uninitialized cursor.
89828    */
89829    if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
89830      regRowset = ++pParse->nMem;
89831      regRowid = ++pParse->nMem;
89832      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
89833    }
89834    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
89835
89836    for(ii=0; ii<pOrWc->nTerm; ii++){
89837      WhereTerm *pOrTerm = &pOrWc->a[ii];
89838      if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
89839        WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
89840        /* Loop through table entries that match term pOrTerm. */
89841        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
89842                        WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
89843                        WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
89844        if( pSubWInfo ){
89845          if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
89846            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
89847            int r;
89848            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
89849                                         regRowid);
89850            sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
89851                                 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
89852          }
89853          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
89854
89855          /* The pSubWInfo->untestedTerms flag means that this OR term
89856          ** contained one or more AND term from a notReady table.  The
89857          ** terms from the notReady table could not be tested and will
89858          ** need to be tested later.
89859          */
89860          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
89861
89862          /* Finish the loop through table entries that match term pOrTerm. */
89863          sqlite3WhereEnd(pSubWInfo);
89864        }
89865      }
89866    }
89867    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
89868    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
89869    sqlite3VdbeResolveLabel(v, iLoopBody);
89870
89871    if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
89872    if( !untestedTerms ) disableTerm(pLevel, pTerm);
89873  }else
89874#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
89875
89876  {
89877    /* Case 5:  There is no usable index.  We must do a complete
89878    **          scan of the entire table.
89879    */
89880    static const u8 aStep[] = { OP_Next, OP_Prev };
89881    static const u8 aStart[] = { OP_Rewind, OP_Last };
89882    assert( bRev==0 || bRev==1 );
89883    assert( omitTable==0 );
89884    pLevel->op = aStep[bRev];
89885    pLevel->p1 = iCur;
89886    pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
89887    pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
89888  }
89889  notReady &= ~getMask(pWC->pMaskSet, iCur);
89890
89891  /* Insert code to test every subexpression that can be completely
89892  ** computed using the current set of tables.
89893  */
89894  k = 0;
89895  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
89896    Expr *pE;
89897    testcase( pTerm->wtFlags & TERM_VIRTUAL );
89898    testcase( pTerm->wtFlags & TERM_CODED );
89899    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
89900    if( (pTerm->prereqAll & notReady)!=0 ){
89901      testcase( pWInfo->untestedTerms==0
89902               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
89903      pWInfo->untestedTerms = 1;
89904      continue;
89905    }
89906    pE = pTerm->pExpr;
89907    assert( pE!=0 );
89908    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
89909      continue;
89910    }
89911    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
89912    k = 1;
89913    pTerm->wtFlags |= TERM_CODED;
89914  }
89915
89916  /* For a LEFT OUTER JOIN, generate code that will record the fact that
89917  ** at least one row of the right table has matched the left table.
89918  */
89919  if( pLevel->iLeftJoin ){
89920    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
89921    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
89922    VdbeComment((v, "record LEFT JOIN hit"));
89923    sqlite3ExprCacheClear(pParse);
89924    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
89925      testcase( pTerm->wtFlags & TERM_VIRTUAL );
89926      testcase( pTerm->wtFlags & TERM_CODED );
89927      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
89928      if( (pTerm->prereqAll & notReady)!=0 ){
89929        assert( pWInfo->untestedTerms );
89930        continue;
89931      }
89932      assert( pTerm->pExpr );
89933      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
89934      pTerm->wtFlags |= TERM_CODED;
89935    }
89936  }
89937  sqlite3ReleaseTempReg(pParse, iReleaseReg);
89938
89939  return notReady;
89940}
89941
89942#if defined(SQLITE_TEST)
89943/*
89944** The following variable holds a text description of query plan generated
89945** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
89946** overwrites the previous.  This information is used for testing and
89947** analysis only.
89948*/
89949SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
89950static int nQPlan = 0;              /* Next free slow in _query_plan[] */
89951
89952#endif /* SQLITE_TEST */
89953
89954
89955/*
89956** Free a WhereInfo structure
89957*/
89958static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
89959  if( pWInfo ){
89960    int i;
89961    for(i=0; i<pWInfo->nLevel; i++){
89962      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
89963      if( pInfo ){
89964        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
89965        if( pInfo->needToFreeIdxStr ){
89966          sqlite3_free(pInfo->idxStr);
89967        }
89968        sqlite3DbFree(db, pInfo);
89969      }
89970    }
89971    whereClauseClear(pWInfo->pWC);
89972    sqlite3DbFree(db, pWInfo);
89973  }
89974}
89975
89976
89977/*
89978** Generate the beginning of the loop used for WHERE clause processing.
89979** The return value is a pointer to an opaque structure that contains
89980** information needed to terminate the loop.  Later, the calling routine
89981** should invoke sqlite3WhereEnd() with the return value of this function
89982** in order to complete the WHERE clause processing.
89983**
89984** If an error occurs, this routine returns NULL.
89985**
89986** The basic idea is to do a nested loop, one loop for each table in
89987** the FROM clause of a select.  (INSERT and UPDATE statements are the
89988** same as a SELECT with only a single table in the FROM clause.)  For
89989** example, if the SQL is this:
89990**
89991**       SELECT * FROM t1, t2, t3 WHERE ...;
89992**
89993** Then the code generated is conceptually like the following:
89994**
89995**      foreach row1 in t1 do       \    Code generated
89996**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
89997**          foreach row3 in t3 do   /
89998**            ...
89999**          end                     \    Code generated
90000**        end                        |-- by sqlite3WhereEnd()
90001**      end                         /
90002**
90003** Note that the loops might not be nested in the order in which they
90004** appear in the FROM clause if a different order is better able to make
90005** use of indices.  Note also that when the IN operator appears in
90006** the WHERE clause, it might result in additional nested loops for
90007** scanning through all values on the right-hand side of the IN.
90008**
90009** There are Btree cursors associated with each table.  t1 uses cursor
90010** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
90011** And so forth.  This routine generates code to open those VDBE cursors
90012** and sqlite3WhereEnd() generates the code to close them.
90013**
90014** The code that sqlite3WhereBegin() generates leaves the cursors named
90015** in pTabList pointing at their appropriate entries.  The [...] code
90016** can use OP_Column and OP_Rowid opcodes on these cursors to extract
90017** data from the various tables of the loop.
90018**
90019** If the WHERE clause is empty, the foreach loops must each scan their
90020** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
90021** the tables have indices and there are terms in the WHERE clause that
90022** refer to those indices, a complete table scan can be avoided and the
90023** code will run much faster.  Most of the work of this routine is checking
90024** to see if there are indices that can be used to speed up the loop.
90025**
90026** Terms of the WHERE clause are also used to limit which rows actually
90027** make it to the "..." in the middle of the loop.  After each "foreach",
90028** terms of the WHERE clause that use only terms in that loop and outer
90029** loops are evaluated and if false a jump is made around all subsequent
90030** inner loops (or around the "..." if the test occurs within the inner-
90031** most loop)
90032**
90033** OUTER JOINS
90034**
90035** An outer join of tables t1 and t2 is conceptally coded as follows:
90036**
90037**    foreach row1 in t1 do
90038**      flag = 0
90039**      foreach row2 in t2 do
90040**        start:
90041**          ...
90042**          flag = 1
90043**      end
90044**      if flag==0 then
90045**        move the row2 cursor to a null row
90046**        goto start
90047**      fi
90048**    end
90049**
90050** ORDER BY CLAUSE PROCESSING
90051**
90052** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
90053** if there is one.  If there is no ORDER BY clause or if this routine
90054** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
90055**
90056** If an index can be used so that the natural output order of the table
90057** scan is correct for the ORDER BY clause, then that index is used and
90058** *ppOrderBy is set to NULL.  This is an optimization that prevents an
90059** unnecessary sort of the result set if an index appropriate for the
90060** ORDER BY clause already exists.
90061**
90062** If the where clause loops cannot be arranged to provide the correct
90063** output order, then the *ppOrderBy is unchanged.
90064*/
90065SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
90066  Parse *pParse,        /* The parser context */
90067  SrcList *pTabList,    /* A list of all tables to be scanned */
90068  Expr *pWhere,         /* The WHERE clause */
90069  ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
90070  u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
90071){
90072  int i;                     /* Loop counter */
90073  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
90074  int nTabList;              /* Number of elements in pTabList */
90075  WhereInfo *pWInfo;         /* Will become the return value of this function */
90076  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
90077  Bitmask notReady;          /* Cursors that are not yet positioned */
90078  WhereMaskSet *pMaskSet;    /* The expression mask set */
90079  WhereClause *pWC;               /* Decomposition of the WHERE clause */
90080  struct SrcList_item *pTabItem;  /* A single entry from pTabList */
90081  WhereLevel *pLevel;             /* A single level in the pWInfo list */
90082  int iFrom;                      /* First unused FROM clause element */
90083  int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
90084  sqlite3 *db;               /* Database connection */
90085
90086  /* The number of tables in the FROM clause is limited by the number of
90087  ** bits in a Bitmask
90088  */
90089  if( pTabList->nSrc>BMS ){
90090    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
90091    return 0;
90092  }
90093
90094  /* This function normally generates a nested loop for all tables in
90095  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
90096  ** only generate code for the first table in pTabList and assume that
90097  ** any cursors associated with subsequent tables are uninitialized.
90098  */
90099  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
90100
90101  /* Allocate and initialize the WhereInfo structure that will become the
90102  ** return value. A single allocation is used to store the WhereInfo
90103  ** struct, the contents of WhereInfo.a[], the WhereClause structure
90104  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
90105  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
90106  ** some architectures. Hence the ROUND8() below.
90107  */
90108  db = pParse->db;
90109  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
90110  pWInfo = sqlite3DbMallocZero(db,
90111      nByteWInfo +
90112      sizeof(WhereClause) +
90113      sizeof(WhereMaskSet)
90114  );
90115  if( db->mallocFailed ){
90116    goto whereBeginError;
90117  }
90118  pWInfo->nLevel = nTabList;
90119  pWInfo->pParse = pParse;
90120  pWInfo->pTabList = pTabList;
90121  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
90122  pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
90123  pWInfo->wctrlFlags = wctrlFlags;
90124  pMaskSet = (WhereMaskSet*)&pWC[1];
90125
90126  /* Split the WHERE clause into separate subexpressions where each
90127  ** subexpression is separated by an AND operator.
90128  */
90129  initMaskSet(pMaskSet);
90130  whereClauseInit(pWC, pParse, pMaskSet);
90131  sqlite3ExprCodeConstants(pParse, pWhere);
90132  whereSplit(pWC, pWhere, TK_AND);
90133
90134  /* Special case: a WHERE clause that is constant.  Evaluate the
90135  ** expression and either jump over all of the code or fall thru.
90136  */
90137  if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
90138    sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
90139    pWhere = 0;
90140  }
90141
90142  /* Assign a bit from the bitmask to every term in the FROM clause.
90143  **
90144  ** When assigning bitmask values to FROM clause cursors, it must be
90145  ** the case that if X is the bitmask for the N-th FROM clause term then
90146  ** the bitmask for all FROM clause terms to the left of the N-th term
90147  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
90148  ** its Expr.iRightJoinTable value to find the bitmask of the right table
90149  ** of the join.  Subtracting one from the right table bitmask gives a
90150  ** bitmask for all tables to the left of the join.  Knowing the bitmask
90151  ** for all tables to the left of a left join is important.  Ticket #3015.
90152  **
90153  ** Configure the WhereClause.vmask variable so that bits that correspond
90154  ** to virtual table cursors are set. This is used to selectively disable
90155  ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
90156  ** with virtual tables.
90157  **
90158  ** Note that bitmasks are created for all pTabList->nSrc tables in
90159  ** pTabList, not just the first nTabList tables.  nTabList is normally
90160  ** equal to pTabList->nSrc but might be shortened to 1 if the
90161  ** WHERE_ONETABLE_ONLY flag is set.
90162  */
90163  assert( pWC->vmask==0 && pMaskSet->n==0 );
90164  for(i=0; i<pTabList->nSrc; i++){
90165    createMask(pMaskSet, pTabList->a[i].iCursor);
90166#ifndef SQLITE_OMIT_VIRTUALTABLE
90167    if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
90168      pWC->vmask |= ((Bitmask)1 << i);
90169    }
90170#endif
90171  }
90172#ifndef NDEBUG
90173  {
90174    Bitmask toTheLeft = 0;
90175    for(i=0; i<pTabList->nSrc; i++){
90176      Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
90177      assert( (m-1)==toTheLeft );
90178      toTheLeft |= m;
90179    }
90180  }
90181#endif
90182
90183  /* Analyze all of the subexpressions.  Note that exprAnalyze() might
90184  ** add new virtual terms onto the end of the WHERE clause.  We do not
90185  ** want to analyze these virtual terms, so start analyzing at the end
90186  ** and work forward so that the added virtual terms are never processed.
90187  */
90188  exprAnalyzeAll(pTabList, pWC);
90189  if( db->mallocFailed ){
90190    goto whereBeginError;
90191  }
90192
90193  /* Chose the best index to use for each table in the FROM clause.
90194  **
90195  ** This loop fills in the following fields:
90196  **
90197  **   pWInfo->a[].pIdx      The index to use for this level of the loop.
90198  **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
90199  **   pWInfo->a[].nEq       The number of == and IN constraints
90200  **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
90201  **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
90202  **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
90203  **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
90204  **
90205  ** This loop also figures out the nesting order of tables in the FROM
90206  ** clause.
90207  */
90208  notReady = ~(Bitmask)0;
90209  pTabItem = pTabList->a;
90210  pLevel = pWInfo->a;
90211  andFlags = ~0;
90212  WHERETRACE(("*** Optimizer Start ***\n"));
90213  for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
90214    WhereCost bestPlan;         /* Most efficient plan seen so far */
90215    Index *pIdx;                /* Index for FROM table at pTabItem */
90216    int j;                      /* For looping over FROM tables */
90217    int bestJ = -1;             /* The value of j */
90218    Bitmask m;                  /* Bitmask value for j or bestJ */
90219    int isOptimal;              /* Iterator for optimal/non-optimal search */
90220
90221    memset(&bestPlan, 0, sizeof(bestPlan));
90222    bestPlan.rCost = SQLITE_BIG_DBL;
90223
90224    /* Loop through the remaining entries in the FROM clause to find the
90225    ** next nested loop. The FROM clause entries may be iterated through
90226    ** either once or twice.
90227    **
90228    ** The first iteration, which is always performed, searches for the
90229    ** FROM clause entry that permits the lowest-cost, "optimal" scan. In
90230    ** this context an optimal scan is one that uses the same strategy
90231    ** for the given FROM clause entry as would be selected if the entry
90232    ** were used as the innermost nested loop.  In other words, a table
90233    ** is chosen such that the cost of running that table cannot be reduced
90234    ** by waiting for other tables to run first.
90235    **
90236    ** The second iteration is only performed if no optimal scan strategies
90237    ** were found by the first. This iteration is used to search for the
90238    ** lowest cost scan overall.
90239    **
90240    ** Previous versions of SQLite performed only the second iteration -
90241    ** the next outermost loop was always that with the lowest overall
90242    ** cost. However, this meant that SQLite could select the wrong plan
90243    ** for scripts such as the following:
90244    **
90245    **   CREATE TABLE t1(a, b);
90246    **   CREATE TABLE t2(c, d);
90247    **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
90248    **
90249    ** The best strategy is to iterate through table t1 first. However it
90250    ** is not possible to determine this with a simple greedy algorithm.
90251    ** However, since the cost of a linear scan through table t2 is the same
90252    ** as the cost of a linear scan through table t1, a simple greedy
90253    ** algorithm may choose to use t2 for the outer loop, which is a much
90254    ** costlier approach.
90255    */
90256    for(isOptimal=1; isOptimal>=0 && bestJ<0; isOptimal--){
90257      Bitmask mask = (isOptimal ? 0 : notReady);
90258      assert( (nTabList-iFrom)>1 || isOptimal );
90259      for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
90260        int doNotReorder;    /* True if this table should not be reordered */
90261        WhereCost sCost;     /* Cost information from best[Virtual]Index() */
90262        ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
90263
90264        doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
90265        if( j!=iFrom && doNotReorder ) break;
90266        m = getMask(pMaskSet, pTabItem->iCursor);
90267        if( (m & notReady)==0 ){
90268          if( j==iFrom ) iFrom++;
90269          continue;
90270        }
90271        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
90272
90273        assert( pTabItem->pTab );
90274#ifndef SQLITE_OMIT_VIRTUALTABLE
90275        if( IsVirtual(pTabItem->pTab) ){
90276          sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
90277          bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
90278        }else
90279#endif
90280        {
90281          bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
90282        }
90283        assert( isOptimal || (sCost.used&notReady)==0 );
90284
90285        if( (sCost.used&notReady)==0
90286         && (j==iFrom || sCost.rCost<bestPlan.rCost)
90287        ){
90288          bestPlan = sCost;
90289          bestJ = j;
90290        }
90291        if( doNotReorder ) break;
90292      }
90293    }
90294    assert( bestJ>=0 );
90295    assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
90296    WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
90297           pLevel-pWInfo->a));
90298    if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
90299      *ppOrderBy = 0;
90300    }
90301    andFlags &= bestPlan.plan.wsFlags;
90302    pLevel->plan = bestPlan.plan;
90303    if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
90304      pLevel->iIdxCur = pParse->nTab++;
90305    }else{
90306      pLevel->iIdxCur = -1;
90307    }
90308    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
90309    pLevel->iFrom = (u8)bestJ;
90310
90311    /* Check that if the table scanned by this loop iteration had an
90312    ** INDEXED BY clause attached to it, that the named index is being
90313    ** used for the scan. If not, then query compilation has failed.
90314    ** Return an error.
90315    */
90316    pIdx = pTabList->a[bestJ].pIndex;
90317    if( pIdx ){
90318      if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
90319        sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
90320        goto whereBeginError;
90321      }else{
90322        /* If an INDEXED BY clause is used, the bestIndex() function is
90323        ** guaranteed to find the index specified in the INDEXED BY clause
90324        ** if it find an index at all. */
90325        assert( bestPlan.plan.u.pIdx==pIdx );
90326      }
90327    }
90328  }
90329  WHERETRACE(("*** Optimizer Finished ***\n"));
90330  if( pParse->nErr || db->mallocFailed ){
90331    goto whereBeginError;
90332  }
90333
90334  /* If the total query only selects a single row, then the ORDER BY
90335  ** clause is irrelevant.
90336  */
90337  if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
90338    *ppOrderBy = 0;
90339  }
90340
90341  /* If the caller is an UPDATE or DELETE statement that is requesting
90342  ** to use a one-pass algorithm, determine if this is appropriate.
90343  ** The one-pass algorithm only works if the WHERE clause constraints
90344  ** the statement to update a single row.
90345  */
90346  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
90347  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
90348    pWInfo->okOnePass = 1;
90349    pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
90350  }
90351
90352  /* Open all tables in the pTabList and any indices selected for
90353  ** searching those tables.
90354  */
90355  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
90356  for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
90357    Table *pTab;     /* Table to open */
90358    int iDb;         /* Index of database containing table/index */
90359
90360#ifndef SQLITE_OMIT_EXPLAIN
90361    if( pParse->explain==2 ){
90362      char *zMsg;
90363      struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
90364      zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
90365      if( pItem->zAlias ){
90366        zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
90367      }
90368      if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90369        zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
90370           zMsg, pLevel->plan.u.pIdx->zName);
90371      }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
90372        zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
90373      }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
90374        zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
90375      }
90376#ifndef SQLITE_OMIT_VIRTUALTABLE
90377      else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
90378        sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
90379        zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
90380                    pVtabIdx->idxNum, pVtabIdx->idxStr);
90381      }
90382#endif
90383      if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
90384        zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
90385      }
90386      sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
90387    }
90388#endif /* SQLITE_OMIT_EXPLAIN */
90389    pTabItem = &pTabList->a[pLevel->iFrom];
90390    pTab = pTabItem->pTab;
90391    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90392    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
90393#ifndef SQLITE_OMIT_VIRTUALTABLE
90394    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
90395      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
90396      int iCur = pTabItem->iCursor;
90397      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
90398    }else
90399#endif
90400    if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90401         && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
90402      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
90403      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
90404      if( !pWInfo->okOnePass && pTab->nCol<BMS ){
90405        Bitmask b = pTabItem->colUsed;
90406        int n = 0;
90407        for(; b; b=b>>1, n++){}
90408        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
90409                            SQLITE_INT_TO_PTR(n), P4_INT32);
90410        assert( n<=pTab->nCol );
90411      }
90412    }else{
90413      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
90414    }
90415    pLevel->iTabCur = pTabItem->iCursor;
90416    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90417      Index *pIx = pLevel->plan.u.pIdx;
90418      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
90419      int iIdxCur = pLevel->iIdxCur;
90420      assert( pIx->pSchema==pTab->pSchema );
90421      assert( iIdxCur>=0 );
90422      sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
90423                        (char*)pKey, P4_KEYINFO_HANDOFF);
90424      VdbeComment((v, "%s", pIx->zName));
90425    }
90426    sqlite3CodeVerifySchema(pParse, iDb);
90427  }
90428  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
90429
90430  /* Generate the code to do the search.  Each iteration of the for
90431  ** loop below generates code for a single nested loop of the VM
90432  ** program.
90433  */
90434  notReady = ~(Bitmask)0;
90435  for(i=0; i<nTabList; i++){
90436    notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
90437    pWInfo->iContinue = pWInfo->a[i].addrCont;
90438  }
90439
90440#ifdef SQLITE_TEST  /* For testing and debugging use only */
90441  /* Record in the query plan information about the current table
90442  ** and the index used to access it (if any).  If the table itself
90443  ** is not used, its name is just '{}'.  If no index is used
90444  ** the index is listed as "{}".  If the primary key is used the
90445  ** index name is '*'.
90446  */
90447  for(i=0; i<nTabList; i++){
90448    char *z;
90449    int n;
90450    pLevel = &pWInfo->a[i];
90451    pTabItem = &pTabList->a[pLevel->iFrom];
90452    z = pTabItem->zAlias;
90453    if( z==0 ) z = pTabItem->pTab->zName;
90454    n = sqlite3Strlen30(z);
90455    if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
90456      if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
90457        memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
90458        nQPlan += 2;
90459      }else{
90460        memcpy(&sqlite3_query_plan[nQPlan], z, n);
90461        nQPlan += n;
90462      }
90463      sqlite3_query_plan[nQPlan++] = ' ';
90464    }
90465    testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
90466    testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
90467    if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
90468      memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
90469      nQPlan += 2;
90470    }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90471      n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
90472      if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
90473        memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
90474        nQPlan += n;
90475        sqlite3_query_plan[nQPlan++] = ' ';
90476      }
90477    }else{
90478      memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
90479      nQPlan += 3;
90480    }
90481  }
90482  while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
90483    sqlite3_query_plan[--nQPlan] = 0;
90484  }
90485  sqlite3_query_plan[nQPlan] = 0;
90486  nQPlan = 0;
90487#endif /* SQLITE_TEST // Testing and debugging use only */
90488
90489  /* Record the continuation address in the WhereInfo structure.  Then
90490  ** clean up and return.
90491  */
90492  return pWInfo;
90493
90494  /* Jump here if malloc fails */
90495whereBeginError:
90496  whereInfoFree(db, pWInfo);
90497  return 0;
90498}
90499
90500/*
90501** Generate the end of the WHERE loop.  See comments on
90502** sqlite3WhereBegin() for additional information.
90503*/
90504SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
90505  Parse *pParse = pWInfo->pParse;
90506  Vdbe *v = pParse->pVdbe;
90507  int i;
90508  WhereLevel *pLevel;
90509  SrcList *pTabList = pWInfo->pTabList;
90510  sqlite3 *db = pParse->db;
90511
90512  /* Generate loop termination code.
90513  */
90514  sqlite3ExprCacheClear(pParse);
90515  for(i=pWInfo->nLevel-1; i>=0; i--){
90516    pLevel = &pWInfo->a[i];
90517    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
90518    if( pLevel->op!=OP_Noop ){
90519      sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
90520      sqlite3VdbeChangeP5(v, pLevel->p5);
90521    }
90522    if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
90523      struct InLoop *pIn;
90524      int j;
90525      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
90526      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
90527        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
90528        sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
90529        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
90530      }
90531      sqlite3DbFree(db, pLevel->u.in.aInLoop);
90532    }
90533    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
90534    if( pLevel->iLeftJoin ){
90535      int addr;
90536      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
90537      assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90538           || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
90539      if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
90540        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
90541      }
90542      if( pLevel->iIdxCur>=0 ){
90543        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
90544      }
90545      if( pLevel->op==OP_Return ){
90546        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
90547      }else{
90548        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
90549      }
90550      sqlite3VdbeJumpHere(v, addr);
90551    }
90552  }
90553
90554  /* The "break" point is here, just past the end of the outer loop.
90555  ** Set it.
90556  */
90557  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
90558
90559  /* Close all of the cursors that were opened by sqlite3WhereBegin.
90560  */
90561  assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
90562  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
90563    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
90564    Table *pTab = pTabItem->pTab;
90565    assert( pTab!=0 );
90566    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
90567    if( (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 ){
90568      if( !pWInfo->okOnePass && (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
90569        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
90570      }
90571      if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
90572        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
90573      }
90574    }
90575
90576    /* If this scan uses an index, make code substitutions to read data
90577    ** from the index in preference to the table. Sometimes, this means
90578    ** the table need never be read from. This is a performance boost,
90579    ** as the vdbe level waits until the table is read before actually
90580    ** seeking the table cursor to the record corresponding to the current
90581    ** position in the index.
90582    **
90583    ** Calls to the code generator in between sqlite3WhereBegin and
90584    ** sqlite3WhereEnd will have created code that references the table
90585    ** directly.  This loop scans all that code looking for opcodes
90586    ** that reference the table and converts them into opcodes that
90587    ** reference the index.
90588    */
90589    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
90590      int k, j, last;
90591      VdbeOp *pOp;
90592      Index *pIdx = pLevel->plan.u.pIdx;
90593
90594      assert( pIdx!=0 );
90595      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
90596      last = sqlite3VdbeCurrentAddr(v);
90597      for(k=pWInfo->iTop; k<last; k++, pOp++){
90598        if( pOp->p1!=pLevel->iTabCur ) continue;
90599        if( pOp->opcode==OP_Column ){
90600          for(j=0; j<pIdx->nColumn; j++){
90601            if( pOp->p2==pIdx->aiColumn[j] ){
90602              pOp->p2 = j;
90603              pOp->p1 = pLevel->iIdxCur;
90604              break;
90605            }
90606          }
90607          assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
90608               || j<pIdx->nColumn );
90609        }else if( pOp->opcode==OP_Rowid ){
90610          pOp->p1 = pLevel->iIdxCur;
90611          pOp->opcode = OP_IdxRowid;
90612        }
90613      }
90614    }
90615  }
90616
90617  /* Final cleanup
90618  */
90619  whereInfoFree(db, pWInfo);
90620  return;
90621}
90622
90623/************** End of where.c ***********************************************/
90624/************** Begin file parse.c *******************************************/
90625/* Driver template for the LEMON parser generator.
90626** The author disclaims copyright to this source code.
90627**
90628** This version of "lempar.c" is modified, slightly, for use by SQLite.
90629** The only modifications are the addition of a couple of NEVER()
90630** macros to disable tests that are needed in the case of a general
90631** LALR(1) grammar but which are always false in the
90632** specific grammar used by SQLite.
90633*/
90634/* First off, code is included that follows the "include" declaration
90635** in the input grammar file. */
90636
90637
90638/*
90639** Disable all error recovery processing in the parser push-down
90640** automaton.
90641*/
90642#define YYNOERRORRECOVERY 1
90643
90644/*
90645** Make yytestcase() the same as testcase()
90646*/
90647#define yytestcase(X) testcase(X)
90648
90649/*
90650** An instance of this structure holds information about the
90651** LIMIT clause of a SELECT statement.
90652*/
90653struct LimitVal {
90654  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
90655  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
90656};
90657
90658/*
90659** An instance of this structure is used to store the LIKE,
90660** GLOB, NOT LIKE, and NOT GLOB operators.
90661*/
90662struct LikeOp {
90663  Token eOperator;  /* "like" or "glob" or "regexp" */
90664  int not;         /* True if the NOT keyword is present */
90665};
90666
90667/*
90668** An instance of the following structure describes the event of a
90669** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
90670** TK_DELETE, or TK_INSTEAD.  If the event is of the form
90671**
90672**      UPDATE ON (a,b,c)
90673**
90674** Then the "b" IdList records the list "a,b,c".
90675*/
90676struct TrigEvent { int a; IdList * b; };
90677
90678/*
90679** An instance of this structure holds the ATTACH key and the key type.
90680*/
90681struct AttachKey { int type;  Token key; };
90682
90683
90684  /* This is a utility routine used to set the ExprSpan.zStart and
90685  ** ExprSpan.zEnd values of pOut so that the span covers the complete
90686  ** range of text beginning with pStart and going to the end of pEnd.
90687  */
90688  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
90689    pOut->zStart = pStart->z;
90690    pOut->zEnd = &pEnd->z[pEnd->n];
90691  }
90692
90693  /* Construct a new Expr object from a single identifier.  Use the
90694  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
90695  ** that created the expression.
90696  */
90697  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
90698    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
90699    pOut->zStart = pValue->z;
90700    pOut->zEnd = &pValue->z[pValue->n];
90701  }
90702
90703  /* This routine constructs a binary expression node out of two ExprSpan
90704  ** objects and uses the result to populate a new ExprSpan object.
90705  */
90706  static void spanBinaryExpr(
90707    ExprSpan *pOut,     /* Write the result here */
90708    Parse *pParse,      /* The parsing context.  Errors accumulate here */
90709    int op,             /* The binary operation */
90710    ExprSpan *pLeft,    /* The left operand */
90711    ExprSpan *pRight    /* The right operand */
90712  ){
90713    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
90714    pOut->zStart = pLeft->zStart;
90715    pOut->zEnd = pRight->zEnd;
90716  }
90717
90718  /* Construct an expression node for a unary postfix operator
90719  */
90720  static void spanUnaryPostfix(
90721    ExprSpan *pOut,        /* Write the new expression node here */
90722    Parse *pParse,         /* Parsing context to record errors */
90723    int op,                /* The operator */
90724    ExprSpan *pOperand,    /* The operand */
90725    Token *pPostOp         /* The operand token for setting the span */
90726  ){
90727    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
90728    pOut->zStart = pOperand->zStart;
90729    pOut->zEnd = &pPostOp->z[pPostOp->n];
90730  }
90731
90732  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
90733  ** unary TK_ISNULL or TK_NOTNULL expression. */
90734  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
90735    sqlite3 *db = pParse->db;
90736    if( db->mallocFailed==0 && pY->op==TK_NULL ){
90737      pA->op = (u8)op;
90738      sqlite3ExprDelete(db, pA->pRight);
90739      pA->pRight = 0;
90740    }
90741  }
90742
90743  /* Construct an expression node for a unary prefix operator
90744  */
90745  static void spanUnaryPrefix(
90746    ExprSpan *pOut,        /* Write the new expression node here */
90747    Parse *pParse,         /* Parsing context to record errors */
90748    int op,                /* The operator */
90749    ExprSpan *pOperand,    /* The operand */
90750    Token *pPreOp         /* The operand token for setting the span */
90751  ){
90752    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
90753    pOut->zStart = pPreOp->z;
90754    pOut->zEnd = pOperand->zEnd;
90755  }
90756/* Next is all token values, in a form suitable for use by makeheaders.
90757** This section will be null unless lemon is run with the -m switch.
90758*/
90759/*
90760** These constants (all generated automatically by the parser generator)
90761** specify the various kinds of tokens (terminals) that the parser
90762** understands.
90763**
90764** Each symbol here is a terminal symbol in the grammar.
90765*/
90766/* Make sure the INTERFACE macro is defined.
90767*/
90768#ifndef INTERFACE
90769# define INTERFACE 1
90770#endif
90771/* The next thing included is series of defines which control
90772** various aspects of the generated parser.
90773**    YYCODETYPE         is the data type used for storing terminal
90774**                       and nonterminal numbers.  "unsigned char" is
90775**                       used if there are fewer than 250 terminals
90776**                       and nonterminals.  "int" is used otherwise.
90777**    YYNOCODE           is a number of type YYCODETYPE which corresponds
90778**                       to no legal terminal or nonterminal number.  This
90779**                       number is used to fill in empty slots of the hash
90780**                       table.
90781**    YYFALLBACK         If defined, this indicates that one or more tokens
90782**                       have fall-back values which should be used if the
90783**                       original value of the token will not parse.
90784**    YYACTIONTYPE       is the data type used for storing terminal
90785**                       and nonterminal numbers.  "unsigned char" is
90786**                       used if there are fewer than 250 rules and
90787**                       states combined.  "int" is used otherwise.
90788**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
90789**                       directly to the parser from the tokenizer.
90790**    YYMINORTYPE        is the data type used for all minor tokens.
90791**                       This is typically a union of many types, one of
90792**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
90793**                       for base tokens is called "yy0".
90794**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
90795**                       zero the stack is dynamically sized using realloc()
90796**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
90797**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
90798**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
90799**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
90800**    YYNSTATE           the combined number of states.
90801**    YYNRULE            the number of rules in the grammar
90802**    YYERRORSYMBOL      is the code number of the error symbol.  If not
90803**                       defined, then do no error processing.
90804*/
90805#define YYCODETYPE unsigned char
90806#define YYNOCODE 254
90807#define YYACTIONTYPE unsigned short int
90808#define YYWILDCARD 67
90809#define sqlite3ParserTOKENTYPE Token
90810typedef union {
90811  int yyinit;
90812  sqlite3ParserTOKENTYPE yy0;
90813  Select* yy3;
90814  ExprList* yy14;
90815  SrcList* yy65;
90816  struct LikeOp yy96;
90817  Expr* yy132;
90818  u8 yy186;
90819  int yy328;
90820  ExprSpan yy346;
90821  struct TrigEvent yy378;
90822  IdList* yy408;
90823  struct {int value; int mask;} yy429;
90824  TriggerStep* yy473;
90825  struct LimitVal yy476;
90826} YYMINORTYPE;
90827#ifndef YYSTACKDEPTH
90828#define YYSTACKDEPTH 100
90829#endif
90830#define sqlite3ParserARG_SDECL Parse *pParse;
90831#define sqlite3ParserARG_PDECL ,Parse *pParse
90832#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
90833#define sqlite3ParserARG_STORE yypParser->pParse = pParse
90834#define YYNSTATE 631
90835#define YYNRULE 330
90836#define YYFALLBACK 1
90837#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
90838#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
90839#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
90840
90841/* The yyzerominor constant is used to initialize instances of
90842** YYMINORTYPE objects to zero. */
90843static const YYMINORTYPE yyzerominor = { 0 };
90844
90845/* Define the yytestcase() macro to be a no-op if is not already defined
90846** otherwise.
90847**
90848** Applications can choose to define yytestcase() in the %include section
90849** to a macro that can assist in verifying code coverage.  For production
90850** code the yytestcase() macro should be turned off.  But it is useful
90851** for testing.
90852*/
90853#ifndef yytestcase
90854# define yytestcase(X)
90855#endif
90856
90857
90858/* Next are the tables used to determine what action to take based on the
90859** current state and lookahead token.  These tables are used to implement
90860** functions that take a state number and lookahead value and return an
90861** action integer.
90862**
90863** Suppose the action integer is N.  Then the action is determined as
90864** follows
90865**
90866**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
90867**                                      token onto the stack and goto state N.
90868**
90869**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
90870**
90871**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
90872**
90873**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
90874**
90875**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
90876**                                      slots in the yy_action[] table.
90877**
90878** The action table is constructed as a single large table named yy_action[].
90879** Given state S and lookahead X, the action is computed as
90880**
90881**      yy_action[ yy_shift_ofst[S] + X ]
90882**
90883** If the index value yy_shift_ofst[S]+X is out of range or if the value
90884** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
90885** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
90886** and that yy_default[S] should be used instead.
90887**
90888** The formula above is for computing the action when the lookahead is
90889** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
90890** a reduce action) then the yy_reduce_ofst[] array is used in place of
90891** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
90892** YY_SHIFT_USE_DFLT.
90893**
90894** The following are the tables generated in this section:
90895**
90896**  yy_action[]        A single table containing all actions.
90897**  yy_lookahead[]     A table containing the lookahead for each entry in
90898**                     yy_action.  Used to detect hash collisions.
90899**  yy_shift_ofst[]    For each state, the offset into yy_action for
90900**                     shifting terminals.
90901**  yy_reduce_ofst[]   For each state, the offset into yy_action for
90902**                     shifting non-terminals after a reduce.
90903**  yy_default[]       Default action for each state.
90904*/
90905#define YY_ACTTAB_COUNT (1543)
90906static const YYACTIONTYPE yy_action[] = {
90907 /*     0 */   313,   49,  556,   46,  147,  172,  628,  598,   55,   55,
90908 /*    10 */    55,   55,  302,   53,   53,   53,   53,   52,   52,   51,
90909 /*    20 */    51,   51,   50,  238,  603,   66,  624,  623,  604,  598,
90910 /*    30 */   591,  585,   48,   53,   53,   53,   53,   52,   52,   51,
90911 /*    40 */    51,   51,   50,  238,   51,   51,   51,   50,  238,   56,
90912 /*    50 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
90913 /*    60 */    55,   55,  609,   53,   53,   53,   53,   52,   52,   51,
90914 /*    70 */    51,   51,   50,  238,  313,  598,  672,  330,  411,  217,
90915 /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
90916 /*    90 */    50,  238,  330,  414,  621,  620,  166,  598,  673,  382,
90917 /*   100 */   379,  378,  602,   73,  591,  585,  307,  424,  166,   58,
90918 /*   110 */   377,  382,  379,  378,  516,  515,  624,  623,  254,  200,
90919 /*   120 */   199,  198,  377,   56,   57,   47,  583,  582,  584,  584,
90920 /*   130 */    54,   54,   55,   55,   55,   55,  581,   53,   53,   53,
90921 /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  270,
90922 /*   150 */   226,  422,  283,  133,  177,  139,  284,  385,  279,  384,
90923 /*   160 */   169,  197,  251,  282,  253,  226,  411,  275,  440,  167,
90924 /*   170 */   139,  284,  385,  279,  384,  169,  571,  236,  591,  585,
90925 /*   180 */   240,  414,  275,  622,  621,  620,  674,  437,  441,  442,
90926 /*   190 */   602,   88,  352,  266,  439,  268,  438,   56,   57,   47,
90927 /*   200 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
90928 /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
90929 /*   220 */    50,  238,  313,  471,   52,   52,   51,   51,   51,   50,
90930 /*   230 */   238,  234,  166,  491,  567,  382,  379,  378,    1,  440,
90931 /*   240 */   252,  176,  624,  623,  608,   67,  377,  513,  622,  443,
90932 /*   250 */   237,  577,  591,  585,  622,  172,  466,  598,  554,  441,
90933 /*   260 */   340,  409,  526,  580,  580,  349,  596,  553,  194,  482,
90934 /*   270 */   175,   56,   57,   47,  583,  582,  584,  584,   54,   54,
90935 /*   280 */    55,   55,   55,   55,  562,   53,   53,   53,   53,   52,
90936 /*   290 */    52,   51,   51,   51,   50,  238,  313,  594,  594,  594,
90937 /*   300 */   561,  578,  469,   65,  259,  351,  258,  411,  624,  623,
90938 /*   310 */   621,  620,  332,  576,  575,  240,  560,  568,  520,  411,
90939 /*   320 */   341,  237,  414,  624,  623,  598,  591,  585,  542,  519,
90940 /*   330 */   171,  602,   95,   68,  414,  624,  623,  624,  623,   38,
90941 /*   340 */   877,  506,  507,  602,   88,   56,   57,   47,  583,  582,
90942 /*   350 */   584,  584,   54,   54,   55,   55,   55,   55,  532,   53,
90943 /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
90944 /*   370 */   313,  411,  579,  398,  531,  237,  621,  620,  388,  625,
90945 /*   380 */   500,  206,  167,  396,  233,  312,  414,  387,  569,  492,
90946 /*   390 */   216,  621,  620,  566,  622,  602,   74,  533,  210,  491,
90947 /*   400 */   591,  585,  548,  621,  620,  621,  620,  300,  598,  466,
90948 /*   410 */   481,   67,  603,   35,  622,  601,  604,  547,    6,   56,
90949 /*   420 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
90950 /*   430 */    55,   55,  601,   53,   53,   53,   53,   52,   52,   51,
90951 /*   440 */    51,   51,   50,  238,  313,  411,  184,  409,  528,  580,
90952 /*   450 */   580,  551,  962,  186,  419,    2,  353,  259,  351,  258,
90953 /*   460 */   414,  409,  411,  580,  580,   44,  411,  544,  240,  602,
90954 /*   470 */    94,  190,    7,   62,  591,  585,  598,  414,  350,  607,
90955 /*   480 */   493,  414,  409,  317,  580,  580,  602,   95,  496,  565,
90956 /*   490 */   602,   80,  203,   56,   57,   47,  583,  582,  584,  584,
90957 /*   500 */    54,   54,   55,   55,   55,   55,  535,   53,   53,   53,
90958 /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  202,
90959 /*   520 */   564,  293,  511,   49,  562,   46,  147,  411,  394,  183,
90960 /*   530 */   563,  549,  505,  549,  174,  409,  322,  580,  580,   39,
90961 /*   540 */   561,   37,  414,  624,  623,  192,  473,  383,  591,  585,
90962 /*   550 */   474,  602,   80,  601,  504,  544,  560,  364,  402,  210,
90963 /*   560 */   421,  952,  361,  952,  365,  201,  144,   56,   57,   47,
90964 /*   570 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
90965 /*   580 */   559,   53,   53,   53,   53,   52,   52,   51,   51,   51,
90966 /*   590 */    50,  238,  313,  601,  232,  264,  272,  321,  374,  484,
90967 /*   600 */   510,  146,  342,  146,  328,  425,  485,  407,  576,  575,
90968 /*   610 */   622,  621,  620,   49,  168,   46,  147,  353,  546,  491,
90969 /*   620 */   204,  240,  591,  585,  421,  951,  549,  951,  549,  168,
90970 /*   630 */   429,   67,  390,  343,  622,  434,  307,  423,  338,  360,
90971 /*   640 */   391,   56,   57,   47,  583,  582,  584,  584,   54,   54,
90972 /*   650 */    55,   55,   55,   55,  601,   53,   53,   53,   53,   52,
90973 /*   660 */    52,   51,   51,   51,   50,  238,  313,   34,  318,  425,
90974 /*   670 */   237,   21,  359,  273,  411,  167,  411,  276,  411,  540,
90975 /*   680 */   411,  422,   13,  318,  619,  618,  617,  622,  275,  414,
90976 /*   690 */   336,  414,  622,  414,  622,  414,  591,  585,  602,   69,
90977 /*   700 */   602,   97,  602,  100,  602,   98,  631,  629,  334,  475,
90978 /*   710 */   475,  367,  319,  148,  327,   56,   57,   47,  583,  582,
90979 /*   720 */   584,  584,   54,   54,   55,   55,   55,   55,  411,   53,
90980 /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
90981 /*   740 */   313,  411,  331,  414,  411,   49,  276,   46,  147,  569,
90982 /*   750 */   406,  216,  602,  106,  573,  573,  414,  354,  524,  414,
90983 /*   760 */   411,  622,  411,  224,    4,  602,  104,  605,  602,  108,
90984 /*   770 */   591,  585,  622,   20,  375,  414,  167,  414,  215,  144,
90985 /*   780 */   470,  239,  167,  225,  602,  109,  602,  134,   18,   56,
90986 /*   790 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
90987 /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
90988 /*   810 */    51,   51,   50,  238,  313,  411,  276,  414,   12,  459,
90989 /*   820 */   276,  171,  411,   16,  223,  189,  602,  135,  354,  170,
90990 /*   830 */   414,  622,  630,    2,  411,  622,  540,  414,  143,  602,
90991 /*   840 */    61,  359,  132,  622,  591,  585,  602,  105,  458,  414,
90992 /*   850 */    23,  622,  446,  326,   23,  538,  622,  325,  602,  103,
90993 /*   860 */   427,  530,  309,   56,   57,   47,  583,  582,  584,  584,
90994 /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
90995 /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
90996 /*   890 */   264,  414,  411,  276,  359,  219,  157,  214,  357,  366,
90997 /*   900 */   602,   96,  522,  521,  414,  622,  358,  414,  622,  622,
90998 /*   910 */   411,  613,  612,  602,  102,  142,  602,   77,  591,  585,
90999 /*   920 */   529,  540,  231,  426,  308,  414,  622,  622,  468,  521,
91000 /*   930 */   324,  601,  257,  263,  602,   99,  622,   56,   45,   47,
91001 /*   940 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
91002 /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
91003 /*   960 */    50,  238,  313,  264,  264,  414,  411,  213,  209,  544,
91004 /*   970 */   544,  207,  611,   28,  602,  138,   50,  238,  622,  622,
91005 /*   980 */   381,  414,  503,  140,  323,  222,  274,  622,  590,  589,
91006 /*   990 */   602,  137,  591,  585,  629,  334,  606,   30,  622,  571,
91007 /*  1000 */   236,  601,  601,  130,  496,  601,  453,  451,  288,  286,
91008 /*  1010 */   587,  586,   57,   47,  583,  582,  584,  584,   54,   54,
91009 /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
91010 /*  1030 */    52,   51,   51,   51,   50,  238,  313,  588,  411,  414,
91011 /*  1040 */   411,  264,  410,  129,  595,  400,   27,  376,  602,  136,
91012 /*  1050 */   128,  165,  479,  414,  282,  414,  622,  622,  411,  622,
91013 /*  1060 */   622,  411,  602,   76,  602,   93,  591,  585,  188,  372,
91014 /*  1070 */   368,  125,  476,  414,  261,  160,  414,  171,  124,  472,
91015 /*  1080 */   123,   15,  602,   92,  450,  602,   75,   47,  583,  582,
91016 /*  1090 */   584,  584,   54,   54,   55,   55,   55,   55,  464,   53,
91017 /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
91018 /*  1110 */    43,  405,  264,    3,  558,  264,  545,  415,  623,  159,
91019 /*  1120 */   541,  158,  539,  278,   25,  461,  121,  622,  408,  622,
91020 /*  1130 */   622,  622,   24,   43,  405,  622,    3,  622,  622,  120,
91021 /*  1140 */   415,  623,   11,  456,  411,  156,  452,  403,  509,  277,
91022 /*  1150 */   118,  408,  489,  113,  205,  449,  271,  567,  221,  414,
91023 /*  1160 */   269,  267,  155,  622,  622,  111,  411,  622,  602,   95,
91024 /*  1170 */   403,  622,  411,  110,   10,  622,  622,   40,   41,  534,
91025 /*  1180 */   567,  414,   64,  264,   42,  413,  412,  414,  601,  596,
91026 /*  1190 */   602,   91,  445,  436,  150,  435,  602,   90,  622,  265,
91027 /*  1200 */    40,   41,  337,  242,  411,  191,  333,   42,  413,  412,
91028 /*  1210 */   398,  420,  596,  316,  622,  399,  260,  107,  230,  414,
91029 /*  1220 */   594,  594,  594,  593,  592,   14,  220,  411,  602,  101,
91030 /*  1230 */   240,  622,   43,  405,  362,    3,  149,  315,  626,  415,
91031 /*  1240 */   623,  127,  414,  594,  594,  594,  593,  592,   14,  622,
91032 /*  1250 */   408,  602,   89,  411,  181,   33,  405,  463,    3,  411,
91033 /*  1260 */   264,  462,  415,  623,  616,  615,  614,  355,  414,  403,
91034 /*  1270 */   417,  416,  622,  408,  414,  622,  622,  602,   87,  567,
91035 /*  1280 */   418,  627,  622,  602,   86,    8,  241,  180,  126,  255,
91036 /*  1290 */   600,  178,  403,  240,  208,  455,  395,  294,  444,   40,
91037 /*  1300 */    41,  297,  567,  248,  622,  296,   42,  413,  412,  247,
91038 /*  1310 */   622,  596,  244,  622,   30,   60,   31,  243,  430,  624,
91039 /*  1320 */   623,  292,   40,   41,  622,  295,  145,  622,  601,   42,
91040 /*  1330 */   413,  412,  622,  622,  596,  393,  622,  397,  599,   59,
91041 /*  1340 */   235,  622,  594,  594,  594,  593,  592,   14,  218,  291,
91042 /*  1350 */   622,   36,  344,  305,  304,  303,  179,  301,  411,  567,
91043 /*  1360 */   454,  557,  173,  185,  622,  594,  594,  594,  593,  592,
91044 /*  1370 */    14,  411,   29,  414,  151,  289,  246,  523,  411,  196,
91045 /*  1380 */   195,  335,  602,   85,  411,  245,  414,  526,  392,  543,
91046 /*  1390 */   411,  596,  287,  414,  285,  602,   72,  537,  153,  414,
91047 /*  1400 */   466,  411,  602,   71,  154,  414,  411,  152,  602,   84,
91048 /*  1410 */   386,  536,  329,  411,  602,   83,  414,  518,  280,  411,
91049 /*  1420 */   513,  414,  594,  594,  594,  602,   82,  517,  414,  311,
91050 /*  1430 */   602,   81,  411,  514,  414,  512,  131,  602,   70,  229,
91051 /*  1440 */   228,  227,  494,  602,   17,  411,  488,  414,  259,  346,
91052 /*  1450 */   249,  389,  487,  486,  314,  164,  602,   79,  310,  240,
91053 /*  1460 */   414,  373,  480,  163,  262,  371,  414,  162,  369,  602,
91054 /*  1470 */    78,  212,  478,   26,  477,  602,    9,  161,  467,  363,
91055 /*  1480 */   141,  122,  339,  187,  119,  457,  348,  117,  347,  116,
91056 /*  1490 */   115,  114,  448,  112,  182,  320,   22,  433,   19,  432,
91057 /*  1500 */   431,   63,  428,  610,  193,  298,  597,  574,  572,  404,
91058 /*  1510 */   555,  552,  290,  281,  510,  499,  498,  497,  495,  380,
91059 /*  1520 */   356,  460,  256,  250,  345,  447,  306,    5,  570,  550,
91060 /*  1530 */   299,  211,  370,  401,  550,  508,  502,  501,  490,  527,
91061 /*  1540 */   525,  483,  238,
91062};
91063static const YYCODETYPE yy_lookahead[] = {
91064 /*     0 */    19,  222,  223,  224,  225,   24,    1,   26,   77,   78,
91065 /*    10 */    79,   80,   15,   82,   83,   84,   85,   86,   87,   88,
91066 /*    20 */    89,   90,   91,   92,  113,   22,   26,   27,  117,   26,
91067 /*    30 */    49,   50,   81,   82,   83,   84,   85,   86,   87,   88,
91068 /*    40 */    89,   90,   91,   92,   88,   89,   90,   91,   92,   68,
91069 /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91070 /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
91071 /*    70 */    89,   90,   91,   92,   19,   94,  118,   19,  150,   22,
91072 /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91073 /*    90 */    91,   92,   19,  165,   94,   95,   96,   94,  118,   99,
91074 /*   100 */   100,  101,  174,  175,   49,   50,   22,   23,   96,   54,
91075 /*   110 */   110,   99,  100,  101,    7,    8,   26,   27,   16,  105,
91076 /*   120 */   106,  107,  110,   68,   69,   70,   71,   72,   73,   74,
91077 /*   130 */    75,   76,   77,   78,   79,   80,  113,   82,   83,   84,
91078 /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   16,
91079 /*   150 */    92,   67,   98,   24,   96,   97,   98,   99,  100,  101,
91080 /*   160 */   102,   25,   60,  109,   62,   92,  150,  109,  150,   25,
91081 /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
91082 /*   180 */   116,  165,  109,  165,   94,   95,  118,   97,  170,  171,
91083 /*   190 */   174,  175,  128,   60,  104,   62,  106,   68,   69,   70,
91084 /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91085 /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91086 /*   220 */    91,   92,   19,   21,   86,   87,   88,   89,   90,   91,
91087 /*   230 */    92,  215,   96,  150,   66,   99,  100,  101,   22,  150,
91088 /*   240 */   138,  118,   26,   27,  161,  162,  110,  103,  165,  231,
91089 /*   250 */   232,   23,   49,   50,  165,   24,   57,   26,   32,  170,
91090 /*   260 */   171,  112,   94,  114,  115,   63,   98,   41,  185,  186,
91091 /*   270 */   118,   68,   69,   70,   71,   72,   73,   74,   75,   76,
91092 /*   280 */    77,   78,   79,   80,   12,   82,   83,   84,   85,   86,
91093 /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
91094 /*   300 */    28,   23,  100,   25,  105,  106,  107,  150,   26,   27,
91095 /*   310 */    94,   95,  169,  170,  171,  116,   44,   23,   46,  150,
91096 /*   320 */   231,  232,  165,   26,   27,   94,   49,   50,   23,   57,
91097 /*   330 */    25,  174,  175,   22,  165,   26,   27,   26,   27,  136,
91098 /*   340 */   138,   97,   98,  174,  175,   68,   69,   70,   71,   72,
91099 /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
91100 /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91101 /*   370 */    19,  150,   23,  216,   23,  232,   94,   95,  221,  150,
91102 /*   380 */    23,  160,   25,  214,  215,  163,  165,   88,  166,  167,
91103 /*   390 */   168,   94,   95,   23,  165,  174,  175,   88,  160,  150,
91104 /*   400 */    49,   50,  120,   94,   95,   94,   95,  158,   26,   57,
91105 /*   410 */   161,  162,  113,  136,  165,  194,  117,  120,   22,   68,
91106 /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91107 /*   430 */    79,   80,  194,   82,   83,   84,   85,   86,   87,   88,
91108 /*   440 */    89,   90,   91,   92,   19,  150,   23,  112,   23,  114,
91109 /*   450 */   115,   25,  142,  143,  144,  145,  218,  105,  106,  107,
91110 /*   460 */   165,  112,  150,  114,  115,   22,  150,  166,  116,  174,
91111 /*   470 */   175,   22,   76,  235,   49,   50,   94,  165,  240,  172,
91112 /*   480 */   173,  165,  112,  155,  114,  115,  174,  175,  181,   11,
91113 /*   490 */   174,  175,   22,   68,   69,   70,   71,   72,   73,   74,
91114 /*   500 */    75,   76,   77,   78,   79,   80,  205,   82,   83,   84,
91115 /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  160,
91116 /*   520 */    23,  226,   23,  222,   12,  224,  225,  150,  216,   23,
91117 /*   530 */    23,   25,   36,   25,   25,  112,  220,  114,  115,  135,
91118 /*   540 */    28,  137,  165,   26,   27,  119,   30,   51,   49,   50,
91119 /*   550 */    34,  174,  175,  194,   58,  166,   44,  229,   46,  160,
91120 /*   560 */    22,   23,  234,   25,   48,  206,  207,   68,   69,   70,
91121 /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91122 /*   580 */    23,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91123 /*   590 */    91,   92,   19,  194,  205,  150,   23,  220,   19,  181,
91124 /*   600 */   182,   95,   97,   95,  108,   67,  188,  169,  170,  171,
91125 /*   610 */   165,   94,   95,  222,   50,  224,  225,  218,  120,  150,
91126 /*   620 */   160,  116,   49,   50,   22,   23,  120,   25,  120,   50,
91127 /*   630 */   161,  162,   19,  128,  165,  244,   22,   23,  193,  240,
91128 /*   640 */    27,   68,   69,   70,   71,   72,   73,   74,   75,   76,
91129 /*   650 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
91130 /*   660 */    87,   88,   89,   90,   91,   92,   19,   25,  104,   67,
91131 /*   670 */   232,   24,  150,   23,  150,   25,  150,  150,  150,  150,
91132 /*   680 */   150,   67,   25,  104,    7,    8,    9,  165,  109,  165,
91133 /*   690 */   245,  165,  165,  165,  165,  165,   49,   50,  174,  175,
91134 /*   700 */   174,  175,  174,  175,  174,  175,    0,    1,    2,  105,
91135 /*   710 */   106,  107,  248,  249,  187,   68,   69,   70,   71,   72,
91136 /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
91137 /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91138 /*   740 */    19,  150,  213,  165,  150,  222,  150,  224,  225,  166,
91139 /*   750 */   167,  168,  174,  175,  129,  130,  165,  150,  165,  165,
91140 /*   760 */   150,  165,  150,  241,   35,  174,  175,  174,  174,  175,
91141 /*   770 */    49,   50,  165,   52,   23,  165,   25,  165,  206,  207,
91142 /*   780 */    23,  197,   25,  187,  174,  175,  174,  175,  204,   68,
91143 /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
91144 /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
91145 /*   810 */    89,   90,   91,   92,   19,  150,  150,  165,   35,   23,
91146 /*   820 */   150,   25,  150,   22,  217,   24,  174,  175,  150,   35,
91147 /*   830 */   165,  165,  144,  145,  150,  165,  150,  165,  118,  174,
91148 /*   840 */   175,  150,   22,  165,   49,   50,  174,  175,   23,  165,
91149 /*   850 */    25,  165,   23,  187,   25,   27,  165,  187,  174,  175,
91150 /*   860 */    23,   23,   25,   68,   69,   70,   71,   72,   73,   74,
91151 /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
91152 /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
91153 /*   890 */   150,  165,  150,  150,  150,  217,   25,  160,   19,  213,
91154 /*   900 */   174,  175,  190,  191,  165,  165,   27,  165,  165,  165,
91155 /*   910 */   150,  150,  150,  174,  175,   39,  174,  175,   49,   50,
91156 /*   920 */    23,  150,   52,  250,  251,  165,  165,  165,  190,  191,
91157 /*   930 */   187,  194,  241,  193,  174,  175,  165,   68,   69,   70,
91158 /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
91159 /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
91160 /*   960 */    91,   92,   19,  150,  150,  165,  150,  160,  160,  166,
91161 /*   970 */   166,  160,  150,   22,  174,  175,   91,   92,  165,  165,
91162 /*   980 */    52,  165,   29,  150,  213,  241,   23,  165,   49,   50,
91163 /*   990 */   174,  175,   49,   50,    1,    2,  173,  126,  165,   86,
91164 /*  1000 */    87,  194,  194,   22,  181,  194,  193,  193,  205,  205,
91165 /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
91166 /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
91167 /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
91168 /*  1040 */   150,  150,  150,   22,  150,  150,   22,   52,  174,  175,
91169 /*  1050 */    22,  102,   20,  165,  109,  165,  165,  165,  150,  165,
91170 /*  1060 */   165,  150,  174,  175,  174,  175,   49,   50,   24,   19,
91171 /*  1070 */    43,  104,   59,  165,  138,  104,  165,   25,   53,   53,
91172 /*  1080 */    22,    5,  174,  175,  193,  174,  175,   70,   71,   72,
91173 /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,    1,   82,
91174 /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
91175 /*  1110 */    19,   20,  150,   22,  150,  150,  150,   26,   27,  118,
91176 /*  1120 */   150,   35,  150,  150,   76,   27,  108,  165,   37,  165,
91177 /*  1130 */   165,  165,   76,   19,   20,  165,   22,  165,  165,  127,
91178 /*  1140 */    26,   27,   22,    1,  150,   16,   20,   56,  150,  150,
91179 /*  1150 */   119,   37,  150,  119,  160,  193,  150,   66,  193,  165,
91180 /*  1160 */   150,  150,  121,  165,  165,  108,  150,  165,  174,  175,
91181 /*  1170 */    56,  165,  150,  127,   22,  165,  165,   86,   87,   88,
91182 /*  1180 */    66,  165,   16,  150,   93,   94,   95,  165,  194,   98,
91183 /*  1190 */   174,  175,  128,   23,   15,   23,  174,  175,  165,  150,
91184 /*  1200 */    86,   87,   65,  140,  150,   22,    3,   93,   94,   95,
91185 /*  1210 */   216,    4,   98,  252,  165,  221,  150,  164,  180,  165,
91186 /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
91187 /*  1230 */   116,  165,   19,   20,  150,   22,  249,  252,  149,   26,
91188 /*  1240 */    27,  180,  165,  129,  130,  131,  132,  133,  134,  165,
91189 /*  1250 */    37,  174,  175,  150,    6,   19,   20,  150,   22,  150,
91190 /*  1260 */   150,  150,   26,   27,  149,  149,   13,  150,  165,   56,
91191 /*  1270 */   149,  159,  165,   37,  165,  165,  165,  174,  175,   66,
91192 /*  1280 */   146,  147,  165,  174,  175,   25,  152,  151,  154,  150,
91193 /*  1290 */   194,  151,   56,  116,  160,  150,  123,  202,  150,   86,
91194 /*  1300 */    87,  199,   66,  193,  165,  200,   93,   94,   95,  150,
91195 /*  1310 */   165,   98,  150,  165,  126,   22,  124,  150,  150,   26,
91196 /*  1320 */    27,  150,   86,   87,  165,  201,  150,  165,  194,   93,
91197 /*  1330 */    94,   95,  165,  165,   98,  150,  165,  122,  203,  125,
91198 /*  1340 */   227,  165,  129,  130,  131,  132,  133,  134,    5,  150,
91199 /*  1350 */   165,  135,  218,   10,   11,   12,   13,   14,  150,   66,
91200 /*  1360 */    17,  157,  118,  157,  165,  129,  130,  131,  132,  133,
91201 /*  1370 */   134,  150,  104,  165,   31,  210,   33,  176,  150,   86,
91202 /*  1380 */    87,  247,  174,  175,  150,   42,  165,   94,  121,  211,
91203 /*  1390 */   150,   98,  210,  165,  210,  174,  175,  211,   55,  165,
91204 /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
91205 /*  1410 */   104,  211,   47,  150,  174,  175,  165,  176,  176,  150,
91206 /*  1420 */   103,  165,  129,  130,  131,  174,  175,  184,  165,  179,
91207 /*  1430 */   174,  175,  150,  178,  165,  176,   22,  174,  175,  230,
91208 /*  1440 */    92,  230,  184,  174,  175,  150,  176,  165,  105,  106,
91209 /*  1450 */   107,  150,  176,  176,  111,  156,  174,  175,  179,  116,
91210 /*  1460 */   165,   18,  157,  156,  238,  157,  165,  156,   45,  174,
91211 /*  1470 */   175,  157,  157,  135,  239,  174,  175,  156,  189,  157,
91212 /*  1480 */    68,  189,  139,  219,   22,  199,  157,  192,   18,  192,
91213 /*  1490 */   192,  192,  199,  189,  219,  157,  243,   40,  243,  157,
91214 /*  1500 */   157,  246,   38,  153,  196,  198,  166,  233,  233,  228,
91215 /*  1510 */   177,  177,  209,  177,  182,  177,  166,  177,  166,  178,
91216 /*  1520 */   242,  199,  242,  209,  209,  199,  148,  196,  166,  208,
91217 /*  1530 */   195,  236,  237,  191,  208,  183,  183,  183,  186,  174,
91218 /*  1540 */   174,  186,   92,
91219};
91220#define YY_SHIFT_USE_DFLT (-90)
91221#define YY_SHIFT_COUNT (418)
91222#define YY_SHIFT_MIN   (-89)
91223#define YY_SHIFT_MAX   (1470)
91224static const short yy_shift_ofst[] = {
91225 /*     0 */   993, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
91226 /*    10 */  1213, 1213, 1213, 1213, 1213,  352,  517,  721, 1091, 1213,
91227 /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91228 /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91229 /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
91230 /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
91231 /*    60 */  1213,  -49,  199,  517,  517,  913,  913,  382, 1177,   55,
91232 /*    70 */   647,  573,  499,  425,  351,  277,  203,  129,  795,  795,
91233 /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
91234 /*    90 */   795,  795,  795,  795,  795,  795,  869,  795,  943, 1017,
91235 /*   100 */  1017,  -69,  -69,  -69,  -69,   -1,   -1,   58,  138,  -44,
91236 /*   110 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91237 /*   120 */   517,  517,  517,  517,  517,  517,  202,  579,  517,  517,
91238 /*   130 */   517,  517,  517,  382,  885, 1450,  -90,  -90,  -90, 1293,
91239 /*   140 */    73,  272,  272,  309,  311,  297,  282,  216,  602,  538,
91240 /*   150 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91241 /*   160 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91242 /*   170 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
91243 /*   180 */   517,  517,  505,  231,  231,  231,  706,   64, 1177, 1177,
91244 /*   190 */  1177,  -90,  -90,  -90,  136,  168,  168,   12,  496,  496,
91245 /*   200 */   496,  506,  423,  512,  370,  349,  335,  149,  149,  149,
91246 /*   210 */   149,  604,  516,  149,  149,  508,    3,  299,  677,  871,
91247 /*   220 */   613,  613,  879,  871,  879,  144,  382,  226,  382,  226,
91248 /*   230 */   564,  226,  613,  226,  226,  404,  625,  625,  382,  426,
91249 /*   240 */   -89,  801, 1464, 1244, 1244, 1457, 1457, 1244, 1462, 1412,
91250 /*   250 */  1188, 1470, 1470, 1470, 1470, 1244, 1188, 1462, 1412, 1412,
91251 /*   260 */  1244, 1443, 1338, 1423, 1244, 1244, 1443, 1244, 1443, 1244,
91252 /*   270 */  1443, 1414, 1306, 1306, 1306, 1365, 1348, 1348, 1414, 1306,
91253 /*   280 */  1317, 1306, 1365, 1306, 1306, 1267, 1268, 1267, 1268, 1267,
91254 /*   290 */  1268, 1244, 1244, 1216, 1214, 1215, 1192, 1173, 1188, 1177,
91255 /*   300 */  1260, 1253, 1253, 1248, 1248, 1248, 1248,  -90,  -90,  -90,
91256 /*   310 */   -90,  -90,  -90,  939,  102,  614,   84,  133,   14,  837,
91257 /*   320 */   396,  829,  825,  796,  757,  751,  650,  357,  244,  107,
91258 /*   330 */    54,  305,  278, 1207, 1203, 1183, 1063, 1179, 1137, 1166,
91259 /*   340 */  1172, 1170, 1064, 1152, 1046, 1057, 1034, 1126, 1041, 1129,
91260 /*   350 */  1142, 1031, 1120, 1012, 1056, 1048, 1018, 1098, 1086, 1001,
91261 /*   360 */  1097, 1076, 1058,  971,  936, 1026, 1052, 1025, 1013, 1027,
91262 /*   370 */   967, 1044, 1032, 1050,  945,  949, 1028,  995, 1024, 1021,
91263 /*   380 */   963,  981,  928,  953,  951,  870,  876,  897,  838,  720,
91264 /*   390 */   828,  794,  820,  498,  642,  783,  657,  729,  642,  557,
91265 /*   400 */   507,  509,  497,  470,  478,  449,  294,  228,  443,   23,
91266 /*   410 */   152,  123,   68,  -20,  -42,   57,   39,   -3,    5,
91267};
91268#define YY_REDUCE_USE_DFLT (-222)
91269#define YY_REDUCE_COUNT (312)
91270#define YY_REDUCE_MIN   (-221)
91271#define YY_REDUCE_MAX   (1378)
91272static const short yy_reduce_ofst[] = {
91273 /*     0 */   310,  994, 1134,  221,  169,  157,   89,   18,   83,  301,
91274 /*    10 */   377,  316,  312,   16,  295,  238,  249,  391, 1301, 1295,
91275 /*    20 */  1282, 1269, 1263, 1256, 1251, 1240, 1234, 1228, 1221, 1208,
91276 /*    30 */  1109, 1103, 1077, 1054, 1022, 1016,  911,  908,  890,  888,
91277 /*    40 */   874,  816,  800,  760,  742,  739,  726,  684,  672,  665,
91278 /*    50 */   652,  612,  610,  594,  591,  578,  530,  528,  526,  524,
91279 /*    60 */   -72, -221,  399,  469,  445,  438,  143,  222,  359,  523,
91280 /*    70 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91281 /*    80 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91282 /*    90 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
91283 /*   100 */   523,  523,  523,  523,  523,  523,  523,  307,  523,  523,
91284 /*   110 */  1110,  678, 1033,  965,  962,  891,  814,  813,  744,  771,
91285 /*   120 */   691,  607,  522,  743,  686,  740,  328,  418,  670,  666,
91286 /*   130 */   596,  527,  529,  583,  523,  523,  523,  523,  523,  593,
91287 /*   140 */   823,  738,  712,  892, 1199, 1185, 1176, 1171,  673,  673,
91288 /*   150 */  1168, 1167, 1162, 1159, 1148, 1145, 1139, 1117, 1111, 1107,
91289 /*   160 */  1084, 1066, 1049, 1011, 1010, 1006, 1002,  999,  998,  973,
91290 /*   170 */   972,  970,  966,  964,  895,  894,  892,  833,  822,  762,
91291 /*   180 */   761,  229,  811,  804,  803,  389,  688,  808,  807,  737,
91292 /*   190 */   460,  464,  572,  584, 1355, 1366, 1365, 1352, 1354, 1353,
91293 /*   200 */  1352, 1326, 1335, 1342, 1335, 1335, 1335, 1335, 1335, 1335,
91294 /*   210 */  1335, 1295, 1295, 1335, 1335, 1321, 1362, 1331, 1378, 1326,
91295 /*   220 */  1315, 1314, 1280, 1322, 1278, 1341, 1352, 1340, 1350, 1338,
91296 /*   230 */  1332, 1336, 1303, 1334, 1333, 1281, 1275, 1274, 1340, 1307,
91297 /*   240 */  1308, 1350, 1255, 1343, 1342, 1255, 1253, 1338, 1275, 1304,
91298 /*   250 */  1293, 1299, 1298, 1297, 1295, 1329, 1286, 1264, 1292, 1289,
91299 /*   260 */  1322, 1321, 1235, 1226, 1315, 1314, 1311, 1308, 1307, 1305,
91300 /*   270 */  1299, 1279, 1277, 1276, 1270, 1258, 1211, 1209, 1250, 1259,
91301 /*   280 */  1255, 1242, 1243, 1241, 1201, 1200, 1184, 1186, 1182, 1178,
91302 /*   290 */  1165, 1206, 1204, 1113, 1135, 1095, 1124, 1105, 1102, 1096,
91303 /*   300 */  1112, 1140, 1136, 1121, 1116, 1115, 1089,  985,  961,  987,
91304 /*   310 */  1061, 1038, 1053,
91305};
91306static const YYACTIONTYPE yy_default[] = {
91307 /*     0 */   636,  872,  961,  961,  961,  872,  901,  901,  961,  760,
91308 /*    10 */   961,  961,  961,  961,  870,  961,  961,  935,  961,  961,
91309 /*    20 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91310 /*    30 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91311 /*    40 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91312 /*    50 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91313 /*    60 */   961,  844,  961,  961,  961,  901,  901,  675,  764,  795,
91314 /*    70 */   961,  961,  961,  961,  961,  961,  961,  961,  934,  936,
91315 /*    80 */   810,  809,  803,  802,  914,  775,  800,  793,  786,  797,
91316 /*    90 */   873,  866,  867,  865,  869,  874,  961,  796,  832,  850,
91317 /*   100 */   831,  849,  856,  848,  834,  843,  833,  667,  835,  836,
91318 /*   110 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91319 /*   120 */   961,  961,  961,  961,  961,  961,  662,  729,  961,  961,
91320 /*   130 */   961,  961,  961,  961,  837,  838,  853,  852,  851,  961,
91321 /*   140 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91322 /*   150 */   961,  941,  939,  961,  885,  961,  961,  961,  961,  961,
91323 /*   160 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91324 /*   170 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91325 /*   180 */   961,  642,  961,  760,  760,  760,  636,  961,  961,  961,
91326 /*   190 */   961,  953,  764,  754,  720,  961,  961,  961,  961,  961,
91327 /*   200 */   961,  961,  961,  961,  961,  961,  961,  805,  743,  924,
91328 /*   210 */   926,  961,  907,  741,  664,  762,  677,  752,  644,  799,
91329 /*   220 */   777,  777,  919,  799,  919,  701,  961,  789,  961,  789,
91330 /*   230 */   698,  789,  777,  789,  789,  868,  961,  961,  961,  761,
91331 /*   240 */   752,  961,  946,  768,  768,  938,  938,  768,  811,  733,
91332 /*   250 */   799,  740,  740,  740,  740,  768,  799,  811,  733,  733,
91333 /*   260 */   768,  659,  913,  911,  768,  768,  659,  768,  659,  768,
91334 /*   270 */   659,  878,  731,  731,  731,  716,  882,  882,  878,  731,
91335 /*   280 */   701,  731,  716,  731,  731,  781,  776,  781,  776,  781,
91336 /*   290 */   776,  768,  768,  961,  794,  782,  792,  790,  799,  961,
91337 /*   300 */   719,  652,  652,  641,  641,  641,  641,  958,  958,  953,
91338 /*   310 */   703,  703,  685,  961,  961,  961,  961,  961,  961,  961,
91339 /*   320 */   887,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91340 /*   330 */   961,  961,  961,  961,  637,  948,  961,  961,  945,  961,
91341 /*   340 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91342 /*   350 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  917,
91343 /*   360 */   961,  961,  961,  961,  961,  961,  910,  909,  961,  961,
91344 /*   370 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91345 /*   380 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
91346 /*   390 */   961,  961,  961,  961,  791,  961,  783,  961,  871,  961,
91347 /*   400 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  746,
91348 /*   410 */   820,  961,  819,  823,  818,  669,  961,  650,  961,  633,
91349 /*   420 */   638,  957,  960,  959,  956,  955,  954,  949,  947,  944,
91350 /*   430 */   943,  942,  940,  937,  933,  891,  889,  896,  895,  894,
91351 /*   440 */   893,  892,  890,  888,  886,  806,  804,  801,  798,  932,
91352 /*   450 */   884,  742,  739,  738,  658,  950,  916,  925,  923,  812,
91353 /*   460 */   922,  921,  920,  918,  915,  902,  808,  807,  734,  876,
91354 /*   470 */   875,  661,  906,  905,  904,  908,  912,  903,  770,  660,
91355 /*   480 */   657,  666,  723,  722,  730,  728,  727,  726,  725,  724,
91356 /*   490 */   721,  668,  676,  687,  715,  700,  699,  881,  883,  880,
91357 /*   500 */   879,  708,  707,  713,  712,  711,  710,  709,  706,  705,
91358 /*   510 */   704,  697,  696,  702,  695,  718,  717,  714,  694,  737,
91359 /*   520 */   736,  735,  732,  693,  692,  691,  823,  690,  689,  829,
91360 /*   530 */   828,  816,  860,  757,  756,  755,  767,  766,  779,  778,
91361 /*   540 */   814,  813,  780,  765,  759,  758,  774,  773,  772,  771,
91362 /*   550 */   763,  753,  785,  788,  787,  784,  845,  862,  769,  859,
91363 /*   560 */   931,  930,  929,  928,  927,  864,  863,  830,  827,  680,
91364 /*   570 */   681,  900,  898,  899,  897,  683,  682,  679,  678,  861,
91365 /*   580 */   748,  747,  857,  854,  846,  841,  858,  855,  847,  842,
91366 /*   590 */   840,  839,  825,  824,  822,  821,  817,  826,  671,  749,
91367 /*   600 */   745,  744,  815,  751,  750,  688,  686,  684,  665,  663,
91368 /*   610 */   656,  654,  653,  655,  651,  649,  648,  647,  646,  645,
91369 /*   620 */   674,  673,  672,  670,  669,  643,  640,  639,  635,  634,
91370 /*   630 */   632,
91371};
91372
91373/* The next table maps tokens into fallback tokens.  If a construct
91374** like the following:
91375**
91376**      %fallback ID X Y Z.
91377**
91378** appears in the grammar, then ID becomes a fallback token for X, Y,
91379** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
91380** but it does not parse, the type of the token is changed to ID and
91381** the parse is retried before an error is thrown.
91382*/
91383#ifdef YYFALLBACK
91384static const YYCODETYPE yyFallback[] = {
91385    0,  /*          $ => nothing */
91386    0,  /*       SEMI => nothing */
91387   26,  /*    EXPLAIN => ID */
91388   26,  /*      QUERY => ID */
91389   26,  /*       PLAN => ID */
91390   26,  /*      BEGIN => ID */
91391    0,  /* TRANSACTION => nothing */
91392   26,  /*   DEFERRED => ID */
91393   26,  /*  IMMEDIATE => ID */
91394   26,  /*  EXCLUSIVE => ID */
91395    0,  /*     COMMIT => nothing */
91396   26,  /*        END => ID */
91397   26,  /*   ROLLBACK => ID */
91398   26,  /*  SAVEPOINT => ID */
91399   26,  /*    RELEASE => ID */
91400    0,  /*         TO => nothing */
91401    0,  /*      TABLE => nothing */
91402    0,  /*     CREATE => nothing */
91403   26,  /*         IF => ID */
91404    0,  /*        NOT => nothing */
91405    0,  /*     EXISTS => nothing */
91406   26,  /*       TEMP => ID */
91407    0,  /*         LP => nothing */
91408    0,  /*         RP => nothing */
91409    0,  /*         AS => nothing */
91410    0,  /*      COMMA => nothing */
91411    0,  /*         ID => nothing */
91412    0,  /*    INDEXED => nothing */
91413   26,  /*      ABORT => ID */
91414   26,  /*     ACTION => ID */
91415   26,  /*      AFTER => ID */
91416   26,  /*    ANALYZE => ID */
91417   26,  /*        ASC => ID */
91418   26,  /*     ATTACH => ID */
91419   26,  /*     BEFORE => ID */
91420   26,  /*         BY => ID */
91421   26,  /*    CASCADE => ID */
91422   26,  /*       CAST => ID */
91423   26,  /*   COLUMNKW => ID */
91424   26,  /*   CONFLICT => ID */
91425   26,  /*   DATABASE => ID */
91426   26,  /*       DESC => ID */
91427   26,  /*     DETACH => ID */
91428   26,  /*       EACH => ID */
91429   26,  /*       FAIL => ID */
91430   26,  /*        FOR => ID */
91431   26,  /*     IGNORE => ID */
91432   26,  /*  INITIALLY => ID */
91433   26,  /*    INSTEAD => ID */
91434   26,  /*    LIKE_KW => ID */
91435   26,  /*      MATCH => ID */
91436   26,  /*         NO => ID */
91437   26,  /*        KEY => ID */
91438   26,  /*         OF => ID */
91439   26,  /*     OFFSET => ID */
91440   26,  /*     PRAGMA => ID */
91441   26,  /*      RAISE => ID */
91442   26,  /*    REPLACE => ID */
91443   26,  /*   RESTRICT => ID */
91444   26,  /*        ROW => ID */
91445   26,  /*    TRIGGER => ID */
91446   26,  /*     VACUUM => ID */
91447   26,  /*       VIEW => ID */
91448   26,  /*    VIRTUAL => ID */
91449   26,  /*    REINDEX => ID */
91450   26,  /*     RENAME => ID */
91451   26,  /*   CTIME_KW => ID */
91452};
91453#endif /* YYFALLBACK */
91454
91455/* The following structure represents a single element of the
91456** parser's stack.  Information stored includes:
91457**
91458**   +  The state number for the parser at this level of the stack.
91459**
91460**   +  The value of the token stored at this level of the stack.
91461**      (In other words, the "major" token.)
91462**
91463**   +  The semantic value stored at this level of the stack.  This is
91464**      the information used by the action routines in the grammar.
91465**      It is sometimes called the "minor" token.
91466*/
91467struct yyStackEntry {
91468  YYACTIONTYPE stateno;  /* The state-number */
91469  YYCODETYPE major;      /* The major token value.  This is the code
91470                         ** number for the token at this stack level */
91471  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
91472                         ** is the value of the token  */
91473};
91474typedef struct yyStackEntry yyStackEntry;
91475
91476/* The state of the parser is completely contained in an instance of
91477** the following structure */
91478struct yyParser {
91479  int yyidx;                    /* Index of top element in stack */
91480#ifdef YYTRACKMAXSTACKDEPTH
91481  int yyidxMax;                 /* Maximum value of yyidx */
91482#endif
91483  int yyerrcnt;                 /* Shifts left before out of the error */
91484  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
91485#if YYSTACKDEPTH<=0
91486  int yystksz;                  /* Current side of the stack */
91487  yyStackEntry *yystack;        /* The parser's stack */
91488#else
91489  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
91490#endif
91491};
91492typedef struct yyParser yyParser;
91493
91494#ifndef NDEBUG
91495static FILE *yyTraceFILE = 0;
91496static char *yyTracePrompt = 0;
91497#endif /* NDEBUG */
91498
91499#ifndef NDEBUG
91500/*
91501** Turn parser tracing on by giving a stream to which to write the trace
91502** and a prompt to preface each trace message.  Tracing is turned off
91503** by making either argument NULL
91504**
91505** Inputs:
91506** <ul>
91507** <li> A FILE* to which trace output should be written.
91508**      If NULL, then tracing is turned off.
91509** <li> A prefix string written at the beginning of every
91510**      line of trace output.  If NULL, then tracing is
91511**      turned off.
91512** </ul>
91513**
91514** Outputs:
91515** None.
91516*/
91517SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
91518  yyTraceFILE = TraceFILE;
91519  yyTracePrompt = zTracePrompt;
91520  if( yyTraceFILE==0 ) yyTracePrompt = 0;
91521  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
91522}
91523#endif /* NDEBUG */
91524
91525#ifndef NDEBUG
91526/* For tracing shifts, the names of all terminals and nonterminals
91527** are required.  The following table supplies these names */
91528static const char *const yyTokenName[] = {
91529  "$",             "SEMI",          "EXPLAIN",       "QUERY",
91530  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
91531  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
91532  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
91533  "TABLE",         "CREATE",        "IF",            "NOT",
91534  "EXISTS",        "TEMP",          "LP",            "RP",
91535  "AS",            "COMMA",         "ID",            "INDEXED",
91536  "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
91537  "ASC",           "ATTACH",        "BEFORE",        "BY",
91538  "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
91539  "DATABASE",      "DESC",          "DETACH",        "EACH",
91540  "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
91541  "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
91542  "KEY",           "OF",            "OFFSET",        "PRAGMA",
91543  "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
91544  "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
91545  "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
91546  "OR",            "AND",           "IS",            "BETWEEN",
91547  "IN",            "ISNULL",        "NOTNULL",       "NE",
91548  "EQ",            "GT",            "LE",            "LT",
91549  "GE",            "ESCAPE",        "BITAND",        "BITOR",
91550  "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
91551  "STAR",          "SLASH",         "REM",           "CONCAT",
91552  "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
91553  "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
91554  "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
91555  "ON",            "INSERT",        "DELETE",        "UPDATE",
91556  "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
91557  "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
91558  "SELECT",        "DISTINCT",      "DOT",           "FROM",
91559  "JOIN",          "USING",         "ORDER",         "GROUP",
91560  "HAVING",        "LIMIT",         "WHERE",         "INTO",
91561  "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
91562  "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
91563  "THEN",          "ELSE",          "INDEX",         "ALTER",
91564  "ADD",           "error",         "input",         "cmdlist",
91565  "ecmd",          "explain",       "cmdx",          "cmd",
91566  "transtype",     "trans_opt",     "nm",            "savepoint_opt",
91567  "create_table",  "create_table_args",  "createkw",      "temp",
91568  "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
91569  "select",        "column",        "columnid",      "type",
91570  "carglist",      "id",            "ids",           "typetoken",
91571  "typename",      "signed",        "plus_num",      "minus_num",
91572  "carg",          "ccons",         "term",          "expr",
91573  "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
91574  "refargs",       "defer_subclause",  "refarg",        "refact",
91575  "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
91576  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
91577  "ifexists",      "fullname",      "oneselect",     "multiselect_op",
91578  "distinct",      "selcollist",    "from",          "where_opt",
91579  "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
91580  "sclp",          "as",            "seltablist",    "stl_prefix",
91581  "joinop",        "indexed_opt",   "on_opt",        "using_opt",
91582  "joinop2",       "inscollist",    "sortlist",      "sortitem",
91583  "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
91584  "itemlist",      "exprlist",      "likeop",        "escape",
91585  "between_op",    "in_op",         "case_operand",  "case_exprlist",
91586  "case_else",     "uniqueflag",    "collate",       "nmnum",
91587  "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
91588  "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause",
91589  "trigger_cmd",   "trnm",          "tridxby",       "database_kw_opt",
91590  "key_opt",       "add_column_fullname",  "kwcolumn_opt",  "create_vtab",
91591  "vtabarglist",   "vtabarg",       "vtabargtoken",  "lp",
91592  "anylist",
91593};
91594#endif /* NDEBUG */
91595
91596#ifndef NDEBUG
91597/* For tracing reduce actions, the names of all rules are required.
91598*/
91599static const char *const yyRuleName[] = {
91600 /*   0 */ "input ::= cmdlist",
91601 /*   1 */ "cmdlist ::= cmdlist ecmd",
91602 /*   2 */ "cmdlist ::= ecmd",
91603 /*   3 */ "ecmd ::= SEMI",
91604 /*   4 */ "ecmd ::= explain cmdx SEMI",
91605 /*   5 */ "explain ::=",
91606 /*   6 */ "explain ::= EXPLAIN",
91607 /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
91608 /*   8 */ "cmdx ::= cmd",
91609 /*   9 */ "cmd ::= BEGIN transtype trans_opt",
91610 /*  10 */ "trans_opt ::=",
91611 /*  11 */ "trans_opt ::= TRANSACTION",
91612 /*  12 */ "trans_opt ::= TRANSACTION nm",
91613 /*  13 */ "transtype ::=",
91614 /*  14 */ "transtype ::= DEFERRED",
91615 /*  15 */ "transtype ::= IMMEDIATE",
91616 /*  16 */ "transtype ::= EXCLUSIVE",
91617 /*  17 */ "cmd ::= COMMIT trans_opt",
91618 /*  18 */ "cmd ::= END trans_opt",
91619 /*  19 */ "cmd ::= ROLLBACK trans_opt",
91620 /*  20 */ "savepoint_opt ::= SAVEPOINT",
91621 /*  21 */ "savepoint_opt ::=",
91622 /*  22 */ "cmd ::= SAVEPOINT nm",
91623 /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
91624 /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
91625 /*  25 */ "cmd ::= create_table create_table_args",
91626 /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
91627 /*  27 */ "createkw ::= CREATE",
91628 /*  28 */ "ifnotexists ::=",
91629 /*  29 */ "ifnotexists ::= IF NOT EXISTS",
91630 /*  30 */ "temp ::= TEMP",
91631 /*  31 */ "temp ::=",
91632 /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
91633 /*  33 */ "create_table_args ::= AS select",
91634 /*  34 */ "columnlist ::= columnlist COMMA column",
91635 /*  35 */ "columnlist ::= column",
91636 /*  36 */ "column ::= columnid type carglist",
91637 /*  37 */ "columnid ::= nm",
91638 /*  38 */ "id ::= ID",
91639 /*  39 */ "id ::= INDEXED",
91640 /*  40 */ "ids ::= ID|STRING",
91641 /*  41 */ "nm ::= id",
91642 /*  42 */ "nm ::= STRING",
91643 /*  43 */ "nm ::= JOIN_KW",
91644 /*  44 */ "type ::=",
91645 /*  45 */ "type ::= typetoken",
91646 /*  46 */ "typetoken ::= typename",
91647 /*  47 */ "typetoken ::= typename LP signed RP",
91648 /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
91649 /*  49 */ "typename ::= ids",
91650 /*  50 */ "typename ::= typename ids",
91651 /*  51 */ "signed ::= plus_num",
91652 /*  52 */ "signed ::= minus_num",
91653 /*  53 */ "carglist ::= carglist carg",
91654 /*  54 */ "carglist ::=",
91655 /*  55 */ "carg ::= CONSTRAINT nm ccons",
91656 /*  56 */ "carg ::= ccons",
91657 /*  57 */ "ccons ::= DEFAULT term",
91658 /*  58 */ "ccons ::= DEFAULT LP expr RP",
91659 /*  59 */ "ccons ::= DEFAULT PLUS term",
91660 /*  60 */ "ccons ::= DEFAULT MINUS term",
91661 /*  61 */ "ccons ::= DEFAULT id",
91662 /*  62 */ "ccons ::= NULL onconf",
91663 /*  63 */ "ccons ::= NOT NULL onconf",
91664 /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
91665 /*  65 */ "ccons ::= UNIQUE onconf",
91666 /*  66 */ "ccons ::= CHECK LP expr RP",
91667 /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
91668 /*  68 */ "ccons ::= defer_subclause",
91669 /*  69 */ "ccons ::= COLLATE ids",
91670 /*  70 */ "autoinc ::=",
91671 /*  71 */ "autoinc ::= AUTOINCR",
91672 /*  72 */ "refargs ::=",
91673 /*  73 */ "refargs ::= refargs refarg",
91674 /*  74 */ "refarg ::= MATCH nm",
91675 /*  75 */ "refarg ::= ON INSERT refact",
91676 /*  76 */ "refarg ::= ON DELETE refact",
91677 /*  77 */ "refarg ::= ON UPDATE refact",
91678 /*  78 */ "refact ::= SET NULL",
91679 /*  79 */ "refact ::= SET DEFAULT",
91680 /*  80 */ "refact ::= CASCADE",
91681 /*  81 */ "refact ::= RESTRICT",
91682 /*  82 */ "refact ::= NO ACTION",
91683 /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
91684 /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
91685 /*  85 */ "init_deferred_pred_opt ::=",
91686 /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
91687 /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
91688 /*  88 */ "conslist_opt ::=",
91689 /*  89 */ "conslist_opt ::= COMMA conslist",
91690 /*  90 */ "conslist ::= conslist COMMA tcons",
91691 /*  91 */ "conslist ::= conslist tcons",
91692 /*  92 */ "conslist ::= tcons",
91693 /*  93 */ "tcons ::= CONSTRAINT nm",
91694 /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
91695 /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
91696 /*  96 */ "tcons ::= CHECK LP expr RP onconf",
91697 /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
91698 /*  98 */ "defer_subclause_opt ::=",
91699 /*  99 */ "defer_subclause_opt ::= defer_subclause",
91700 /* 100 */ "onconf ::=",
91701 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
91702 /* 102 */ "orconf ::=",
91703 /* 103 */ "orconf ::= OR resolvetype",
91704 /* 104 */ "resolvetype ::= raisetype",
91705 /* 105 */ "resolvetype ::= IGNORE",
91706 /* 106 */ "resolvetype ::= REPLACE",
91707 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
91708 /* 108 */ "ifexists ::= IF EXISTS",
91709 /* 109 */ "ifexists ::=",
91710 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
91711 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
91712 /* 112 */ "cmd ::= select",
91713 /* 113 */ "select ::= oneselect",
91714 /* 114 */ "select ::= select multiselect_op oneselect",
91715 /* 115 */ "multiselect_op ::= UNION",
91716 /* 116 */ "multiselect_op ::= UNION ALL",
91717 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
91718 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
91719 /* 119 */ "distinct ::= DISTINCT",
91720 /* 120 */ "distinct ::= ALL",
91721 /* 121 */ "distinct ::=",
91722 /* 122 */ "sclp ::= selcollist COMMA",
91723 /* 123 */ "sclp ::=",
91724 /* 124 */ "selcollist ::= sclp expr as",
91725 /* 125 */ "selcollist ::= sclp STAR",
91726 /* 126 */ "selcollist ::= sclp nm DOT STAR",
91727 /* 127 */ "as ::= AS nm",
91728 /* 128 */ "as ::= ids",
91729 /* 129 */ "as ::=",
91730 /* 130 */ "from ::=",
91731 /* 131 */ "from ::= FROM seltablist",
91732 /* 132 */ "stl_prefix ::= seltablist joinop",
91733 /* 133 */ "stl_prefix ::=",
91734 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
91735 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
91736 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
91737 /* 137 */ "dbnm ::=",
91738 /* 138 */ "dbnm ::= DOT nm",
91739 /* 139 */ "fullname ::= nm dbnm",
91740 /* 140 */ "joinop ::= COMMA|JOIN",
91741 /* 141 */ "joinop ::= JOIN_KW JOIN",
91742 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
91743 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
91744 /* 144 */ "on_opt ::= ON expr",
91745 /* 145 */ "on_opt ::=",
91746 /* 146 */ "indexed_opt ::=",
91747 /* 147 */ "indexed_opt ::= INDEXED BY nm",
91748 /* 148 */ "indexed_opt ::= NOT INDEXED",
91749 /* 149 */ "using_opt ::= USING LP inscollist RP",
91750 /* 150 */ "using_opt ::=",
91751 /* 151 */ "orderby_opt ::=",
91752 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
91753 /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
91754 /* 154 */ "sortlist ::= sortitem sortorder",
91755 /* 155 */ "sortitem ::= expr",
91756 /* 156 */ "sortorder ::= ASC",
91757 /* 157 */ "sortorder ::= DESC",
91758 /* 158 */ "sortorder ::=",
91759 /* 159 */ "groupby_opt ::=",
91760 /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
91761 /* 161 */ "having_opt ::=",
91762 /* 162 */ "having_opt ::= HAVING expr",
91763 /* 163 */ "limit_opt ::=",
91764 /* 164 */ "limit_opt ::= LIMIT expr",
91765 /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
91766 /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
91767 /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
91768 /* 168 */ "where_opt ::=",
91769 /* 169 */ "where_opt ::= WHERE expr",
91770 /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
91771 /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
91772 /* 172 */ "setlist ::= nm EQ expr",
91773 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
91774 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
91775 /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
91776 /* 176 */ "insert_cmd ::= INSERT orconf",
91777 /* 177 */ "insert_cmd ::= REPLACE",
91778 /* 178 */ "itemlist ::= itemlist COMMA expr",
91779 /* 179 */ "itemlist ::= expr",
91780 /* 180 */ "inscollist_opt ::=",
91781 /* 181 */ "inscollist_opt ::= LP inscollist RP",
91782 /* 182 */ "inscollist ::= inscollist COMMA nm",
91783 /* 183 */ "inscollist ::= nm",
91784 /* 184 */ "expr ::= term",
91785 /* 185 */ "expr ::= LP expr RP",
91786 /* 186 */ "term ::= NULL",
91787 /* 187 */ "expr ::= id",
91788 /* 188 */ "expr ::= JOIN_KW",
91789 /* 189 */ "expr ::= nm DOT nm",
91790 /* 190 */ "expr ::= nm DOT nm DOT nm",
91791 /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
91792 /* 192 */ "term ::= STRING",
91793 /* 193 */ "expr ::= REGISTER",
91794 /* 194 */ "expr ::= VARIABLE",
91795 /* 195 */ "expr ::= expr COLLATE ids",
91796 /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
91797 /* 197 */ "expr ::= ID LP distinct exprlist RP",
91798 /* 198 */ "expr ::= ID LP STAR RP",
91799 /* 199 */ "term ::= CTIME_KW",
91800 /* 200 */ "expr ::= expr AND expr",
91801 /* 201 */ "expr ::= expr OR expr",
91802 /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
91803 /* 203 */ "expr ::= expr EQ|NE expr",
91804 /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
91805 /* 205 */ "expr ::= expr PLUS|MINUS expr",
91806 /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
91807 /* 207 */ "expr ::= expr CONCAT expr",
91808 /* 208 */ "likeop ::= LIKE_KW",
91809 /* 209 */ "likeop ::= NOT LIKE_KW",
91810 /* 210 */ "likeop ::= MATCH",
91811 /* 211 */ "likeop ::= NOT MATCH",
91812 /* 212 */ "escape ::= ESCAPE expr",
91813 /* 213 */ "escape ::=",
91814 /* 214 */ "expr ::= expr likeop expr escape",
91815 /* 215 */ "expr ::= expr ISNULL|NOTNULL",
91816 /* 216 */ "expr ::= expr NOT NULL",
91817 /* 217 */ "expr ::= expr IS expr",
91818 /* 218 */ "expr ::= expr IS NOT expr",
91819 /* 219 */ "expr ::= NOT expr",
91820 /* 220 */ "expr ::= BITNOT expr",
91821 /* 221 */ "expr ::= MINUS expr",
91822 /* 222 */ "expr ::= PLUS expr",
91823 /* 223 */ "between_op ::= BETWEEN",
91824 /* 224 */ "between_op ::= NOT BETWEEN",
91825 /* 225 */ "expr ::= expr between_op expr AND expr",
91826 /* 226 */ "in_op ::= IN",
91827 /* 227 */ "in_op ::= NOT IN",
91828 /* 228 */ "expr ::= expr in_op LP exprlist RP",
91829 /* 229 */ "expr ::= LP select RP",
91830 /* 230 */ "expr ::= expr in_op LP select RP",
91831 /* 231 */ "expr ::= expr in_op nm dbnm",
91832 /* 232 */ "expr ::= EXISTS LP select RP",
91833 /* 233 */ "expr ::= CASE case_operand case_exprlist case_else END",
91834 /* 234 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
91835 /* 235 */ "case_exprlist ::= WHEN expr THEN expr",
91836 /* 236 */ "case_else ::= ELSE expr",
91837 /* 237 */ "case_else ::=",
91838 /* 238 */ "case_operand ::= expr",
91839 /* 239 */ "case_operand ::=",
91840 /* 240 */ "exprlist ::= nexprlist",
91841 /* 241 */ "exprlist ::=",
91842 /* 242 */ "nexprlist ::= nexprlist COMMA expr",
91843 /* 243 */ "nexprlist ::= expr",
91844 /* 244 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
91845 /* 245 */ "uniqueflag ::= UNIQUE",
91846 /* 246 */ "uniqueflag ::=",
91847 /* 247 */ "idxlist_opt ::=",
91848 /* 248 */ "idxlist_opt ::= LP idxlist RP",
91849 /* 249 */ "idxlist ::= idxlist COMMA nm collate sortorder",
91850 /* 250 */ "idxlist ::= nm collate sortorder",
91851 /* 251 */ "collate ::=",
91852 /* 252 */ "collate ::= COLLATE ids",
91853 /* 253 */ "cmd ::= DROP INDEX ifexists fullname",
91854 /* 254 */ "cmd ::= VACUUM",
91855 /* 255 */ "cmd ::= VACUUM nm",
91856 /* 256 */ "cmd ::= PRAGMA nm dbnm",
91857 /* 257 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
91858 /* 258 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
91859 /* 259 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
91860 /* 260 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
91861 /* 261 */ "nmnum ::= plus_num",
91862 /* 262 */ "nmnum ::= nm",
91863 /* 263 */ "nmnum ::= ON",
91864 /* 264 */ "nmnum ::= DELETE",
91865 /* 265 */ "nmnum ::= DEFAULT",
91866 /* 266 */ "plus_num ::= plus_opt number",
91867 /* 267 */ "minus_num ::= MINUS number",
91868 /* 268 */ "number ::= INTEGER|FLOAT",
91869 /* 269 */ "plus_opt ::= PLUS",
91870 /* 270 */ "plus_opt ::=",
91871 /* 271 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
91872 /* 272 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
91873 /* 273 */ "trigger_time ::= BEFORE",
91874 /* 274 */ "trigger_time ::= AFTER",
91875 /* 275 */ "trigger_time ::= INSTEAD OF",
91876 /* 276 */ "trigger_time ::=",
91877 /* 277 */ "trigger_event ::= DELETE|INSERT",
91878 /* 278 */ "trigger_event ::= UPDATE",
91879 /* 279 */ "trigger_event ::= UPDATE OF inscollist",
91880 /* 280 */ "foreach_clause ::=",
91881 /* 281 */ "foreach_clause ::= FOR EACH ROW",
91882 /* 282 */ "when_clause ::=",
91883 /* 283 */ "when_clause ::= WHEN expr",
91884 /* 284 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
91885 /* 285 */ "trigger_cmd_list ::= trigger_cmd SEMI",
91886 /* 286 */ "trnm ::= nm",
91887 /* 287 */ "trnm ::= nm DOT nm",
91888 /* 288 */ "tridxby ::=",
91889 /* 289 */ "tridxby ::= INDEXED BY nm",
91890 /* 290 */ "tridxby ::= NOT INDEXED",
91891 /* 291 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
91892 /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
91893 /* 293 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
91894 /* 294 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
91895 /* 295 */ "trigger_cmd ::= select",
91896 /* 296 */ "expr ::= RAISE LP IGNORE RP",
91897 /* 297 */ "expr ::= RAISE LP raisetype COMMA nm RP",
91898 /* 298 */ "raisetype ::= ROLLBACK",
91899 /* 299 */ "raisetype ::= ABORT",
91900 /* 300 */ "raisetype ::= FAIL",
91901 /* 301 */ "cmd ::= DROP TRIGGER ifexists fullname",
91902 /* 302 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
91903 /* 303 */ "cmd ::= DETACH database_kw_opt expr",
91904 /* 304 */ "key_opt ::=",
91905 /* 305 */ "key_opt ::= KEY expr",
91906 /* 306 */ "database_kw_opt ::= DATABASE",
91907 /* 307 */ "database_kw_opt ::=",
91908 /* 308 */ "cmd ::= REINDEX",
91909 /* 309 */ "cmd ::= REINDEX nm dbnm",
91910 /* 310 */ "cmd ::= ANALYZE",
91911 /* 311 */ "cmd ::= ANALYZE nm dbnm",
91912 /* 312 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
91913 /* 313 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
91914 /* 314 */ "add_column_fullname ::= fullname",
91915 /* 315 */ "kwcolumn_opt ::=",
91916 /* 316 */ "kwcolumn_opt ::= COLUMNKW",
91917 /* 317 */ "cmd ::= create_vtab",
91918 /* 318 */ "cmd ::= create_vtab LP vtabarglist RP",
91919 /* 319 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
91920 /* 320 */ "vtabarglist ::= vtabarg",
91921 /* 321 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
91922 /* 322 */ "vtabarg ::=",
91923 /* 323 */ "vtabarg ::= vtabarg vtabargtoken",
91924 /* 324 */ "vtabargtoken ::= ANY",
91925 /* 325 */ "vtabargtoken ::= lp anylist RP",
91926 /* 326 */ "lp ::= LP",
91927 /* 327 */ "anylist ::=",
91928 /* 328 */ "anylist ::= anylist LP anylist RP",
91929 /* 329 */ "anylist ::= anylist ANY",
91930};
91931#endif /* NDEBUG */
91932
91933
91934#if YYSTACKDEPTH<=0
91935/*
91936** Try to increase the size of the parser stack.
91937*/
91938static void yyGrowStack(yyParser *p){
91939  int newSize;
91940  yyStackEntry *pNew;
91941
91942  newSize = p->yystksz*2 + 100;
91943  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
91944  if( pNew ){
91945    p->yystack = pNew;
91946    p->yystksz = newSize;
91947#ifndef NDEBUG
91948    if( yyTraceFILE ){
91949      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
91950              yyTracePrompt, p->yystksz);
91951    }
91952#endif
91953  }
91954}
91955#endif
91956
91957/*
91958** This function allocates a new parser.
91959** The only argument is a pointer to a function which works like
91960** malloc.
91961**
91962** Inputs:
91963** A pointer to the function used to allocate memory.
91964**
91965** Outputs:
91966** A pointer to a parser.  This pointer is used in subsequent calls
91967** to sqlite3Parser and sqlite3ParserFree.
91968*/
91969SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
91970  yyParser *pParser;
91971  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
91972  if( pParser ){
91973    pParser->yyidx = -1;
91974#ifdef YYTRACKMAXSTACKDEPTH
91975    pParser->yyidxMax = 0;
91976#endif
91977#if YYSTACKDEPTH<=0
91978    pParser->yystack = NULL;
91979    pParser->yystksz = 0;
91980    yyGrowStack(pParser);
91981#endif
91982  }
91983  return pParser;
91984}
91985
91986/* The following function deletes the value associated with a
91987** symbol.  The symbol can be either a terminal or nonterminal.
91988** "yymajor" is the symbol code, and "yypminor" is a pointer to
91989** the value.
91990*/
91991static void yy_destructor(
91992  yyParser *yypParser,    /* The parser */
91993  YYCODETYPE yymajor,     /* Type code for object to destroy */
91994  YYMINORTYPE *yypminor   /* The object to be destroyed */
91995){
91996  sqlite3ParserARG_FETCH;
91997  switch( yymajor ){
91998    /* Here is inserted the actions which take place when a
91999    ** terminal or non-terminal is destroyed.  This can happen
92000    ** when the symbol is popped from the stack during a
92001    ** reduce or during error processing or when a parser is
92002    ** being destroyed before it is finished parsing.
92003    **
92004    ** Note: during a reduce, the only symbols destroyed are those
92005    ** which appear on the RHS of the rule, but which are not used
92006    ** inside the C code.
92007    */
92008    case 160: /* select */
92009    case 194: /* oneselect */
92010{
92011sqlite3SelectDelete(pParse->db, (yypminor->yy3));
92012}
92013      break;
92014    case 174: /* term */
92015    case 175: /* expr */
92016    case 223: /* escape */
92017{
92018sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
92019}
92020      break;
92021    case 179: /* idxlist_opt */
92022    case 187: /* idxlist */
92023    case 197: /* selcollist */
92024    case 200: /* groupby_opt */
92025    case 202: /* orderby_opt */
92026    case 204: /* sclp */
92027    case 214: /* sortlist */
92028    case 216: /* nexprlist */
92029    case 217: /* setlist */
92030    case 220: /* itemlist */
92031    case 221: /* exprlist */
92032    case 227: /* case_exprlist */
92033{
92034sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
92035}
92036      break;
92037    case 193: /* fullname */
92038    case 198: /* from */
92039    case 206: /* seltablist */
92040    case 207: /* stl_prefix */
92041{
92042sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
92043}
92044      break;
92045    case 199: /* where_opt */
92046    case 201: /* having_opt */
92047    case 210: /* on_opt */
92048    case 215: /* sortitem */
92049    case 226: /* case_operand */
92050    case 228: /* case_else */
92051    case 239: /* when_clause */
92052    case 244: /* key_opt */
92053{
92054sqlite3ExprDelete(pParse->db, (yypminor->yy132));
92055}
92056      break;
92057    case 211: /* using_opt */
92058    case 213: /* inscollist */
92059    case 219: /* inscollist_opt */
92060{
92061sqlite3IdListDelete(pParse->db, (yypminor->yy408));
92062}
92063      break;
92064    case 235: /* trigger_cmd_list */
92065    case 240: /* trigger_cmd */
92066{
92067sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
92068}
92069      break;
92070    case 237: /* trigger_event */
92071{
92072sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
92073}
92074      break;
92075    default:  break;   /* If no destructor action specified: do nothing */
92076  }
92077}
92078
92079/*
92080** Pop the parser's stack once.
92081**
92082** If there is a destructor routine associated with the token which
92083** is popped from the stack, then call it.
92084**
92085** Return the major token number for the symbol popped.
92086*/
92087static int yy_pop_parser_stack(yyParser *pParser){
92088  YYCODETYPE yymajor;
92089  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
92090
92091  /* There is no mechanism by which the parser stack can be popped below
92092  ** empty in SQLite.  */
92093  if( NEVER(pParser->yyidx<0) ) return 0;
92094#ifndef NDEBUG
92095  if( yyTraceFILE && pParser->yyidx>=0 ){
92096    fprintf(yyTraceFILE,"%sPopping %s\n",
92097      yyTracePrompt,
92098      yyTokenName[yytos->major]);
92099  }
92100#endif
92101  yymajor = yytos->major;
92102  yy_destructor(pParser, yymajor, &yytos->minor);
92103  pParser->yyidx--;
92104  return yymajor;
92105}
92106
92107/*
92108** Deallocate and destroy a parser.  Destructors are all called for
92109** all stack elements before shutting the parser down.
92110**
92111** Inputs:
92112** <ul>
92113** <li>  A pointer to the parser.  This should be a pointer
92114**       obtained from sqlite3ParserAlloc.
92115** <li>  A pointer to a function used to reclaim memory obtained
92116**       from malloc.
92117** </ul>
92118*/
92119SQLITE_PRIVATE void sqlite3ParserFree(
92120  void *p,                    /* The parser to be deleted */
92121  void (*freeProc)(void*)     /* Function used to reclaim memory */
92122){
92123  yyParser *pParser = (yyParser*)p;
92124  /* In SQLite, we never try to destroy a parser that was not successfully
92125  ** created in the first place. */
92126  if( NEVER(pParser==0) ) return;
92127  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
92128#if YYSTACKDEPTH<=0
92129  free(pParser->yystack);
92130#endif
92131  (*freeProc)((void*)pParser);
92132}
92133
92134/*
92135** Return the peak depth of the stack for a parser.
92136*/
92137#ifdef YYTRACKMAXSTACKDEPTH
92138SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
92139  yyParser *pParser = (yyParser*)p;
92140  return pParser->yyidxMax;
92141}
92142#endif
92143
92144/*
92145** Find the appropriate action for a parser given the terminal
92146** look-ahead token iLookAhead.
92147**
92148** If the look-ahead token is YYNOCODE, then check to see if the action is
92149** independent of the look-ahead.  If it is, return the action, otherwise
92150** return YY_NO_ACTION.
92151*/
92152static int yy_find_shift_action(
92153  yyParser *pParser,        /* The parser */
92154  YYCODETYPE iLookAhead     /* The look-ahead token */
92155){
92156  int i;
92157  int stateno = pParser->yystack[pParser->yyidx].stateno;
92158
92159  if( stateno>YY_SHIFT_COUNT
92160   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
92161    return yy_default[stateno];
92162  }
92163  assert( iLookAhead!=YYNOCODE );
92164  i += iLookAhead;
92165  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
92166    if( iLookAhead>0 ){
92167#ifdef YYFALLBACK
92168      YYCODETYPE iFallback;            /* Fallback token */
92169      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
92170             && (iFallback = yyFallback[iLookAhead])!=0 ){
92171#ifndef NDEBUG
92172        if( yyTraceFILE ){
92173          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
92174             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
92175        }
92176#endif
92177        return yy_find_shift_action(pParser, iFallback);
92178      }
92179#endif
92180#ifdef YYWILDCARD
92181      {
92182        int j = i - iLookAhead + YYWILDCARD;
92183        if(
92184#if YY_SHIFT_MIN+YYWILDCARD<0
92185          j>=0 &&
92186#endif
92187#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
92188          j<YY_ACTTAB_COUNT &&
92189#endif
92190          yy_lookahead[j]==YYWILDCARD
92191        ){
92192#ifndef NDEBUG
92193          if( yyTraceFILE ){
92194            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
92195               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
92196          }
92197#endif /* NDEBUG */
92198          return yy_action[j];
92199        }
92200      }
92201#endif /* YYWILDCARD */
92202    }
92203    return yy_default[stateno];
92204  }else{
92205    return yy_action[i];
92206  }
92207}
92208
92209/*
92210** Find the appropriate action for a parser given the non-terminal
92211** look-ahead token iLookAhead.
92212**
92213** If the look-ahead token is YYNOCODE, then check to see if the action is
92214** independent of the look-ahead.  If it is, return the action, otherwise
92215** return YY_NO_ACTION.
92216*/
92217static int yy_find_reduce_action(
92218  int stateno,              /* Current state number */
92219  YYCODETYPE iLookAhead     /* The look-ahead token */
92220){
92221  int i;
92222#ifdef YYERRORSYMBOL
92223  if( stateno>YY_REDUCE_COUNT ){
92224    return yy_default[stateno];
92225  }
92226#else
92227  assert( stateno<=YY_REDUCE_COUNT );
92228#endif
92229  i = yy_reduce_ofst[stateno];
92230  assert( i!=YY_REDUCE_USE_DFLT );
92231  assert( iLookAhead!=YYNOCODE );
92232  i += iLookAhead;
92233#ifdef YYERRORSYMBOL
92234  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
92235    return yy_default[stateno];
92236  }
92237#else
92238  assert( i>=0 && i<YY_ACTTAB_COUNT );
92239  assert( yy_lookahead[i]==iLookAhead );
92240#endif
92241  return yy_action[i];
92242}
92243
92244/*
92245** The following routine is called if the stack overflows.
92246*/
92247static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
92248   sqlite3ParserARG_FETCH;
92249   yypParser->yyidx--;
92250#ifndef NDEBUG
92251   if( yyTraceFILE ){
92252     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
92253   }
92254#endif
92255   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
92256   /* Here code is inserted which will execute if the parser
92257   ** stack every overflows */
92258
92259  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
92260  sqlite3ErrorMsg(pParse, "parser stack overflow");
92261  pParse->parseError = 1;
92262   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
92263}
92264
92265/*
92266** Perform a shift action.
92267*/
92268static void yy_shift(
92269  yyParser *yypParser,          /* The parser to be shifted */
92270  int yyNewState,               /* The new state to shift in */
92271  int yyMajor,                  /* The major token to shift in */
92272  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
92273){
92274  yyStackEntry *yytos;
92275  yypParser->yyidx++;
92276#ifdef YYTRACKMAXSTACKDEPTH
92277  if( yypParser->yyidx>yypParser->yyidxMax ){
92278    yypParser->yyidxMax = yypParser->yyidx;
92279  }
92280#endif
92281#if YYSTACKDEPTH>0
92282  if( yypParser->yyidx>=YYSTACKDEPTH ){
92283    yyStackOverflow(yypParser, yypMinor);
92284    return;
92285  }
92286#else
92287  if( yypParser->yyidx>=yypParser->yystksz ){
92288    yyGrowStack(yypParser);
92289    if( yypParser->yyidx>=yypParser->yystksz ){
92290      yyStackOverflow(yypParser, yypMinor);
92291      return;
92292    }
92293  }
92294#endif
92295  yytos = &yypParser->yystack[yypParser->yyidx];
92296  yytos->stateno = (YYACTIONTYPE)yyNewState;
92297  yytos->major = (YYCODETYPE)yyMajor;
92298  yytos->minor = *yypMinor;
92299#ifndef NDEBUG
92300  if( yyTraceFILE && yypParser->yyidx>0 ){
92301    int i;
92302    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
92303    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
92304    for(i=1; i<=yypParser->yyidx; i++)
92305      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
92306    fprintf(yyTraceFILE,"\n");
92307  }
92308#endif
92309}
92310
92311/* The following table contains information about every rule that
92312** is used during the reduce.
92313*/
92314static const struct {
92315  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
92316  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
92317} yyRuleInfo[] = {
92318  { 142, 1 },
92319  { 143, 2 },
92320  { 143, 1 },
92321  { 144, 1 },
92322  { 144, 3 },
92323  { 145, 0 },
92324  { 145, 1 },
92325  { 145, 3 },
92326  { 146, 1 },
92327  { 147, 3 },
92328  { 149, 0 },
92329  { 149, 1 },
92330  { 149, 2 },
92331  { 148, 0 },
92332  { 148, 1 },
92333  { 148, 1 },
92334  { 148, 1 },
92335  { 147, 2 },
92336  { 147, 2 },
92337  { 147, 2 },
92338  { 151, 1 },
92339  { 151, 0 },
92340  { 147, 2 },
92341  { 147, 3 },
92342  { 147, 5 },
92343  { 147, 2 },
92344  { 152, 6 },
92345  { 154, 1 },
92346  { 156, 0 },
92347  { 156, 3 },
92348  { 155, 1 },
92349  { 155, 0 },
92350  { 153, 4 },
92351  { 153, 2 },
92352  { 158, 3 },
92353  { 158, 1 },
92354  { 161, 3 },
92355  { 162, 1 },
92356  { 165, 1 },
92357  { 165, 1 },
92358  { 166, 1 },
92359  { 150, 1 },
92360  { 150, 1 },
92361  { 150, 1 },
92362  { 163, 0 },
92363  { 163, 1 },
92364  { 167, 1 },
92365  { 167, 4 },
92366  { 167, 6 },
92367  { 168, 1 },
92368  { 168, 2 },
92369  { 169, 1 },
92370  { 169, 1 },
92371  { 164, 2 },
92372  { 164, 0 },
92373  { 172, 3 },
92374  { 172, 1 },
92375  { 173, 2 },
92376  { 173, 4 },
92377  { 173, 3 },
92378  { 173, 3 },
92379  { 173, 2 },
92380  { 173, 2 },
92381  { 173, 3 },
92382  { 173, 5 },
92383  { 173, 2 },
92384  { 173, 4 },
92385  { 173, 4 },
92386  { 173, 1 },
92387  { 173, 2 },
92388  { 178, 0 },
92389  { 178, 1 },
92390  { 180, 0 },
92391  { 180, 2 },
92392  { 182, 2 },
92393  { 182, 3 },
92394  { 182, 3 },
92395  { 182, 3 },
92396  { 183, 2 },
92397  { 183, 2 },
92398  { 183, 1 },
92399  { 183, 1 },
92400  { 183, 2 },
92401  { 181, 3 },
92402  { 181, 2 },
92403  { 184, 0 },
92404  { 184, 2 },
92405  { 184, 2 },
92406  { 159, 0 },
92407  { 159, 2 },
92408  { 185, 3 },
92409  { 185, 2 },
92410  { 185, 1 },
92411  { 186, 2 },
92412  { 186, 7 },
92413  { 186, 5 },
92414  { 186, 5 },
92415  { 186, 10 },
92416  { 188, 0 },
92417  { 188, 1 },
92418  { 176, 0 },
92419  { 176, 3 },
92420  { 189, 0 },
92421  { 189, 2 },
92422  { 190, 1 },
92423  { 190, 1 },
92424  { 190, 1 },
92425  { 147, 4 },
92426  { 192, 2 },
92427  { 192, 0 },
92428  { 147, 8 },
92429  { 147, 4 },
92430  { 147, 1 },
92431  { 160, 1 },
92432  { 160, 3 },
92433  { 195, 1 },
92434  { 195, 2 },
92435  { 195, 1 },
92436  { 194, 9 },
92437  { 196, 1 },
92438  { 196, 1 },
92439  { 196, 0 },
92440  { 204, 2 },
92441  { 204, 0 },
92442  { 197, 3 },
92443  { 197, 2 },
92444  { 197, 4 },
92445  { 205, 2 },
92446  { 205, 1 },
92447  { 205, 0 },
92448  { 198, 0 },
92449  { 198, 2 },
92450  { 207, 2 },
92451  { 207, 0 },
92452  { 206, 7 },
92453  { 206, 7 },
92454  { 206, 7 },
92455  { 157, 0 },
92456  { 157, 2 },
92457  { 193, 2 },
92458  { 208, 1 },
92459  { 208, 2 },
92460  { 208, 3 },
92461  { 208, 4 },
92462  { 210, 2 },
92463  { 210, 0 },
92464  { 209, 0 },
92465  { 209, 3 },
92466  { 209, 2 },
92467  { 211, 4 },
92468  { 211, 0 },
92469  { 202, 0 },
92470  { 202, 3 },
92471  { 214, 4 },
92472  { 214, 2 },
92473  { 215, 1 },
92474  { 177, 1 },
92475  { 177, 1 },
92476  { 177, 0 },
92477  { 200, 0 },
92478  { 200, 3 },
92479  { 201, 0 },
92480  { 201, 2 },
92481  { 203, 0 },
92482  { 203, 2 },
92483  { 203, 4 },
92484  { 203, 4 },
92485  { 147, 5 },
92486  { 199, 0 },
92487  { 199, 2 },
92488  { 147, 7 },
92489  { 217, 5 },
92490  { 217, 3 },
92491  { 147, 8 },
92492  { 147, 5 },
92493  { 147, 6 },
92494  { 218, 2 },
92495  { 218, 1 },
92496  { 220, 3 },
92497  { 220, 1 },
92498  { 219, 0 },
92499  { 219, 3 },
92500  { 213, 3 },
92501  { 213, 1 },
92502  { 175, 1 },
92503  { 175, 3 },
92504  { 174, 1 },
92505  { 175, 1 },
92506  { 175, 1 },
92507  { 175, 3 },
92508  { 175, 5 },
92509  { 174, 1 },
92510  { 174, 1 },
92511  { 175, 1 },
92512  { 175, 1 },
92513  { 175, 3 },
92514  { 175, 6 },
92515  { 175, 5 },
92516  { 175, 4 },
92517  { 174, 1 },
92518  { 175, 3 },
92519  { 175, 3 },
92520  { 175, 3 },
92521  { 175, 3 },
92522  { 175, 3 },
92523  { 175, 3 },
92524  { 175, 3 },
92525  { 175, 3 },
92526  { 222, 1 },
92527  { 222, 2 },
92528  { 222, 1 },
92529  { 222, 2 },
92530  { 223, 2 },
92531  { 223, 0 },
92532  { 175, 4 },
92533  { 175, 2 },
92534  { 175, 3 },
92535  { 175, 3 },
92536  { 175, 4 },
92537  { 175, 2 },
92538  { 175, 2 },
92539  { 175, 2 },
92540  { 175, 2 },
92541  { 224, 1 },
92542  { 224, 2 },
92543  { 175, 5 },
92544  { 225, 1 },
92545  { 225, 2 },
92546  { 175, 5 },
92547  { 175, 3 },
92548  { 175, 5 },
92549  { 175, 4 },
92550  { 175, 4 },
92551  { 175, 5 },
92552  { 227, 5 },
92553  { 227, 4 },
92554  { 228, 2 },
92555  { 228, 0 },
92556  { 226, 1 },
92557  { 226, 0 },
92558  { 221, 1 },
92559  { 221, 0 },
92560  { 216, 3 },
92561  { 216, 1 },
92562  { 147, 11 },
92563  { 229, 1 },
92564  { 229, 0 },
92565  { 179, 0 },
92566  { 179, 3 },
92567  { 187, 5 },
92568  { 187, 3 },
92569  { 230, 0 },
92570  { 230, 2 },
92571  { 147, 4 },
92572  { 147, 1 },
92573  { 147, 2 },
92574  { 147, 3 },
92575  { 147, 5 },
92576  { 147, 6 },
92577  { 147, 5 },
92578  { 147, 6 },
92579  { 231, 1 },
92580  { 231, 1 },
92581  { 231, 1 },
92582  { 231, 1 },
92583  { 231, 1 },
92584  { 170, 2 },
92585  { 171, 2 },
92586  { 233, 1 },
92587  { 232, 1 },
92588  { 232, 0 },
92589  { 147, 5 },
92590  { 234, 11 },
92591  { 236, 1 },
92592  { 236, 1 },
92593  { 236, 2 },
92594  { 236, 0 },
92595  { 237, 1 },
92596  { 237, 1 },
92597  { 237, 3 },
92598  { 238, 0 },
92599  { 238, 3 },
92600  { 239, 0 },
92601  { 239, 2 },
92602  { 235, 3 },
92603  { 235, 2 },
92604  { 241, 1 },
92605  { 241, 3 },
92606  { 242, 0 },
92607  { 242, 3 },
92608  { 242, 2 },
92609  { 240, 7 },
92610  { 240, 8 },
92611  { 240, 5 },
92612  { 240, 5 },
92613  { 240, 1 },
92614  { 175, 4 },
92615  { 175, 6 },
92616  { 191, 1 },
92617  { 191, 1 },
92618  { 191, 1 },
92619  { 147, 4 },
92620  { 147, 6 },
92621  { 147, 3 },
92622  { 244, 0 },
92623  { 244, 2 },
92624  { 243, 1 },
92625  { 243, 0 },
92626  { 147, 1 },
92627  { 147, 3 },
92628  { 147, 1 },
92629  { 147, 3 },
92630  { 147, 6 },
92631  { 147, 6 },
92632  { 245, 1 },
92633  { 246, 0 },
92634  { 246, 1 },
92635  { 147, 1 },
92636  { 147, 4 },
92637  { 247, 7 },
92638  { 248, 1 },
92639  { 248, 3 },
92640  { 249, 0 },
92641  { 249, 2 },
92642  { 250, 1 },
92643  { 250, 3 },
92644  { 251, 1 },
92645  { 252, 0 },
92646  { 252, 4 },
92647  { 252, 2 },
92648};
92649
92650static void yy_accept(yyParser*);  /* Forward Declaration */
92651
92652/*
92653** Perform a reduce action and the shift that must immediately
92654** follow the reduce.
92655*/
92656static void yy_reduce(
92657  yyParser *yypParser,         /* The parser */
92658  int yyruleno                 /* Number of the rule by which to reduce */
92659){
92660  int yygoto;                     /* The next state */
92661  int yyact;                      /* The next action */
92662  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
92663  yyStackEntry *yymsp;            /* The top of the parser's stack */
92664  int yysize;                     /* Amount to pop the stack */
92665  sqlite3ParserARG_FETCH;
92666  yymsp = &yypParser->yystack[yypParser->yyidx];
92667#ifndef NDEBUG
92668  if( yyTraceFILE && yyruleno>=0
92669        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
92670    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
92671      yyRuleName[yyruleno]);
92672  }
92673#endif /* NDEBUG */
92674
92675  /* Silence complaints from purify about yygotominor being uninitialized
92676  ** in some cases when it is copied into the stack after the following
92677  ** switch.  yygotominor is uninitialized when a rule reduces that does
92678  ** not set the value of its left-hand side nonterminal.  Leaving the
92679  ** value of the nonterminal uninitialized is utterly harmless as long
92680  ** as the value is never used.  So really the only thing this code
92681  ** accomplishes is to quieten purify.
92682  **
92683  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
92684  ** without this code, their parser segfaults.  I'm not sure what there
92685  ** parser is doing to make this happen.  This is the second bug report
92686  ** from wireshark this week.  Clearly they are stressing Lemon in ways
92687  ** that it has not been previously stressed...  (SQLite ticket #2172)
92688  */
92689  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
92690  yygotominor = yyzerominor;
92691
92692
92693  switch( yyruleno ){
92694  /* Beginning here are the reduction cases.  A typical example
92695  ** follows:
92696  **   case 0:
92697  **  #line <lineno> <grammarfile>
92698  **     { ... }           // User supplied code
92699  **  #line <lineno> <thisfile>
92700  **     break;
92701  */
92702      case 5: /* explain ::= */
92703{ sqlite3BeginParse(pParse, 0); }
92704        break;
92705      case 6: /* explain ::= EXPLAIN */
92706{ sqlite3BeginParse(pParse, 1); }
92707        break;
92708      case 7: /* explain ::= EXPLAIN QUERY PLAN */
92709{ sqlite3BeginParse(pParse, 2); }
92710        break;
92711      case 8: /* cmdx ::= cmd */
92712{ sqlite3FinishCoding(pParse); }
92713        break;
92714      case 9: /* cmd ::= BEGIN transtype trans_opt */
92715{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
92716        break;
92717      case 13: /* transtype ::= */
92718{yygotominor.yy328 = TK_DEFERRED;}
92719        break;
92720      case 14: /* transtype ::= DEFERRED */
92721      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
92722      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
92723      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
92724      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
92725{yygotominor.yy328 = yymsp[0].major;}
92726        break;
92727      case 17: /* cmd ::= COMMIT trans_opt */
92728      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
92729{sqlite3CommitTransaction(pParse);}
92730        break;
92731      case 19: /* cmd ::= ROLLBACK trans_opt */
92732{sqlite3RollbackTransaction(pParse);}
92733        break;
92734      case 22: /* cmd ::= SAVEPOINT nm */
92735{
92736  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
92737}
92738        break;
92739      case 23: /* cmd ::= RELEASE savepoint_opt nm */
92740{
92741  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
92742}
92743        break;
92744      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
92745{
92746  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
92747}
92748        break;
92749      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
92750{
92751   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
92752}
92753        break;
92754      case 27: /* createkw ::= CREATE */
92755{
92756  pParse->db->lookaside.bEnabled = 0;
92757  yygotominor.yy0 = yymsp[0].minor.yy0;
92758}
92759        break;
92760      case 28: /* ifnotexists ::= */
92761      case 31: /* temp ::= */ yytestcase(yyruleno==31);
92762      case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
92763      case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
92764      case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
92765      case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
92766      case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
92767      case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
92768      case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
92769      case 121: /* distinct ::= */ yytestcase(yyruleno==121);
92770      case 223: /* between_op ::= BETWEEN */ yytestcase(yyruleno==223);
92771      case 226: /* in_op ::= IN */ yytestcase(yyruleno==226);
92772{yygotominor.yy328 = 0;}
92773        break;
92774      case 29: /* ifnotexists ::= IF NOT EXISTS */
92775      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
92776      case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
92777      case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
92778      case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
92779      case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
92780      case 224: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==224);
92781      case 227: /* in_op ::= NOT IN */ yytestcase(yyruleno==227);
92782{yygotominor.yy328 = 1;}
92783        break;
92784      case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
92785{
92786  sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
92787}
92788        break;
92789      case 33: /* create_table_args ::= AS select */
92790{
92791  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy3);
92792  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
92793}
92794        break;
92795      case 36: /* column ::= columnid type carglist */
92796{
92797  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
92798  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
92799}
92800        break;
92801      case 37: /* columnid ::= nm */
92802{
92803  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
92804  yygotominor.yy0 = yymsp[0].minor.yy0;
92805}
92806        break;
92807      case 38: /* id ::= ID */
92808      case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
92809      case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
92810      case 41: /* nm ::= id */ yytestcase(yyruleno==41);
92811      case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
92812      case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
92813      case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
92814      case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
92815      case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
92816      case 128: /* as ::= ids */ yytestcase(yyruleno==128);
92817      case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
92818      case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
92819      case 252: /* collate ::= COLLATE ids */ yytestcase(yyruleno==252);
92820      case 261: /* nmnum ::= plus_num */ yytestcase(yyruleno==261);
92821      case 262: /* nmnum ::= nm */ yytestcase(yyruleno==262);
92822      case 263: /* nmnum ::= ON */ yytestcase(yyruleno==263);
92823      case 264: /* nmnum ::= DELETE */ yytestcase(yyruleno==264);
92824      case 265: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==265);
92825      case 266: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==266);
92826      case 267: /* minus_num ::= MINUS number */ yytestcase(yyruleno==267);
92827      case 268: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==268);
92828      case 286: /* trnm ::= nm */ yytestcase(yyruleno==286);
92829{yygotominor.yy0 = yymsp[0].minor.yy0;}
92830        break;
92831      case 45: /* type ::= typetoken */
92832{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
92833        break;
92834      case 47: /* typetoken ::= typename LP signed RP */
92835{
92836  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
92837  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
92838}
92839        break;
92840      case 48: /* typetoken ::= typename LP signed COMMA signed RP */
92841{
92842  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
92843  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
92844}
92845        break;
92846      case 50: /* typename ::= typename ids */
92847{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);}
92848        break;
92849      case 57: /* ccons ::= DEFAULT term */
92850      case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
92851{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
92852        break;
92853      case 58: /* ccons ::= DEFAULT LP expr RP */
92854{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
92855        break;
92856      case 60: /* ccons ::= DEFAULT MINUS term */
92857{
92858  ExprSpan v;
92859  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
92860  v.zStart = yymsp[-1].minor.yy0.z;
92861  v.zEnd = yymsp[0].minor.yy346.zEnd;
92862  sqlite3AddDefaultValue(pParse,&v);
92863}
92864        break;
92865      case 61: /* ccons ::= DEFAULT id */
92866{
92867  ExprSpan v;
92868  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
92869  sqlite3AddDefaultValue(pParse,&v);
92870}
92871        break;
92872      case 63: /* ccons ::= NOT NULL onconf */
92873{sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
92874        break;
92875      case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
92876{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
92877        break;
92878      case 65: /* ccons ::= UNIQUE onconf */
92879{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
92880        break;
92881      case 66: /* ccons ::= CHECK LP expr RP */
92882{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
92883        break;
92884      case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
92885{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
92886        break;
92887      case 68: /* ccons ::= defer_subclause */
92888{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
92889        break;
92890      case 69: /* ccons ::= COLLATE ids */
92891{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
92892        break;
92893      case 72: /* refargs ::= */
92894{ yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
92895        break;
92896      case 73: /* refargs ::= refargs refarg */
92897{ yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
92898        break;
92899      case 74: /* refarg ::= MATCH nm */
92900      case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
92901{ yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
92902        break;
92903      case 76: /* refarg ::= ON DELETE refact */
92904{ yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
92905        break;
92906      case 77: /* refarg ::= ON UPDATE refact */
92907{ yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
92908        break;
92909      case 78: /* refact ::= SET NULL */
92910{ yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
92911        break;
92912      case 79: /* refact ::= SET DEFAULT */
92913{ yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
92914        break;
92915      case 80: /* refact ::= CASCADE */
92916{ yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
92917        break;
92918      case 81: /* refact ::= RESTRICT */
92919{ yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
92920        break;
92921      case 82: /* refact ::= NO ACTION */
92922{ yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
92923        break;
92924      case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
92925      case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
92926      case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
92927      case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
92928{yygotominor.yy328 = yymsp[0].minor.yy328;}
92929        break;
92930      case 88: /* conslist_opt ::= */
92931{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
92932        break;
92933      case 89: /* conslist_opt ::= COMMA conslist */
92934{yygotominor.yy0 = yymsp[-1].minor.yy0;}
92935        break;
92936      case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
92937{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
92938        break;
92939      case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
92940{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
92941        break;
92942      case 96: /* tcons ::= CHECK LP expr RP onconf */
92943{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
92944        break;
92945      case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
92946{
92947    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
92948    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
92949}
92950        break;
92951      case 100: /* onconf ::= */
92952{yygotominor.yy328 = OE_Default;}
92953        break;
92954      case 102: /* orconf ::= */
92955{yygotominor.yy186 = OE_Default;}
92956        break;
92957      case 103: /* orconf ::= OR resolvetype */
92958{yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
92959        break;
92960      case 105: /* resolvetype ::= IGNORE */
92961{yygotominor.yy328 = OE_Ignore;}
92962        break;
92963      case 106: /* resolvetype ::= REPLACE */
92964{yygotominor.yy328 = OE_Replace;}
92965        break;
92966      case 107: /* cmd ::= DROP TABLE ifexists fullname */
92967{
92968  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
92969}
92970        break;
92971      case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
92972{
92973  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);
92974}
92975        break;
92976      case 111: /* cmd ::= DROP VIEW ifexists fullname */
92977{
92978  sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
92979}
92980        break;
92981      case 112: /* cmd ::= select */
92982{
92983  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
92984  sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
92985  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
92986}
92987        break;
92988      case 113: /* select ::= oneselect */
92989{yygotominor.yy3 = yymsp[0].minor.yy3;}
92990        break;
92991      case 114: /* select ::= select multiselect_op oneselect */
92992{
92993  if( yymsp[0].minor.yy3 ){
92994    yymsp[0].minor.yy3->op = (u8)yymsp[-1].minor.yy328;
92995    yymsp[0].minor.yy3->pPrior = yymsp[-2].minor.yy3;
92996  }else{
92997    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
92998  }
92999  yygotominor.yy3 = yymsp[0].minor.yy3;
93000}
93001        break;
93002      case 116: /* multiselect_op ::= UNION ALL */
93003{yygotominor.yy328 = TK_ALL;}
93004        break;
93005      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
93006{
93007  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);
93008}
93009        break;
93010      case 122: /* sclp ::= selcollist COMMA */
93011      case 248: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==248);
93012{yygotominor.yy14 = yymsp[-1].minor.yy14;}
93013        break;
93014      case 123: /* sclp ::= */
93015      case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
93016      case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
93017      case 241: /* exprlist ::= */ yytestcase(yyruleno==241);
93018      case 247: /* idxlist_opt ::= */ yytestcase(yyruleno==247);
93019{yygotominor.yy14 = 0;}
93020        break;
93021      case 124: /* selcollist ::= sclp expr as */
93022{
93023   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
93024   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
93025   sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
93026}
93027        break;
93028      case 125: /* selcollist ::= sclp STAR */
93029{
93030  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
93031  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
93032}
93033        break;
93034      case 126: /* selcollist ::= sclp nm DOT STAR */
93035{
93036  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
93037  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93038  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
93039  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
93040}
93041        break;
93042      case 129: /* as ::= */
93043{yygotominor.yy0.n = 0;}
93044        break;
93045      case 130: /* from ::= */
93046{yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
93047        break;
93048      case 131: /* from ::= FROM seltablist */
93049{
93050  yygotominor.yy65 = yymsp[0].minor.yy65;
93051  sqlite3SrcListShiftJoinType(yygotominor.yy65);
93052}
93053        break;
93054      case 132: /* stl_prefix ::= seltablist joinop */
93055{
93056   yygotominor.yy65 = yymsp[-1].minor.yy65;
93057   if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
93058}
93059        break;
93060      case 133: /* stl_prefix ::= */
93061{yygotominor.yy65 = 0;}
93062        break;
93063      case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
93064{
93065  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);
93066  sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
93067}
93068        break;
93069      case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
93070{
93071    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);
93072  }
93073        break;
93074      case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
93075{
93076    if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
93077      yygotominor.yy65 = yymsp[-4].minor.yy65;
93078    }else{
93079      Select *pSubquery;
93080      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
93081      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,0,0,0);
93082      yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
93083    }
93084  }
93085        break;
93086      case 137: /* dbnm ::= */
93087      case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
93088{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
93089        break;
93090      case 139: /* fullname ::= nm dbnm */
93091{yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
93092        break;
93093      case 140: /* joinop ::= COMMA|JOIN */
93094{ yygotominor.yy328 = JT_INNER; }
93095        break;
93096      case 141: /* joinop ::= JOIN_KW JOIN */
93097{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
93098        break;
93099      case 142: /* joinop ::= JOIN_KW nm JOIN */
93100{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
93101        break;
93102      case 143: /* joinop ::= JOIN_KW nm nm JOIN */
93103{ yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
93104        break;
93105      case 144: /* on_opt ::= ON expr */
93106      case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
93107      case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
93108      case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
93109      case 236: /* case_else ::= ELSE expr */ yytestcase(yyruleno==236);
93110      case 238: /* case_operand ::= expr */ yytestcase(yyruleno==238);
93111{yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
93112        break;
93113      case 145: /* on_opt ::= */
93114      case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
93115      case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
93116      case 237: /* case_else ::= */ yytestcase(yyruleno==237);
93117      case 239: /* case_operand ::= */ yytestcase(yyruleno==239);
93118{yygotominor.yy132 = 0;}
93119        break;
93120      case 148: /* indexed_opt ::= NOT INDEXED */
93121{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
93122        break;
93123      case 149: /* using_opt ::= USING LP inscollist RP */
93124      case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
93125{yygotominor.yy408 = yymsp[-1].minor.yy408;}
93126        break;
93127      case 150: /* using_opt ::= */
93128      case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
93129{yygotominor.yy408 = 0;}
93130        break;
93131      case 152: /* orderby_opt ::= ORDER BY sortlist */
93132      case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
93133      case 240: /* exprlist ::= nexprlist */ yytestcase(yyruleno==240);
93134{yygotominor.yy14 = yymsp[0].minor.yy14;}
93135        break;
93136      case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
93137{
93138  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy132);
93139  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93140}
93141        break;
93142      case 154: /* sortlist ::= sortitem sortorder */
93143{
93144  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy132);
93145  if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
93146}
93147        break;
93148      case 156: /* sortorder ::= ASC */
93149      case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
93150{yygotominor.yy328 = SQLITE_SO_ASC;}
93151        break;
93152      case 157: /* sortorder ::= DESC */
93153{yygotominor.yy328 = SQLITE_SO_DESC;}
93154        break;
93155      case 163: /* limit_opt ::= */
93156{yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
93157        break;
93158      case 164: /* limit_opt ::= LIMIT expr */
93159{yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
93160        break;
93161      case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
93162{yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
93163        break;
93164      case 166: /* limit_opt ::= LIMIT expr COMMA expr */
93165{yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
93166        break;
93167      case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
93168{
93169  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
93170  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
93171}
93172        break;
93173      case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
93174{
93175  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
93176  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
93177  sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
93178}
93179        break;
93180      case 171: /* setlist ::= setlist COMMA nm EQ expr */
93181{
93182  yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
93183  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93184}
93185        break;
93186      case 172: /* setlist ::= nm EQ expr */
93187{
93188  yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
93189  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93190}
93191        break;
93192      case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
93193{sqlite3Insert(pParse, yymsp[-5].minor.yy65, yymsp[-1].minor.yy14, 0, yymsp[-4].minor.yy408, yymsp[-7].minor.yy186);}
93194        break;
93195      case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
93196{sqlite3Insert(pParse, yymsp[-2].minor.yy65, 0, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);}
93197        break;
93198      case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
93199{sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);}
93200        break;
93201      case 176: /* insert_cmd ::= INSERT orconf */
93202{yygotominor.yy186 = yymsp[0].minor.yy186;}
93203        break;
93204      case 177: /* insert_cmd ::= REPLACE */
93205{yygotominor.yy186 = OE_Replace;}
93206        break;
93207      case 178: /* itemlist ::= itemlist COMMA expr */
93208      case 242: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==242);
93209{yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
93210        break;
93211      case 179: /* itemlist ::= expr */
93212      case 243: /* nexprlist ::= expr */ yytestcase(yyruleno==243);
93213{yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
93214        break;
93215      case 182: /* inscollist ::= inscollist COMMA nm */
93216{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
93217        break;
93218      case 183: /* inscollist ::= nm */
93219{yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
93220        break;
93221      case 184: /* expr ::= term */
93222      case 212: /* escape ::= ESCAPE expr */ yytestcase(yyruleno==212);
93223{yygotominor.yy346 = yymsp[0].minor.yy346;}
93224        break;
93225      case 185: /* expr ::= LP expr RP */
93226{yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
93227        break;
93228      case 186: /* term ::= NULL */
93229      case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
93230      case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
93231{spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
93232        break;
93233      case 187: /* expr ::= id */
93234      case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
93235{spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
93236        break;
93237      case 189: /* expr ::= nm DOT nm */
93238{
93239  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93240  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
93241  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
93242  spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
93243}
93244        break;
93245      case 190: /* expr ::= nm DOT nm DOT nm */
93246{
93247  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
93248  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
93249  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
93250  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
93251  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
93252  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
93253}
93254        break;
93255      case 193: /* expr ::= REGISTER */
93256{
93257  /* When doing a nested parse, one can include terms in an expression
93258  ** that look like this:   #1 #2 ...  These terms refer to registers
93259  ** in the virtual machine.  #N is the N-th register. */
93260  if( pParse->nested==0 ){
93261    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
93262    yygotominor.yy346.pExpr = 0;
93263  }else{
93264    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
93265    if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
93266  }
93267  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93268}
93269        break;
93270      case 194: /* expr ::= VARIABLE */
93271{
93272  spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
93273  sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
93274  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93275}
93276        break;
93277      case 195: /* expr ::= expr COLLATE ids */
93278{
93279  yygotominor.yy346.pExpr = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
93280  yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
93281  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93282}
93283        break;
93284      case 196: /* expr ::= CAST LP expr AS typetoken RP */
93285{
93286  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
93287  spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
93288}
93289        break;
93290      case 197: /* expr ::= ID LP distinct exprlist RP */
93291{
93292  if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
93293    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
93294  }
93295  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
93296  spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
93297  if( yymsp[-2].minor.yy328 && yygotominor.yy346.pExpr ){
93298    yygotominor.yy346.pExpr->flags |= EP_Distinct;
93299  }
93300}
93301        break;
93302      case 198: /* expr ::= ID LP STAR RP */
93303{
93304  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
93305  spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
93306}
93307        break;
93308      case 199: /* term ::= CTIME_KW */
93309{
93310  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
93311  ** treated as functions that return constants */
93312  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
93313  if( yygotominor.yy346.pExpr ){
93314    yygotominor.yy346.pExpr->op = TK_CONST_FUNC;
93315  }
93316  spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
93317}
93318        break;
93319      case 200: /* expr ::= expr AND expr */
93320      case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
93321      case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
93322      case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
93323      case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
93324      case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
93325      case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
93326      case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
93327{spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
93328        break;
93329      case 208: /* likeop ::= LIKE_KW */
93330      case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
93331{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 0;}
93332        break;
93333      case 209: /* likeop ::= NOT LIKE_KW */
93334      case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
93335{yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 1;}
93336        break;
93337      case 213: /* escape ::= */
93338{memset(&yygotominor.yy346,0,sizeof(yygotominor.yy346));}
93339        break;
93340      case 214: /* expr ::= expr likeop expr escape */
93341{
93342  ExprList *pList;
93343  pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy346.pExpr);
93344  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy346.pExpr);
93345  if( yymsp[0].minor.yy346.pExpr ){
93346    pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
93347  }
93348  yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy96.eOperator);
93349  if( yymsp[-2].minor.yy96.not ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93350  yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
93351  yygotominor.yy346.zEnd = yymsp[-1].minor.yy346.zEnd;
93352  if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
93353}
93354        break;
93355      case 215: /* expr ::= expr ISNULL|NOTNULL */
93356{spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
93357        break;
93358      case 216: /* expr ::= expr NOT NULL */
93359{spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
93360        break;
93361      case 217: /* expr ::= expr IS expr */
93362{
93363  spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
93364  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
93365}
93366        break;
93367      case 218: /* expr ::= expr IS NOT expr */
93368{
93369  spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
93370  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
93371}
93372        break;
93373      case 219: /* expr ::= NOT expr */
93374      case 220: /* expr ::= BITNOT expr */ yytestcase(yyruleno==220);
93375{spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93376        break;
93377      case 221: /* expr ::= MINUS expr */
93378{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93379        break;
93380      case 222: /* expr ::= PLUS expr */
93381{spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
93382        break;
93383      case 225: /* expr ::= expr between_op expr AND expr */
93384{
93385  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
93386  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
93387  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93388  if( yygotominor.yy346.pExpr ){
93389    yygotominor.yy346.pExpr->x.pList = pList;
93390  }else{
93391    sqlite3ExprListDelete(pParse->db, pList);
93392  }
93393  if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93394  yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93395  yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
93396}
93397        break;
93398      case 228: /* expr ::= expr in_op LP exprlist RP */
93399{
93400    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93401    if( yygotominor.yy346.pExpr ){
93402      yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
93403      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93404    }else{
93405      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
93406    }
93407    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93408    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93409    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93410  }
93411        break;
93412      case 229: /* expr ::= LP select RP */
93413{
93414    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
93415    if( yygotominor.yy346.pExpr ){
93416      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
93417      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93418      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93419    }else{
93420      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93421    }
93422    yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
93423    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93424  }
93425        break;
93426      case 230: /* expr ::= expr in_op LP select RP */
93427{
93428    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
93429    if( yygotominor.yy346.pExpr ){
93430      yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
93431      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93432      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93433    }else{
93434      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93435    }
93436    if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93437    yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
93438    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93439  }
93440        break;
93441      case 231: /* expr ::= expr in_op nm dbnm */
93442{
93443    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
93444    yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
93445    if( yygotominor.yy346.pExpr ){
93446      yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
93447      ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
93448      sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93449    }else{
93450      sqlite3SrcListDelete(pParse->db, pSrc);
93451    }
93452    if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
93453    yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
93454    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];
93455  }
93456        break;
93457      case 232: /* expr ::= EXISTS LP select RP */
93458{
93459    Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
93460    if( p ){
93461      p->x.pSelect = yymsp[-1].minor.yy3;
93462      ExprSetProperty(p, EP_xIsSelect);
93463      sqlite3ExprSetHeight(pParse, p);
93464    }else{
93465      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
93466    }
93467    yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
93468    yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93469  }
93470        break;
93471      case 233: /* expr ::= CASE case_operand case_exprlist case_else END */
93472{
93473  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, yymsp[-1].minor.yy132, 0);
93474  if( yygotominor.yy346.pExpr ){
93475    yygotominor.yy346.pExpr->x.pList = yymsp[-2].minor.yy14;
93476    sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
93477  }else{
93478    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
93479  }
93480  yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
93481  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93482}
93483        break;
93484      case 234: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
93485{
93486  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
93487  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
93488}
93489        break;
93490      case 235: /* case_exprlist ::= WHEN expr THEN expr */
93491{
93492  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
93493  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
93494}
93495        break;
93496      case 244: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
93497{
93498  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
93499                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy14, yymsp[-9].minor.yy328,
93500                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy328);
93501}
93502        break;
93503      case 245: /* uniqueflag ::= UNIQUE */
93504      case 299: /* raisetype ::= ABORT */ yytestcase(yyruleno==299);
93505{yygotominor.yy328 = OE_Abort;}
93506        break;
93507      case 246: /* uniqueflag ::= */
93508{yygotominor.yy328 = OE_None;}
93509        break;
93510      case 249: /* idxlist ::= idxlist COMMA nm collate sortorder */
93511{
93512  Expr *p = 0;
93513  if( yymsp[-1].minor.yy0.n>0 ){
93514    p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
93515    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
93516  }
93517  yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
93518  sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
93519  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
93520  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93521}
93522        break;
93523      case 250: /* idxlist ::= nm collate sortorder */
93524{
93525  Expr *p = 0;
93526  if( yymsp[-1].minor.yy0.n>0 ){
93527    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
93528    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
93529  }
93530  yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
93531  sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
93532  sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
93533  if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
93534}
93535        break;
93536      case 251: /* collate ::= */
93537{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
93538        break;
93539      case 253: /* cmd ::= DROP INDEX ifexists fullname */
93540{sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
93541        break;
93542      case 254: /* cmd ::= VACUUM */
93543      case 255: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==255);
93544{sqlite3Vacuum(pParse);}
93545        break;
93546      case 256: /* cmd ::= PRAGMA nm dbnm */
93547{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
93548        break;
93549      case 257: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
93550{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
93551        break;
93552      case 258: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
93553{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
93554        break;
93555      case 259: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
93556{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
93557        break;
93558      case 260: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
93559{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
93560        break;
93561      case 271: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
93562{
93563  Token all;
93564  all.z = yymsp[-3].minor.yy0.z;
93565  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
93566  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
93567}
93568        break;
93569      case 272: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
93570{
93571  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);
93572  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
93573}
93574        break;
93575      case 273: /* trigger_time ::= BEFORE */
93576      case 276: /* trigger_time ::= */ yytestcase(yyruleno==276);
93577{ yygotominor.yy328 = TK_BEFORE; }
93578        break;
93579      case 274: /* trigger_time ::= AFTER */
93580{ yygotominor.yy328 = TK_AFTER;  }
93581        break;
93582      case 275: /* trigger_time ::= INSTEAD OF */
93583{ yygotominor.yy328 = TK_INSTEAD;}
93584        break;
93585      case 277: /* trigger_event ::= DELETE|INSERT */
93586      case 278: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==278);
93587{yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
93588        break;
93589      case 279: /* trigger_event ::= UPDATE OF inscollist */
93590{yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
93591        break;
93592      case 282: /* when_clause ::= */
93593      case 304: /* key_opt ::= */ yytestcase(yyruleno==304);
93594{ yygotominor.yy132 = 0; }
93595        break;
93596      case 283: /* when_clause ::= WHEN expr */
93597      case 305: /* key_opt ::= KEY expr */ yytestcase(yyruleno==305);
93598{ yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
93599        break;
93600      case 284: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
93601{
93602  assert( yymsp[-2].minor.yy473!=0 );
93603  yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
93604  yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
93605  yygotominor.yy473 = yymsp[-2].minor.yy473;
93606}
93607        break;
93608      case 285: /* trigger_cmd_list ::= trigger_cmd SEMI */
93609{
93610  assert( yymsp[-1].minor.yy473!=0 );
93611  yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
93612  yygotominor.yy473 = yymsp[-1].minor.yy473;
93613}
93614        break;
93615      case 287: /* trnm ::= nm DOT nm */
93616{
93617  yygotominor.yy0 = yymsp[0].minor.yy0;
93618  sqlite3ErrorMsg(pParse,
93619        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
93620        "statements within triggers");
93621}
93622        break;
93623      case 289: /* tridxby ::= INDEXED BY nm */
93624{
93625  sqlite3ErrorMsg(pParse,
93626        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
93627        "within triggers");
93628}
93629        break;
93630      case 290: /* tridxby ::= NOT INDEXED */
93631{
93632  sqlite3ErrorMsg(pParse,
93633        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
93634        "within triggers");
93635}
93636        break;
93637      case 291: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
93638{ yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
93639        break;
93640      case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
93641{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy408, yymsp[-1].minor.yy14, 0, yymsp[-7].minor.yy186);}
93642        break;
93643      case 293: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
93644{yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, 0, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
93645        break;
93646      case 294: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
93647{yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
93648        break;
93649      case 295: /* trigger_cmd ::= select */
93650{yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
93651        break;
93652      case 296: /* expr ::= RAISE LP IGNORE RP */
93653{
93654  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
93655  if( yygotominor.yy346.pExpr ){
93656    yygotominor.yy346.pExpr->affinity = OE_Ignore;
93657  }
93658  yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
93659  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93660}
93661        break;
93662      case 297: /* expr ::= RAISE LP raisetype COMMA nm RP */
93663{
93664  yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
93665  if( yygotominor.yy346.pExpr ) {
93666    yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
93667  }
93668  yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
93669  yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
93670}
93671        break;
93672      case 298: /* raisetype ::= ROLLBACK */
93673{yygotominor.yy328 = OE_Rollback;}
93674        break;
93675      case 300: /* raisetype ::= FAIL */
93676{yygotominor.yy328 = OE_Fail;}
93677        break;
93678      case 301: /* cmd ::= DROP TRIGGER ifexists fullname */
93679{
93680  sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
93681}
93682        break;
93683      case 302: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
93684{
93685  sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
93686}
93687        break;
93688      case 303: /* cmd ::= DETACH database_kw_opt expr */
93689{
93690  sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
93691}
93692        break;
93693      case 308: /* cmd ::= REINDEX */
93694{sqlite3Reindex(pParse, 0, 0);}
93695        break;
93696      case 309: /* cmd ::= REINDEX nm dbnm */
93697{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
93698        break;
93699      case 310: /* cmd ::= ANALYZE */
93700{sqlite3Analyze(pParse, 0, 0);}
93701        break;
93702      case 311: /* cmd ::= ANALYZE nm dbnm */
93703{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
93704        break;
93705      case 312: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
93706{
93707  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
93708}
93709        break;
93710      case 313: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
93711{
93712  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
93713}
93714        break;
93715      case 314: /* add_column_fullname ::= fullname */
93716{
93717  pParse->db->lookaside.bEnabled = 0;
93718  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
93719}
93720        break;
93721      case 317: /* cmd ::= create_vtab */
93722{sqlite3VtabFinishParse(pParse,0);}
93723        break;
93724      case 318: /* cmd ::= create_vtab LP vtabarglist RP */
93725{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
93726        break;
93727      case 319: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
93728{
93729    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
93730}
93731        break;
93732      case 322: /* vtabarg ::= */
93733{sqlite3VtabArgInit(pParse);}
93734        break;
93735      case 324: /* vtabargtoken ::= ANY */
93736      case 325: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==325);
93737      case 326: /* lp ::= LP */ yytestcase(yyruleno==326);
93738{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
93739        break;
93740      default:
93741      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
93742      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
93743      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
93744      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
93745      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
93746      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
93747      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
93748      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
93749      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
93750      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
93751      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
93752      /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
93753      /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
93754      /* (44) type ::= */ yytestcase(yyruleno==44);
93755      /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
93756      /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
93757      /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
93758      /* (54) carglist ::= */ yytestcase(yyruleno==54);
93759      /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
93760      /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
93761      /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
93762      /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
93763      /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
93764      /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
93765      /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
93766      /* (269) plus_opt ::= PLUS */ yytestcase(yyruleno==269);
93767      /* (270) plus_opt ::= */ yytestcase(yyruleno==270);
93768      /* (280) foreach_clause ::= */ yytestcase(yyruleno==280);
93769      /* (281) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==281);
93770      /* (288) tridxby ::= */ yytestcase(yyruleno==288);
93771      /* (306) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==306);
93772      /* (307) database_kw_opt ::= */ yytestcase(yyruleno==307);
93773      /* (315) kwcolumn_opt ::= */ yytestcase(yyruleno==315);
93774      /* (316) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==316);
93775      /* (320) vtabarglist ::= vtabarg */ yytestcase(yyruleno==320);
93776      /* (321) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==321);
93777      /* (323) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==323);
93778      /* (327) anylist ::= */ yytestcase(yyruleno==327);
93779      /* (328) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==328);
93780      /* (329) anylist ::= anylist ANY */ yytestcase(yyruleno==329);
93781        break;
93782  };
93783  yygoto = yyRuleInfo[yyruleno].lhs;
93784  yysize = yyRuleInfo[yyruleno].nrhs;
93785  yypParser->yyidx -= yysize;
93786  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
93787  if( yyact < YYNSTATE ){
93788#ifdef NDEBUG
93789    /* If we are not debugging and the reduce action popped at least
93790    ** one element off the stack, then we can push the new element back
93791    ** onto the stack here, and skip the stack overflow test in yy_shift().
93792    ** That gives a significant speed improvement. */
93793    if( yysize ){
93794      yypParser->yyidx++;
93795      yymsp -= yysize-1;
93796      yymsp->stateno = (YYACTIONTYPE)yyact;
93797      yymsp->major = (YYCODETYPE)yygoto;
93798      yymsp->minor = yygotominor;
93799    }else
93800#endif
93801    {
93802      yy_shift(yypParser,yyact,yygoto,&yygotominor);
93803    }
93804  }else{
93805    assert( yyact == YYNSTATE + YYNRULE + 1 );
93806    yy_accept(yypParser);
93807  }
93808}
93809
93810/*
93811** The following code executes when the parse fails
93812*/
93813#ifndef YYNOERRORRECOVERY
93814static void yy_parse_failed(
93815  yyParser *yypParser           /* The parser */
93816){
93817  sqlite3ParserARG_FETCH;
93818#ifndef NDEBUG
93819  if( yyTraceFILE ){
93820    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
93821  }
93822#endif
93823  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
93824  /* Here code is inserted which will be executed whenever the
93825  ** parser fails */
93826  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
93827}
93828#endif /* YYNOERRORRECOVERY */
93829
93830/*
93831** The following code executes when a syntax error first occurs.
93832*/
93833static void yy_syntax_error(
93834  yyParser *yypParser,           /* The parser */
93835  int yymajor,                   /* The major type of the error token */
93836  YYMINORTYPE yyminor            /* The minor type of the error token */
93837){
93838  sqlite3ParserARG_FETCH;
93839#define TOKEN (yyminor.yy0)
93840
93841  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
93842  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
93843  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
93844  pParse->parseError = 1;
93845  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
93846}
93847
93848/*
93849** The following is executed when the parser accepts
93850*/
93851static void yy_accept(
93852  yyParser *yypParser           /* The parser */
93853){
93854  sqlite3ParserARG_FETCH;
93855#ifndef NDEBUG
93856  if( yyTraceFILE ){
93857    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
93858  }
93859#endif
93860  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
93861  /* Here code is inserted which will be executed whenever the
93862  ** parser accepts */
93863  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
93864}
93865
93866/* The main parser program.
93867** The first argument is a pointer to a structure obtained from
93868** "sqlite3ParserAlloc" which describes the current state of the parser.
93869** The second argument is the major token number.  The third is
93870** the minor token.  The fourth optional argument is whatever the
93871** user wants (and specified in the grammar) and is available for
93872** use by the action routines.
93873**
93874** Inputs:
93875** <ul>
93876** <li> A pointer to the parser (an opaque structure.)
93877** <li> The major token number.
93878** <li> The minor token number.
93879** <li> An option argument of a grammar-specified type.
93880** </ul>
93881**
93882** Outputs:
93883** None.
93884*/
93885SQLITE_PRIVATE void sqlite3Parser(
93886  void *yyp,                   /* The parser */
93887  int yymajor,                 /* The major token code number */
93888  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
93889  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
93890){
93891  YYMINORTYPE yyminorunion;
93892  int yyact;            /* The parser action. */
93893  int yyendofinput;     /* True if we are at the end of input */
93894#ifdef YYERRORSYMBOL
93895  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
93896#endif
93897  yyParser *yypParser;  /* The parser */
93898
93899  /* (re)initialize the parser, if necessary */
93900  yypParser = (yyParser*)yyp;
93901  if( yypParser->yyidx<0 ){
93902#if YYSTACKDEPTH<=0
93903    if( yypParser->yystksz <=0 ){
93904      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
93905      yyminorunion = yyzerominor;
93906      yyStackOverflow(yypParser, &yyminorunion);
93907      return;
93908    }
93909#endif
93910    yypParser->yyidx = 0;
93911    yypParser->yyerrcnt = -1;
93912    yypParser->yystack[0].stateno = 0;
93913    yypParser->yystack[0].major = 0;
93914  }
93915  yyminorunion.yy0 = yyminor;
93916  yyendofinput = (yymajor==0);
93917  sqlite3ParserARG_STORE;
93918
93919#ifndef NDEBUG
93920  if( yyTraceFILE ){
93921    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
93922  }
93923#endif
93924
93925  do{
93926    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
93927    if( yyact<YYNSTATE ){
93928      assert( !yyendofinput );  /* Impossible to shift the $ token */
93929      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
93930      yypParser->yyerrcnt--;
93931      yymajor = YYNOCODE;
93932    }else if( yyact < YYNSTATE + YYNRULE ){
93933      yy_reduce(yypParser,yyact-YYNSTATE);
93934    }else{
93935      assert( yyact == YY_ERROR_ACTION );
93936#ifdef YYERRORSYMBOL
93937      int yymx;
93938#endif
93939#ifndef NDEBUG
93940      if( yyTraceFILE ){
93941        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
93942      }
93943#endif
93944#ifdef YYERRORSYMBOL
93945      /* A syntax error has occurred.
93946      ** The response to an error depends upon whether or not the
93947      ** grammar defines an error token "ERROR".
93948      **
93949      ** This is what we do if the grammar does define ERROR:
93950      **
93951      **  * Call the %syntax_error function.
93952      **
93953      **  * Begin popping the stack until we enter a state where
93954      **    it is legal to shift the error symbol, then shift
93955      **    the error symbol.
93956      **
93957      **  * Set the error count to three.
93958      **
93959      **  * Begin accepting and shifting new tokens.  No new error
93960      **    processing will occur until three tokens have been
93961      **    shifted successfully.
93962      **
93963      */
93964      if( yypParser->yyerrcnt<0 ){
93965        yy_syntax_error(yypParser,yymajor,yyminorunion);
93966      }
93967      yymx = yypParser->yystack[yypParser->yyidx].major;
93968      if( yymx==YYERRORSYMBOL || yyerrorhit ){
93969#ifndef NDEBUG
93970        if( yyTraceFILE ){
93971          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
93972             yyTracePrompt,yyTokenName[yymajor]);
93973        }
93974#endif
93975        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
93976        yymajor = YYNOCODE;
93977      }else{
93978         while(
93979          yypParser->yyidx >= 0 &&
93980          yymx != YYERRORSYMBOL &&
93981          (yyact = yy_find_reduce_action(
93982                        yypParser->yystack[yypParser->yyidx].stateno,
93983                        YYERRORSYMBOL)) >= YYNSTATE
93984        ){
93985          yy_pop_parser_stack(yypParser);
93986        }
93987        if( yypParser->yyidx < 0 || yymajor==0 ){
93988          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
93989          yy_parse_failed(yypParser);
93990          yymajor = YYNOCODE;
93991        }else if( yymx!=YYERRORSYMBOL ){
93992          YYMINORTYPE u2;
93993          u2.YYERRSYMDT = 0;
93994          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
93995        }
93996      }
93997      yypParser->yyerrcnt = 3;
93998      yyerrorhit = 1;
93999#elif defined(YYNOERRORRECOVERY)
94000      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
94001      ** do any kind of error recovery.  Instead, simply invoke the syntax
94002      ** error routine and continue going as if nothing had happened.
94003      **
94004      ** Applications can set this macro (for example inside %include) if
94005      ** they intend to abandon the parse upon the first syntax error seen.
94006      */
94007      yy_syntax_error(yypParser,yymajor,yyminorunion);
94008      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
94009      yymajor = YYNOCODE;
94010
94011#else  /* YYERRORSYMBOL is not defined */
94012      /* This is what we do if the grammar does not define ERROR:
94013      **
94014      **  * Report an error message, and throw away the input token.
94015      **
94016      **  * If the input token is $, then fail the parse.
94017      **
94018      ** As before, subsequent error messages are suppressed until
94019      ** three input tokens have been successfully shifted.
94020      */
94021      if( yypParser->yyerrcnt<=0 ){
94022        yy_syntax_error(yypParser,yymajor,yyminorunion);
94023      }
94024      yypParser->yyerrcnt = 3;
94025      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
94026      if( yyendofinput ){
94027        yy_parse_failed(yypParser);
94028      }
94029      yymajor = YYNOCODE;
94030#endif
94031    }
94032  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
94033  return;
94034}
94035
94036/************** End of parse.c ***********************************************/
94037/************** Begin file tokenize.c ****************************************/
94038/*
94039** 2001 September 15
94040**
94041** The author disclaims copyright to this source code.  In place of
94042** a legal notice, here is a blessing:
94043**
94044**    May you do good and not evil.
94045**    May you find forgiveness for yourself and forgive others.
94046**    May you share freely, never taking more than you give.
94047**
94048*************************************************************************
94049** An tokenizer for SQL
94050**
94051** This file contains C code that splits an SQL input string up into
94052** individual tokens and sends those tokens one-by-one over to the
94053** parser for analysis.
94054*/
94055
94056/*
94057** The charMap() macro maps alphabetic characters into their
94058** lower-case ASCII equivalent.  On ASCII machines, this is just
94059** an upper-to-lower case map.  On EBCDIC machines we also need
94060** to adjust the encoding.  Only alphabetic characters and underscores
94061** need to be translated.
94062*/
94063#ifdef SQLITE_ASCII
94064# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
94065#endif
94066#ifdef SQLITE_EBCDIC
94067# define charMap(X) ebcdicToAscii[(unsigned char)X]
94068const unsigned char ebcdicToAscii[] = {
94069/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
94070   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
94071   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
94072   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
94073   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
94074   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
94075   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
94076   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
94077   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
94078   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
94079   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
94080   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
94081   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
94082   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
94083   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
94084   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
94085   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
94086};
94087#endif
94088
94089/*
94090** The sqlite3KeywordCode function looks up an identifier to determine if
94091** it is a keyword.  If it is a keyword, the token code of that keyword is
94092** returned.  If the input is not a keyword, TK_ID is returned.
94093**
94094** The implementation of this routine was generated by a program,
94095** mkkeywordhash.h, located in the tool subdirectory of the distribution.
94096** The output of the mkkeywordhash.c program is written into a file
94097** named keywordhash.h and then included into this source file by
94098** the #include below.
94099*/
94100/************** Include keywordhash.h in the middle of tokenize.c ************/
94101/************** Begin file keywordhash.h *************************************/
94102/***** This file contains automatically generated code ******
94103**
94104** The code in this file has been automatically generated by
94105**
94106**   sqlite/tool/mkkeywordhash.c
94107**
94108** The code in this file implements a function that determines whether
94109** or not a given identifier is really an SQL keyword.  The same thing
94110** might be implemented more directly using a hand-written hash table.
94111** But by using this automatically generated code, the size of the code
94112** is substantially reduced.  This is important for embedded applications
94113** on platforms with limited memory.
94114*/
94115/* Hash score: 175 */
94116static int keywordCode(const char *z, int n){
94117  /* zText[] encodes 811 bytes of keywords in 541 bytes */
94118  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
94119  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
94120  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
94121  /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
94122  /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
94123  /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
94124  /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
94125  /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
94126  /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
94127  /*   INITIALLY                                                          */
94128  static const char zText[540] = {
94129    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
94130    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
94131    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
94132    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
94133    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
94134    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
94135    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
94136    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
94137    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
94138    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
94139    'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
94140    'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
94141    'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
94142    'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
94143    'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
94144    'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
94145    'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
94146    'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
94147    'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
94148    'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
94149    'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
94150    'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
94151    'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
94152    'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
94153    'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
94154    'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
94155    'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
94156    'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
94157    'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
94158    'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
94159  };
94160  static const unsigned char aHash[127] = {
94161      72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
94162      42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
94163     118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
94164       0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
94165       0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
94166      92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
94167      96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
94168      39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
94169      58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
94170      29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
94171  };
94172  static const unsigned char aNext[121] = {
94173       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
94174       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
94175       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
94176       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
94177       0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
94178      62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
94179      61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
94180       0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
94181     103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
94182      35,  64,   0,   0,
94183  };
94184  static const unsigned char aLen[121] = {
94185       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
94186       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
94187      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
94188       4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
94189       5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
94190       7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
94191       7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
94192       6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
94193       4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
94194       6,   4,   9,   3,
94195  };
94196  static const unsigned short int aOffset[121] = {
94197       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
94198      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
94199      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
94200     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
94201     203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
94202     248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
94203     326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
94204     387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
94205     462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
94206     521, 527, 531, 536,
94207  };
94208  static const unsigned char aCode[121] = {
94209    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
94210    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
94211    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
94212    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
94213    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
94214    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
94215    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
94216    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
94217    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
94218    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
94219    TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
94220    TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
94221    TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
94222    TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
94223    TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
94224    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
94225    TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
94226    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
94227    TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
94228    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
94229    TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
94230    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
94231    TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
94232    TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
94233    TK_ALL,
94234  };
94235  int h, i;
94236  if( n<2 ) return TK_ID;
94237  h = ((charMap(z[0])*4) ^
94238      (charMap(z[n-1])*3) ^
94239      n) % 127;
94240  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
94241    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
94242      testcase( i==0 ); /* REINDEX */
94243      testcase( i==1 ); /* INDEXED */
94244      testcase( i==2 ); /* INDEX */
94245      testcase( i==3 ); /* DESC */
94246      testcase( i==4 ); /* ESCAPE */
94247      testcase( i==5 ); /* EACH */
94248      testcase( i==6 ); /* CHECK */
94249      testcase( i==7 ); /* KEY */
94250      testcase( i==8 ); /* BEFORE */
94251      testcase( i==9 ); /* FOREIGN */
94252      testcase( i==10 ); /* FOR */
94253      testcase( i==11 ); /* IGNORE */
94254      testcase( i==12 ); /* REGEXP */
94255      testcase( i==13 ); /* EXPLAIN */
94256      testcase( i==14 ); /* INSTEAD */
94257      testcase( i==15 ); /* ADD */
94258      testcase( i==16 ); /* DATABASE */
94259      testcase( i==17 ); /* AS */
94260      testcase( i==18 ); /* SELECT */
94261      testcase( i==19 ); /* TABLE */
94262      testcase( i==20 ); /* LEFT */
94263      testcase( i==21 ); /* THEN */
94264      testcase( i==22 ); /* END */
94265      testcase( i==23 ); /* DEFERRABLE */
94266      testcase( i==24 ); /* ELSE */
94267      testcase( i==25 ); /* EXCEPT */
94268      testcase( i==26 ); /* TRANSACTION */
94269      testcase( i==27 ); /* ACTION */
94270      testcase( i==28 ); /* ON */
94271      testcase( i==29 ); /* NATURAL */
94272      testcase( i==30 ); /* ALTER */
94273      testcase( i==31 ); /* RAISE */
94274      testcase( i==32 ); /* EXCLUSIVE */
94275      testcase( i==33 ); /* EXISTS */
94276      testcase( i==34 ); /* SAVEPOINT */
94277      testcase( i==35 ); /* INTERSECT */
94278      testcase( i==36 ); /* TRIGGER */
94279      testcase( i==37 ); /* REFERENCES */
94280      testcase( i==38 ); /* CONSTRAINT */
94281      testcase( i==39 ); /* INTO */
94282      testcase( i==40 ); /* OFFSET */
94283      testcase( i==41 ); /* OF */
94284      testcase( i==42 ); /* SET */
94285      testcase( i==43 ); /* TEMPORARY */
94286      testcase( i==44 ); /* TEMP */
94287      testcase( i==45 ); /* OR */
94288      testcase( i==46 ); /* UNIQUE */
94289      testcase( i==47 ); /* QUERY */
94290      testcase( i==48 ); /* ATTACH */
94291      testcase( i==49 ); /* HAVING */
94292      testcase( i==50 ); /* GROUP */
94293      testcase( i==51 ); /* UPDATE */
94294      testcase( i==52 ); /* BEGIN */
94295      testcase( i==53 ); /* INNER */
94296      testcase( i==54 ); /* RELEASE */
94297      testcase( i==55 ); /* BETWEEN */
94298      testcase( i==56 ); /* NOTNULL */
94299      testcase( i==57 ); /* NOT */
94300      testcase( i==58 ); /* NO */
94301      testcase( i==59 ); /* NULL */
94302      testcase( i==60 ); /* LIKE */
94303      testcase( i==61 ); /* CASCADE */
94304      testcase( i==62 ); /* ASC */
94305      testcase( i==63 ); /* DELETE */
94306      testcase( i==64 ); /* CASE */
94307      testcase( i==65 ); /* COLLATE */
94308      testcase( i==66 ); /* CREATE */
94309      testcase( i==67 ); /* CURRENT_DATE */
94310      testcase( i==68 ); /* DETACH */
94311      testcase( i==69 ); /* IMMEDIATE */
94312      testcase( i==70 ); /* JOIN */
94313      testcase( i==71 ); /* INSERT */
94314      testcase( i==72 ); /* MATCH */
94315      testcase( i==73 ); /* PLAN */
94316      testcase( i==74 ); /* ANALYZE */
94317      testcase( i==75 ); /* PRAGMA */
94318      testcase( i==76 ); /* ABORT */
94319      testcase( i==77 ); /* VALUES */
94320      testcase( i==78 ); /* VIRTUAL */
94321      testcase( i==79 ); /* LIMIT */
94322      testcase( i==80 ); /* WHEN */
94323      testcase( i==81 ); /* WHERE */
94324      testcase( i==82 ); /* RENAME */
94325      testcase( i==83 ); /* AFTER */
94326      testcase( i==84 ); /* REPLACE */
94327      testcase( i==85 ); /* AND */
94328      testcase( i==86 ); /* DEFAULT */
94329      testcase( i==87 ); /* AUTOINCREMENT */
94330      testcase( i==88 ); /* TO */
94331      testcase( i==89 ); /* IN */
94332      testcase( i==90 ); /* CAST */
94333      testcase( i==91 ); /* COLUMN */
94334      testcase( i==92 ); /* COMMIT */
94335      testcase( i==93 ); /* CONFLICT */
94336      testcase( i==94 ); /* CROSS */
94337      testcase( i==95 ); /* CURRENT_TIMESTAMP */
94338      testcase( i==96 ); /* CURRENT_TIME */
94339      testcase( i==97 ); /* PRIMARY */
94340      testcase( i==98 ); /* DEFERRED */
94341      testcase( i==99 ); /* DISTINCT */
94342      testcase( i==100 ); /* IS */
94343      testcase( i==101 ); /* DROP */
94344      testcase( i==102 ); /* FAIL */
94345      testcase( i==103 ); /* FROM */
94346      testcase( i==104 ); /* FULL */
94347      testcase( i==105 ); /* GLOB */
94348      testcase( i==106 ); /* BY */
94349      testcase( i==107 ); /* IF */
94350      testcase( i==108 ); /* ISNULL */
94351      testcase( i==109 ); /* ORDER */
94352      testcase( i==110 ); /* RESTRICT */
94353      testcase( i==111 ); /* OUTER */
94354      testcase( i==112 ); /* RIGHT */
94355      testcase( i==113 ); /* ROLLBACK */
94356      testcase( i==114 ); /* ROW */
94357      testcase( i==115 ); /* UNION */
94358      testcase( i==116 ); /* USING */
94359      testcase( i==117 ); /* VACUUM */
94360      testcase( i==118 ); /* VIEW */
94361      testcase( i==119 ); /* INITIALLY */
94362      testcase( i==120 ); /* ALL */
94363      return aCode[i];
94364    }
94365  }
94366  return TK_ID;
94367}
94368SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
94369  return keywordCode((char*)z, n);
94370}
94371#define SQLITE_N_KEYWORD 121
94372
94373/************** End of keywordhash.h *****************************************/
94374/************** Continuing where we left off in tokenize.c *******************/
94375
94376
94377/*
94378** If X is a character that can be used in an identifier then
94379** IdChar(X) will be true.  Otherwise it is false.
94380**
94381** For ASCII, any character with the high-order bit set is
94382** allowed in an identifier.  For 7-bit characters,
94383** sqlite3IsIdChar[X] must be 1.
94384**
94385** For EBCDIC, the rules are more complex but have the same
94386** end result.
94387**
94388** Ticket #1066.  the SQL standard does not allow '$' in the
94389** middle of identfiers.  But many SQL implementations do.
94390** SQLite will allow '$' in identifiers for compatibility.
94391** But the feature is undocumented.
94392*/
94393#ifdef SQLITE_ASCII
94394#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
94395#endif
94396#ifdef SQLITE_EBCDIC
94397SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
94398/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
94399    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
94400    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
94401    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
94402    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
94403    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
94404    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
94405    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
94406    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
94407    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
94408    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
94409    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
94410    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
94411};
94412#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
94413#endif
94414
94415
94416/*
94417** Return the length of the token that begins at z[0].
94418** Store the token type in *tokenType before returning.
94419*/
94420SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
94421  int i, c;
94422  switch( *z ){
94423    case ' ': case '\t': case '\n': case '\f': case '\r': {
94424      testcase( z[0]==' ' );
94425      testcase( z[0]=='\t' );
94426      testcase( z[0]=='\n' );
94427      testcase( z[0]=='\f' );
94428      testcase( z[0]=='\r' );
94429      for(i=1; sqlite3Isspace(z[i]); i++){}
94430      *tokenType = TK_SPACE;
94431      return i;
94432    }
94433    case '-': {
94434      if( z[1]=='-' ){
94435        /* IMP: R-15891-05542 -- syntax diagram for comments */
94436        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
94437        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
94438        return i;
94439      }
94440      *tokenType = TK_MINUS;
94441      return 1;
94442    }
94443    case '(': {
94444      *tokenType = TK_LP;
94445      return 1;
94446    }
94447    case ')': {
94448      *tokenType = TK_RP;
94449      return 1;
94450    }
94451    case ';': {
94452      *tokenType = TK_SEMI;
94453      return 1;
94454    }
94455    case '+': {
94456      *tokenType = TK_PLUS;
94457      return 1;
94458    }
94459    case '*': {
94460      *tokenType = TK_STAR;
94461      return 1;
94462    }
94463    case '/': {
94464      if( z[1]!='*' || z[2]==0 ){
94465        *tokenType = TK_SLASH;
94466        return 1;
94467      }
94468      /* IMP: R-15891-05542 -- syntax diagram for comments */
94469      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
94470      if( c ) i++;
94471      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
94472      return i;
94473    }
94474    case '%': {
94475      *tokenType = TK_REM;
94476      return 1;
94477    }
94478    case '=': {
94479      *tokenType = TK_EQ;
94480      return 1 + (z[1]=='=');
94481    }
94482    case '<': {
94483      if( (c=z[1])=='=' ){
94484        *tokenType = TK_LE;
94485        return 2;
94486      }else if( c=='>' ){
94487        *tokenType = TK_NE;
94488        return 2;
94489      }else if( c=='<' ){
94490        *tokenType = TK_LSHIFT;
94491        return 2;
94492      }else{
94493        *tokenType = TK_LT;
94494        return 1;
94495      }
94496    }
94497    case '>': {
94498      if( (c=z[1])=='=' ){
94499        *tokenType = TK_GE;
94500        return 2;
94501      }else if( c=='>' ){
94502        *tokenType = TK_RSHIFT;
94503        return 2;
94504      }else{
94505        *tokenType = TK_GT;
94506        return 1;
94507      }
94508    }
94509    case '!': {
94510      if( z[1]!='=' ){
94511        *tokenType = TK_ILLEGAL;
94512        return 2;
94513      }else{
94514        *tokenType = TK_NE;
94515        return 2;
94516      }
94517    }
94518    case '|': {
94519      if( z[1]!='|' ){
94520        *tokenType = TK_BITOR;
94521        return 1;
94522      }else{
94523        *tokenType = TK_CONCAT;
94524        return 2;
94525      }
94526    }
94527    case ',': {
94528      *tokenType = TK_COMMA;
94529      return 1;
94530    }
94531    case '&': {
94532      *tokenType = TK_BITAND;
94533      return 1;
94534    }
94535    case '~': {
94536      *tokenType = TK_BITNOT;
94537      return 1;
94538    }
94539    case '`':
94540    case '\'':
94541    case '"': {
94542      int delim = z[0];
94543      testcase( delim=='`' );
94544      testcase( delim=='\'' );
94545      testcase( delim=='"' );
94546      for(i=1; (c=z[i])!=0; i++){
94547        if( c==delim ){
94548          if( z[i+1]==delim ){
94549            i++;
94550          }else{
94551            break;
94552          }
94553        }
94554      }
94555      if( c=='\'' ){
94556        *tokenType = TK_STRING;
94557        return i+1;
94558      }else if( c!=0 ){
94559        *tokenType = TK_ID;
94560        return i+1;
94561      }else{
94562        *tokenType = TK_ILLEGAL;
94563        return i;
94564      }
94565    }
94566    case '.': {
94567#ifndef SQLITE_OMIT_FLOATING_POINT
94568      if( !sqlite3Isdigit(z[1]) )
94569#endif
94570      {
94571        *tokenType = TK_DOT;
94572        return 1;
94573      }
94574      /* If the next character is a digit, this is a floating point
94575      ** number that begins with ".".  Fall thru into the next case */
94576    }
94577    case '0': case '1': case '2': case '3': case '4':
94578    case '5': case '6': case '7': case '8': case '9': {
94579      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
94580      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
94581      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
94582      testcase( z[0]=='9' );
94583      *tokenType = TK_INTEGER;
94584      for(i=0; sqlite3Isdigit(z[i]); i++){}
94585#ifndef SQLITE_OMIT_FLOATING_POINT
94586      if( z[i]=='.' ){
94587        i++;
94588        while( sqlite3Isdigit(z[i]) ){ i++; }
94589        *tokenType = TK_FLOAT;
94590      }
94591      if( (z[i]=='e' || z[i]=='E') &&
94592           ( sqlite3Isdigit(z[i+1])
94593            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
94594           )
94595      ){
94596        i += 2;
94597        while( sqlite3Isdigit(z[i]) ){ i++; }
94598        *tokenType = TK_FLOAT;
94599      }
94600#endif
94601      while( IdChar(z[i]) ){
94602        *tokenType = TK_ILLEGAL;
94603        i++;
94604      }
94605      return i;
94606    }
94607    case '[': {
94608      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
94609      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
94610      return i;
94611    }
94612    case '?': {
94613      *tokenType = TK_VARIABLE;
94614      for(i=1; sqlite3Isdigit(z[i]); i++){}
94615      return i;
94616    }
94617    case '#': {
94618      for(i=1; sqlite3Isdigit(z[i]); i++){}
94619      if( i>1 ){
94620        /* Parameters of the form #NNN (where NNN is a number) are used
94621        ** internally by sqlite3NestedParse.  */
94622        *tokenType = TK_REGISTER;
94623        return i;
94624      }
94625      /* Fall through into the next case if the '#' is not followed by
94626      ** a digit. Try to match #AAAA where AAAA is a parameter name. */
94627    }
94628#ifndef SQLITE_OMIT_TCL_VARIABLE
94629    case '$':
94630#endif
94631    case '@':  /* For compatibility with MS SQL Server */
94632    case ':': {
94633      int n = 0;
94634      testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
94635      *tokenType = TK_VARIABLE;
94636      for(i=1; (c=z[i])!=0; i++){
94637        if( IdChar(c) ){
94638          n++;
94639#ifndef SQLITE_OMIT_TCL_VARIABLE
94640        }else if( c=='(' && n>0 ){
94641          do{
94642            i++;
94643          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
94644          if( c==')' ){
94645            i++;
94646          }else{
94647            *tokenType = TK_ILLEGAL;
94648          }
94649          break;
94650        }else if( c==':' && z[i+1]==':' ){
94651          i++;
94652#endif
94653        }else{
94654          break;
94655        }
94656      }
94657      if( n==0 ) *tokenType = TK_ILLEGAL;
94658      return i;
94659    }
94660#ifndef SQLITE_OMIT_BLOB_LITERAL
94661    case 'x': case 'X': {
94662      testcase( z[0]=='x' ); testcase( z[0]=='X' );
94663      if( z[1]=='\'' ){
94664        *tokenType = TK_BLOB;
94665        for(i=2; (c=z[i])!=0 && c!='\''; i++){
94666          if( !sqlite3Isxdigit(c) ){
94667            *tokenType = TK_ILLEGAL;
94668          }
94669        }
94670        if( i%2 || !c ) *tokenType = TK_ILLEGAL;
94671        if( c ) i++;
94672        return i;
94673      }
94674      /* Otherwise fall through to the next case */
94675    }
94676#endif
94677    default: {
94678      if( !IdChar(*z) ){
94679        break;
94680      }
94681      for(i=1; IdChar(z[i]); i++){}
94682      *tokenType = keywordCode((char*)z, i);
94683      return i;
94684    }
94685  }
94686  *tokenType = TK_ILLEGAL;
94687  return 1;
94688}
94689
94690/*
94691** Run the parser on the given SQL string.  The parser structure is
94692** passed in.  An SQLITE_ status code is returned.  If an error occurs
94693** then an and attempt is made to write an error message into
94694** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
94695** error message.
94696*/
94697SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
94698  int nErr = 0;                   /* Number of errors encountered */
94699  int i;                          /* Loop counter */
94700  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
94701  int tokenType;                  /* type of the next token */
94702  int lastTokenParsed = -1;       /* type of the previous token */
94703  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
94704  sqlite3 *db = pParse->db;       /* The database connection */
94705  int mxSqlLen;                   /* Max length of an SQL string */
94706
94707
94708  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
94709  if( db->activeVdbeCnt==0 ){
94710    db->u1.isInterrupted = 0;
94711  }
94712  pParse->rc = SQLITE_OK;
94713  pParse->zTail = zSql;
94714  i = 0;
94715  assert( pzErrMsg!=0 );
94716  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
94717  if( pEngine==0 ){
94718    db->mallocFailed = 1;
94719    return SQLITE_NOMEM;
94720  }
94721  assert( pParse->pNewTable==0 );
94722  assert( pParse->pNewTrigger==0 );
94723  assert( pParse->nVar==0 );
94724  assert( pParse->nVarExpr==0 );
94725  assert( pParse->nVarExprAlloc==0 );
94726  assert( pParse->apVarExpr==0 );
94727  enableLookaside = db->lookaside.bEnabled;
94728  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
94729  while( !db->mallocFailed && zSql[i]!=0 ){
94730    assert( i>=0 );
94731    pParse->sLastToken.z = &zSql[i];
94732    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
94733    i += pParse->sLastToken.n;
94734    if( i>mxSqlLen ){
94735      pParse->rc = SQLITE_TOOBIG;
94736      break;
94737    }
94738    switch( tokenType ){
94739      case TK_SPACE: {
94740        if( db->u1.isInterrupted ){
94741          sqlite3ErrorMsg(pParse, "interrupt");
94742          pParse->rc = SQLITE_INTERRUPT;
94743          goto abort_parse;
94744        }
94745        break;
94746      }
94747      case TK_ILLEGAL: {
94748        sqlite3DbFree(db, *pzErrMsg);
94749        *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
94750                        &pParse->sLastToken);
94751        nErr++;
94752        goto abort_parse;
94753      }
94754      case TK_SEMI: {
94755        pParse->zTail = &zSql[i];
94756        /* Fall thru into the default case */
94757      }
94758      default: {
94759        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
94760        lastTokenParsed = tokenType;
94761        if( pParse->rc!=SQLITE_OK ){
94762          goto abort_parse;
94763        }
94764        break;
94765      }
94766    }
94767  }
94768abort_parse:
94769  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
94770    if( lastTokenParsed!=TK_SEMI ){
94771      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
94772      pParse->zTail = &zSql[i];
94773    }
94774    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
94775  }
94776#ifdef YYTRACKMAXSTACKDEPTH
94777  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
94778      sqlite3ParserStackPeak(pEngine)
94779  );
94780#endif /* YYDEBUG */
94781  sqlite3ParserFree(pEngine, sqlite3_free);
94782  db->lookaside.bEnabled = enableLookaside;
94783  if( db->mallocFailed ){
94784    pParse->rc = SQLITE_NOMEM;
94785  }
94786  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
94787    sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
94788  }
94789  assert( pzErrMsg!=0 );
94790  if( pParse->zErrMsg ){
94791    *pzErrMsg = pParse->zErrMsg;
94792    pParse->zErrMsg = 0;
94793    nErr++;
94794  }
94795  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
94796    sqlite3VdbeDelete(pParse->pVdbe);
94797    pParse->pVdbe = 0;
94798  }
94799#ifndef SQLITE_OMIT_SHARED_CACHE
94800  if( pParse->nested==0 ){
94801    sqlite3DbFree(db, pParse->aTableLock);
94802    pParse->aTableLock = 0;
94803    pParse->nTableLock = 0;
94804  }
94805#endif
94806#ifndef SQLITE_OMIT_VIRTUALTABLE
94807  sqlite3DbFree(db, pParse->apVtabLock);
94808#endif
94809
94810  if( !IN_DECLARE_VTAB ){
94811    /* If the pParse->declareVtab flag is set, do not delete any table
94812    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
94813    ** will take responsibility for freeing the Table structure.
94814    */
94815    sqlite3DeleteTable(pParse->pNewTable);
94816  }
94817
94818  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
94819  sqlite3DbFree(db, pParse->apVarExpr);
94820  sqlite3DbFree(db, pParse->aAlias);
94821  while( pParse->pAinc ){
94822    AutoincInfo *p = pParse->pAinc;
94823    pParse->pAinc = p->pNext;
94824    sqlite3DbFree(db, p);
94825  }
94826  while( pParse->pZombieTab ){
94827    Table *p = pParse->pZombieTab;
94828    pParse->pZombieTab = p->pNextZombie;
94829    sqlite3DeleteTable(p);
94830  }
94831  if( nErr>0 && pParse->rc==SQLITE_OK ){
94832    pParse->rc = SQLITE_ERROR;
94833  }
94834  return nErr;
94835}
94836
94837/************** End of tokenize.c ********************************************/
94838/************** Begin file complete.c ****************************************/
94839/*
94840** 2001 September 15
94841**
94842** The author disclaims copyright to this source code.  In place of
94843** a legal notice, here is a blessing:
94844**
94845**    May you do good and not evil.
94846**    May you find forgiveness for yourself and forgive others.
94847**    May you share freely, never taking more than you give.
94848**
94849*************************************************************************
94850** An tokenizer for SQL
94851**
94852** This file contains C code that implements the sqlite3_complete() API.
94853** This code used to be part of the tokenizer.c source file.  But by
94854** separating it out, the code will be automatically omitted from
94855** static links that do not use it.
94856*/
94857#ifndef SQLITE_OMIT_COMPLETE
94858
94859/*
94860** This is defined in tokenize.c.  We just have to import the definition.
94861*/
94862#ifndef SQLITE_AMALGAMATION
94863#ifdef SQLITE_ASCII
94864#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
94865#endif
94866#ifdef SQLITE_EBCDIC
94867SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
94868#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
94869#endif
94870#endif /* SQLITE_AMALGAMATION */
94871
94872
94873/*
94874** Token types used by the sqlite3_complete() routine.  See the header
94875** comments on that procedure for additional information.
94876*/
94877#define tkSEMI    0
94878#define tkWS      1
94879#define tkOTHER   2
94880#ifndef SQLITE_OMIT_TRIGGER
94881#define tkEXPLAIN 3
94882#define tkCREATE  4
94883#define tkTEMP    5
94884#define tkTRIGGER 6
94885#define tkEND     7
94886#endif
94887
94888/*
94889** Return TRUE if the given SQL string ends in a semicolon.
94890**
94891** Special handling is require for CREATE TRIGGER statements.
94892** Whenever the CREATE TRIGGER keywords are seen, the statement
94893** must end with ";END;".
94894**
94895** This implementation uses a state machine with 8 states:
94896**
94897**   (0) INVALID   We have not yet seen a non-whitespace character.
94898**
94899**   (1) START     At the beginning or end of an SQL statement.  This routine
94900**                 returns 1 if it ends in the START state and 0 if it ends
94901**                 in any other state.
94902**
94903**   (2) NORMAL    We are in the middle of statement which ends with a single
94904**                 semicolon.
94905**
94906**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
94907**                 a statement.
94908**
94909**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
94910**                 statement, possibly preceeded by EXPLAIN and/or followed by
94911**                 TEMP or TEMPORARY
94912**
94913**   (5) TRIGGER   We are in the middle of a trigger definition that must be
94914**                 ended by a semicolon, the keyword END, and another semicolon.
94915**
94916**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
94917**                 the end of a trigger definition.
94918**
94919**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
94920**                 of a trigger difinition.
94921**
94922** Transitions between states above are determined by tokens extracted
94923** from the input.  The following tokens are significant:
94924**
94925**   (0) tkSEMI      A semicolon.
94926**   (1) tkWS        Whitespace.
94927**   (2) tkOTHER     Any other SQL token.
94928**   (3) tkEXPLAIN   The "explain" keyword.
94929**   (4) tkCREATE    The "create" keyword.
94930**   (5) tkTEMP      The "temp" or "temporary" keyword.
94931**   (6) tkTRIGGER   The "trigger" keyword.
94932**   (7) tkEND       The "end" keyword.
94933**
94934** Whitespace never causes a state transition and is always ignored.
94935** This means that a SQL string of all whitespace is invalid.
94936**
94937** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
94938** to recognize the end of a trigger can be omitted.  All we have to do
94939** is look for a semicolon that is not part of an string or comment.
94940*/
94941SQLITE_API int sqlite3_complete(const char *zSql){
94942  u8 state = 0;   /* Current state, using numbers defined in header comment */
94943  u8 token;       /* Value of the next token */
94944
94945#ifndef SQLITE_OMIT_TRIGGER
94946  /* A complex statement machine used to detect the end of a CREATE TRIGGER
94947  ** statement.  This is the normal case.
94948  */
94949  static const u8 trans[8][8] = {
94950                     /* Token:                                                */
94951     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
94952     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
94953     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
94954     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
94955     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
94956     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
94957     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
94958     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
94959     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
94960  };
94961#else
94962  /* If triggers are not supported by this compile then the statement machine
94963  ** used to detect the end of a statement is much simplier
94964  */
94965  static const u8 trans[3][3] = {
94966                     /* Token:           */
94967     /* State:       **  SEMI  WS  OTHER */
94968     /* 0 INVALID: */ {    1,  0,     2, },
94969     /* 1   START: */ {    1,  1,     2, },
94970     /* 2  NORMAL: */ {    1,  2,     2, },
94971  };
94972#endif /* SQLITE_OMIT_TRIGGER */
94973
94974  while( *zSql ){
94975    switch( *zSql ){
94976      case ';': {  /* A semicolon */
94977        token = tkSEMI;
94978        break;
94979      }
94980      case ' ':
94981      case '\r':
94982      case '\t':
94983      case '\n':
94984      case '\f': {  /* White space is ignored */
94985        token = tkWS;
94986        break;
94987      }
94988      case '/': {   /* C-style comments */
94989        if( zSql[1]!='*' ){
94990          token = tkOTHER;
94991          break;
94992        }
94993        zSql += 2;
94994        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
94995        if( zSql[0]==0 ) return 0;
94996        zSql++;
94997        token = tkWS;
94998        break;
94999      }
95000      case '-': {   /* SQL-style comments from "--" to end of line */
95001        if( zSql[1]!='-' ){
95002          token = tkOTHER;
95003          break;
95004        }
95005        while( *zSql && *zSql!='\n' ){ zSql++; }
95006        if( *zSql==0 ) return state==1;
95007        token = tkWS;
95008        break;
95009      }
95010      case '[': {   /* Microsoft-style identifiers in [...] */
95011        zSql++;
95012        while( *zSql && *zSql!=']' ){ zSql++; }
95013        if( *zSql==0 ) return 0;
95014        token = tkOTHER;
95015        break;
95016      }
95017      case '`':     /* Grave-accent quoted symbols used by MySQL */
95018      case '"':     /* single- and double-quoted strings */
95019      case '\'': {
95020        int c = *zSql;
95021        zSql++;
95022        while( *zSql && *zSql!=c ){ zSql++; }
95023        if( *zSql==0 ) return 0;
95024        token = tkOTHER;
95025        break;
95026      }
95027      default: {
95028#ifdef SQLITE_EBCDIC
95029        unsigned char c;
95030#endif
95031        if( IdChar((u8)*zSql) ){
95032          /* Keywords and unquoted identifiers */
95033          int nId;
95034          for(nId=1; IdChar(zSql[nId]); nId++){}
95035#ifdef SQLITE_OMIT_TRIGGER
95036          token = tkOTHER;
95037#else
95038          switch( *zSql ){
95039            case 'c': case 'C': {
95040              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
95041                token = tkCREATE;
95042              }else{
95043                token = tkOTHER;
95044              }
95045              break;
95046            }
95047            case 't': case 'T': {
95048              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
95049                token = tkTRIGGER;
95050              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
95051                token = tkTEMP;
95052              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
95053                token = tkTEMP;
95054              }else{
95055                token = tkOTHER;
95056              }
95057              break;
95058            }
95059            case 'e':  case 'E': {
95060              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
95061                token = tkEND;
95062              }else
95063#ifndef SQLITE_OMIT_EXPLAIN
95064              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
95065                token = tkEXPLAIN;
95066              }else
95067#endif
95068              {
95069                token = tkOTHER;
95070              }
95071              break;
95072            }
95073            default: {
95074              token = tkOTHER;
95075              break;
95076            }
95077          }
95078#endif /* SQLITE_OMIT_TRIGGER */
95079          zSql += nId-1;
95080        }else{
95081          /* Operators and special symbols */
95082          token = tkOTHER;
95083        }
95084        break;
95085      }
95086    }
95087    state = trans[state][token];
95088    zSql++;
95089  }
95090  return state==1;
95091}
95092
95093#ifndef SQLITE_OMIT_UTF16
95094/*
95095** This routine is the same as the sqlite3_complete() routine described
95096** above, except that the parameter is required to be UTF-16 encoded, not
95097** UTF-8.
95098*/
95099SQLITE_API int sqlite3_complete16(const void *zSql){
95100  sqlite3_value *pVal;
95101  char const *zSql8;
95102  int rc = SQLITE_NOMEM;
95103
95104#ifndef SQLITE_OMIT_AUTOINIT
95105  rc = sqlite3_initialize();
95106  if( rc ) return rc;
95107#endif
95108  pVal = sqlite3ValueNew(0);
95109  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
95110  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
95111  if( zSql8 ){
95112    rc = sqlite3_complete(zSql8);
95113  }else{
95114    rc = SQLITE_NOMEM;
95115  }
95116  sqlite3ValueFree(pVal);
95117  return sqlite3ApiExit(0, rc);
95118}
95119#endif /* SQLITE_OMIT_UTF16 */
95120#endif /* SQLITE_OMIT_COMPLETE */
95121
95122/************** End of complete.c ********************************************/
95123/************** Begin file main.c ********************************************/
95124/*
95125** 2001 September 15
95126**
95127** The author disclaims copyright to this source code.  In place of
95128** a legal notice, here is a blessing:
95129**
95130**    May you do good and not evil.
95131**    May you find forgiveness for yourself and forgive others.
95132**    May you share freely, never taking more than you give.
95133**
95134*************************************************************************
95135** Main file for the SQLite library.  The routines in this file
95136** implement the programmer interface to the library.  Routines in
95137** other files are for internal use by SQLite and should not be
95138** accessed by users of the library.
95139*/
95140
95141#ifdef SQLITE_ENABLE_FTS3
95142/************** Include fts3.h in the middle of main.c ***********************/
95143/************** Begin file fts3.h ********************************************/
95144/*
95145** 2006 Oct 10
95146**
95147** The author disclaims copyright to this source code.  In place of
95148** a legal notice, here is a blessing:
95149**
95150**    May you do good and not evil.
95151**    May you find forgiveness for yourself and forgive others.
95152**    May you share freely, never taking more than you give.
95153**
95154******************************************************************************
95155**
95156** This header file is used by programs that want to link against the
95157** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
95158*/
95159
95160#if 0
95161extern "C" {
95162#endif  /* __cplusplus */
95163
95164SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
95165
95166#if 0
95167}  /* extern "C" */
95168#endif  /* __cplusplus */
95169
95170/************** End of fts3.h ************************************************/
95171/************** Continuing where we left off in main.c ***********************/
95172#endif
95173#ifdef SQLITE_ENABLE_RTREE
95174/************** Include rtree.h in the middle of main.c **********************/
95175/************** Begin file rtree.h *******************************************/
95176/*
95177** 2008 May 26
95178**
95179** The author disclaims copyright to this source code.  In place of
95180** a legal notice, here is a blessing:
95181**
95182**    May you do good and not evil.
95183**    May you find forgiveness for yourself and forgive others.
95184**    May you share freely, never taking more than you give.
95185**
95186******************************************************************************
95187**
95188** This header file is used by programs that want to link against the
95189** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
95190*/
95191
95192#if 0
95193extern "C" {
95194#endif  /* __cplusplus */
95195
95196SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
95197
95198#if 0
95199}  /* extern "C" */
95200#endif  /* __cplusplus */
95201
95202/************** End of rtree.h ***********************************************/
95203/************** Continuing where we left off in main.c ***********************/
95204#endif
95205#ifdef SQLITE_ENABLE_ICU
95206/************** Include sqliteicu.h in the middle of main.c ******************/
95207/************** Begin file sqliteicu.h ***************************************/
95208/*
95209** 2008 May 26
95210**
95211** The author disclaims copyright to this source code.  In place of
95212** a legal notice, here is a blessing:
95213**
95214**    May you do good and not evil.
95215**    May you find forgiveness for yourself and forgive others.
95216**    May you share freely, never taking more than you give.
95217**
95218******************************************************************************
95219**
95220** This header file is used by programs that want to link against the
95221** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
95222*/
95223
95224#if 0
95225extern "C" {
95226#endif  /* __cplusplus */
95227
95228SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
95229
95230#if 0
95231}  /* extern "C" */
95232#endif  /* __cplusplus */
95233
95234
95235/************** End of sqliteicu.h *******************************************/
95236/************** Continuing where we left off in main.c ***********************/
95237#endif
95238
95239/*
95240** The version of the library
95241*/
95242#ifndef SQLITE_AMALGAMATION
95243SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
95244#endif
95245SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
95246SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
95247SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
95248SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
95249
95250#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
95251/*
95252** If the following function pointer is not NULL and if
95253** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
95254** I/O active are written using this function.  These messages
95255** are intended for debugging activity only.
95256*/
95257SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
95258#endif
95259
95260/*
95261** If the following global variable points to a string which is the
95262** name of a directory, then that directory will be used to store
95263** temporary files.
95264**
95265** See also the "PRAGMA temp_store_directory" SQL command.
95266*/
95267SQLITE_API char *sqlite3_temp_directory = 0;
95268
95269/*
95270** Initialize SQLite.
95271**
95272** This routine must be called to initialize the memory allocation,
95273** VFS, and mutex subsystems prior to doing any serious work with
95274** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
95275** this routine will be called automatically by key routines such as
95276** sqlite3_open().
95277**
95278** This routine is a no-op except on its very first call for the process,
95279** or for the first call after a call to sqlite3_shutdown.
95280**
95281** The first thread to call this routine runs the initialization to
95282** completion.  If subsequent threads call this routine before the first
95283** thread has finished the initialization process, then the subsequent
95284** threads must block until the first thread finishes with the initialization.
95285**
95286** The first thread might call this routine recursively.  Recursive
95287** calls to this routine should not block, of course.  Otherwise the
95288** initialization process would never complete.
95289**
95290** Let X be the first thread to enter this routine.  Let Y be some other
95291** thread.  Then while the initial invocation of this routine by X is
95292** incomplete, it is required that:
95293**
95294**    *  Calls to this routine from Y must block until the outer-most
95295**       call by X completes.
95296**
95297**    *  Recursive calls to this routine from thread X return immediately
95298**       without blocking.
95299*/
95300SQLITE_API int sqlite3_initialize(void){
95301  sqlite3_mutex *pMaster;                      /* The main static mutex */
95302  int rc;                                      /* Result code */
95303
95304#ifdef SQLITE_OMIT_WSD
95305  rc = sqlite3_wsd_init(4096, 24);
95306  if( rc!=SQLITE_OK ){
95307    return rc;
95308  }
95309#endif
95310
95311  /* If SQLite is already completely initialized, then this call
95312  ** to sqlite3_initialize() should be a no-op.  But the initialization
95313  ** must be complete.  So isInit must not be set until the very end
95314  ** of this routine.
95315  */
95316  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
95317
95318  /* Make sure the mutex subsystem is initialized.  If unable to
95319  ** initialize the mutex subsystem, return early with the error.
95320  ** If the system is so sick that we are unable to allocate a mutex,
95321  ** there is not much SQLite is going to be able to do.
95322  **
95323  ** The mutex subsystem must take care of serializing its own
95324  ** initialization.
95325  */
95326  rc = sqlite3MutexInit();
95327  if( rc ) return rc;
95328
95329  /* Initialize the malloc() system and the recursive pInitMutex mutex.
95330  ** This operation is protected by the STATIC_MASTER mutex.  Note that
95331  ** MutexAlloc() is called for a static mutex prior to initializing the
95332  ** malloc subsystem - this implies that the allocation of a static
95333  ** mutex must not require support from the malloc subsystem.
95334  */
95335  pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
95336  sqlite3_mutex_enter(pMaster);
95337  sqlite3GlobalConfig.isMutexInit = 1;
95338  if( !sqlite3GlobalConfig.isMallocInit ){
95339    rc = sqlite3MallocInit();
95340  }
95341  if( rc==SQLITE_OK ){
95342    sqlite3GlobalConfig.isMallocInit = 1;
95343    if( !sqlite3GlobalConfig.pInitMutex ){
95344      sqlite3GlobalConfig.pInitMutex =
95345           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
95346      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
95347        rc = SQLITE_NOMEM;
95348      }
95349    }
95350  }
95351  if( rc==SQLITE_OK ){
95352    sqlite3GlobalConfig.nRefInitMutex++;
95353  }
95354  sqlite3_mutex_leave(pMaster);
95355
95356  /* If rc is not SQLITE_OK at this point, then either the malloc
95357  ** subsystem could not be initialized or the system failed to allocate
95358  ** the pInitMutex mutex. Return an error in either case.  */
95359  if( rc!=SQLITE_OK ){
95360    return rc;
95361  }
95362
95363  /* Do the rest of the initialization under the recursive mutex so
95364  ** that we will be able to handle recursive calls into
95365  ** sqlite3_initialize().  The recursive calls normally come through
95366  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
95367  ** recursive calls might also be possible.
95368  */
95369  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
95370  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
95371    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
95372    sqlite3GlobalConfig.inProgress = 1;
95373    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
95374    sqlite3RegisterGlobalFunctions();
95375    if( sqlite3GlobalConfig.isPCacheInit==0 ){
95376      rc = sqlite3PcacheInitialize();
95377    }
95378    if( rc==SQLITE_OK ){
95379      sqlite3GlobalConfig.isPCacheInit = 1;
95380      rc = sqlite3OsInit();
95381    }
95382    if( rc==SQLITE_OK ){
95383      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
95384          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
95385      sqlite3GlobalConfig.isInit = 1;
95386    }
95387    sqlite3GlobalConfig.inProgress = 0;
95388  }
95389  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
95390
95391  /* Go back under the static mutex and clean up the recursive
95392  ** mutex to prevent a resource leak.
95393  */
95394  sqlite3_mutex_enter(pMaster);
95395  sqlite3GlobalConfig.nRefInitMutex--;
95396  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
95397    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
95398    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
95399    sqlite3GlobalConfig.pInitMutex = 0;
95400  }
95401  sqlite3_mutex_leave(pMaster);
95402
95403  /* The following is just a sanity check to make sure SQLite has
95404  ** been compiled correctly.  It is important to run this code, but
95405  ** we don't want to run it too often and soak up CPU cycles for no
95406  ** reason.  So we run it once during initialization.
95407  */
95408#ifndef NDEBUG
95409#ifndef SQLITE_OMIT_FLOATING_POINT
95410  /* This section of code's only "output" is via assert() statements. */
95411  if ( rc==SQLITE_OK ){
95412    u64 x = (((u64)1)<<63)-1;
95413    double y;
95414    assert(sizeof(x)==8);
95415    assert(sizeof(x)==sizeof(y));
95416    memcpy(&y, &x, 8);
95417    assert( sqlite3IsNaN(y) );
95418  }
95419#endif
95420#endif
95421
95422  return rc;
95423}
95424
95425/*
95426** Undo the effects of sqlite3_initialize().  Must not be called while
95427** there are outstanding database connections or memory allocations or
95428** while any part of SQLite is otherwise in use in any thread.  This
95429** routine is not threadsafe.  But it is safe to invoke this routine
95430** on when SQLite is already shut down.  If SQLite is already shut down
95431** when this routine is invoked, then this routine is a harmless no-op.
95432*/
95433SQLITE_API int sqlite3_shutdown(void){
95434  if( sqlite3GlobalConfig.isInit ){
95435    sqlite3_os_end();
95436    sqlite3_reset_auto_extension();
95437    sqlite3GlobalConfig.isInit = 0;
95438  }
95439  if( sqlite3GlobalConfig.isPCacheInit ){
95440    sqlite3PcacheShutdown();
95441    sqlite3GlobalConfig.isPCacheInit = 0;
95442  }
95443  if( sqlite3GlobalConfig.isMallocInit ){
95444    sqlite3MallocEnd();
95445    sqlite3GlobalConfig.isMallocInit = 0;
95446  }
95447  if( sqlite3GlobalConfig.isMutexInit ){
95448    sqlite3MutexEnd();
95449    sqlite3GlobalConfig.isMutexInit = 0;
95450  }
95451
95452  return SQLITE_OK;
95453}
95454
95455/*
95456** This API allows applications to modify the global configuration of
95457** the SQLite library at run-time.
95458**
95459** This routine should only be called when there are no outstanding
95460** database connections or memory allocations.  This routine is not
95461** threadsafe.  Failure to heed these warnings can lead to unpredictable
95462** behavior.
95463*/
95464SQLITE_API int sqlite3_config(int op, ...){
95465  va_list ap;
95466  int rc = SQLITE_OK;
95467
95468  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
95469  ** the SQLite library is in use. */
95470  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE;
95471
95472  va_start(ap, op);
95473  switch( op ){
95474
95475    /* Mutex configuration options are only available in a threadsafe
95476    ** compile.
95477    */
95478#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
95479    case SQLITE_CONFIG_SINGLETHREAD: {
95480      /* Disable all mutexing */
95481      sqlite3GlobalConfig.bCoreMutex = 0;
95482      sqlite3GlobalConfig.bFullMutex = 0;
95483      break;
95484    }
95485    case SQLITE_CONFIG_MULTITHREAD: {
95486      /* Disable mutexing of database connections */
95487      /* Enable mutexing of core data structures */
95488      sqlite3GlobalConfig.bCoreMutex = 1;
95489      sqlite3GlobalConfig.bFullMutex = 0;
95490      break;
95491    }
95492    case SQLITE_CONFIG_SERIALIZED: {
95493      /* Enable all mutexing */
95494      sqlite3GlobalConfig.bCoreMutex = 1;
95495      sqlite3GlobalConfig.bFullMutex = 1;
95496      break;
95497    }
95498    case SQLITE_CONFIG_MUTEX: {
95499      /* Specify an alternative mutex implementation */
95500      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
95501      break;
95502    }
95503    case SQLITE_CONFIG_GETMUTEX: {
95504      /* Retrieve the current mutex implementation */
95505      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
95506      break;
95507    }
95508#endif
95509
95510
95511    case SQLITE_CONFIG_MALLOC: {
95512      /* Specify an alternative malloc implementation */
95513      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
95514      break;
95515    }
95516    case SQLITE_CONFIG_GETMALLOC: {
95517      /* Retrieve the current malloc() implementation */
95518      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
95519      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
95520      break;
95521    }
95522    case SQLITE_CONFIG_MEMSTATUS: {
95523      /* Enable or disable the malloc status collection */
95524      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
95525      break;
95526    }
95527    case SQLITE_CONFIG_SCRATCH: {
95528      /* Designate a buffer for scratch memory space */
95529      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
95530      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
95531      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
95532      break;
95533    }
95534    case SQLITE_CONFIG_PAGECACHE: {
95535      /* Designate a buffer for page cache memory space */
95536      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
95537      sqlite3GlobalConfig.szPage = va_arg(ap, int);
95538      sqlite3GlobalConfig.nPage = va_arg(ap, int);
95539      break;
95540    }
95541
95542    case SQLITE_CONFIG_PCACHE: {
95543      /* Specify an alternative page cache implementation */
95544      sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
95545      break;
95546    }
95547
95548    case SQLITE_CONFIG_GETPCACHE: {
95549      if( sqlite3GlobalConfig.pcache.xInit==0 ){
95550        sqlite3PCacheSetDefault();
95551      }
95552      *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
95553      break;
95554    }
95555
95556#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
95557    case SQLITE_CONFIG_HEAP: {
95558      /* Designate a buffer for heap memory space */
95559      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
95560      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
95561      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
95562
95563      if( sqlite3GlobalConfig.pHeap==0 ){
95564        /* If the heap pointer is NULL, then restore the malloc implementation
95565        ** back to NULL pointers too.  This will cause the malloc to go
95566        ** back to its default implementation when sqlite3_initialize() is
95567        ** run.
95568        */
95569        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
95570      }else{
95571        /* The heap pointer is not NULL, then install one of the
95572        ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
95573        ** ENABLE_MEMSYS5 is defined, return an error.
95574        */
95575#ifdef SQLITE_ENABLE_MEMSYS3
95576        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
95577#endif
95578#ifdef SQLITE_ENABLE_MEMSYS5
95579        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
95580#endif
95581      }
95582      break;
95583    }
95584#endif
95585
95586    case SQLITE_CONFIG_LOOKASIDE: {
95587      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
95588      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
95589      break;
95590    }
95591
95592    default: {
95593      rc = SQLITE_ERROR;
95594      break;
95595    }
95596  }
95597  va_end(ap);
95598  return rc;
95599}
95600
95601/*
95602** Set up the lookaside buffers for a database connection.
95603** Return SQLITE_OK on success.
95604** If lookaside is already active, return SQLITE_BUSY.
95605**
95606** The sz parameter is the number of bytes in each lookaside slot.
95607** The cnt parameter is the number of slots.  If pStart is NULL the
95608** space for the lookaside memory is obtained from sqlite3_malloc().
95609** If pStart is not NULL then it is sz*cnt bytes of memory to use for
95610** the lookaside memory.
95611*/
95612static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
95613  void *pStart;
95614  if( db->lookaside.nOut ){
95615    return SQLITE_BUSY;
95616  }
95617  /* Free any existing lookaside buffer for this handle before
95618  ** allocating a new one so we don't have to have space for
95619  ** both at the same time.
95620  */
95621  if( db->lookaside.bMalloced ){
95622    sqlite3_free(db->lookaside.pStart);
95623  }
95624  /* The size of a lookaside slot needs to be larger than a pointer
95625  ** to be useful.
95626  */
95627  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
95628  if( cnt<0 ) cnt = 0;
95629  if( sz==0 || cnt==0 ){
95630    sz = 0;
95631    pStart = 0;
95632  }else if( pBuf==0 ){
95633    sz = ROUND8(sz);
95634    sqlite3BeginBenignMalloc();
95635    pStart = sqlite3Malloc( sz*cnt );
95636    sqlite3EndBenignMalloc();
95637  }else{
95638    sz = ROUNDDOWN8(sz);
95639    pStart = pBuf;
95640  }
95641  db->lookaside.pStart = pStart;
95642  db->lookaside.pFree = 0;
95643  db->lookaside.sz = (u16)sz;
95644  if( pStart ){
95645    int i;
95646    LookasideSlot *p;
95647    assert( sz > (int)sizeof(LookasideSlot*) );
95648    p = (LookasideSlot*)pStart;
95649    for(i=cnt-1; i>=0; i--){
95650      p->pNext = db->lookaside.pFree;
95651      db->lookaside.pFree = p;
95652      p = (LookasideSlot*)&((u8*)p)[sz];
95653    }
95654    db->lookaside.pEnd = p;
95655    db->lookaside.bEnabled = 1;
95656    db->lookaside.bMalloced = pBuf==0 ?1:0;
95657  }else{
95658    db->lookaside.pEnd = 0;
95659    db->lookaside.bEnabled = 0;
95660    db->lookaside.bMalloced = 0;
95661  }
95662  return SQLITE_OK;
95663}
95664
95665/*
95666** Return the mutex associated with a database connection.
95667*/
95668SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
95669  return db->mutex;
95670}
95671
95672/*
95673** Configuration settings for an individual database connection
95674*/
95675SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
95676  va_list ap;
95677  int rc;
95678  va_start(ap, op);
95679  switch( op ){
95680    case SQLITE_DBCONFIG_LOOKASIDE: {
95681      void *pBuf = va_arg(ap, void*);
95682      int sz = va_arg(ap, int);
95683      int cnt = va_arg(ap, int);
95684      rc = setupLookaside(db, pBuf, sz, cnt);
95685      break;
95686    }
95687    default: {
95688      rc = SQLITE_ERROR;
95689      break;
95690    }
95691  }
95692  va_end(ap);
95693  return rc;
95694}
95695
95696
95697/*
95698** Return true if the buffer z[0..n-1] contains all spaces.
95699*/
95700static int allSpaces(const char *z, int n){
95701  while( n>0 && z[n-1]==' ' ){ n--; }
95702  return n==0;
95703}
95704
95705/*
95706** This is the default collating function named "BINARY" which is always
95707** available.
95708**
95709** If the padFlag argument is not NULL then space padding at the end
95710** of strings is ignored.  This implements the RTRIM collation.
95711*/
95712static int binCollFunc(
95713  void *padFlag,
95714  int nKey1, const void *pKey1,
95715  int nKey2, const void *pKey2
95716){
95717  int rc, n;
95718  n = nKey1<nKey2 ? nKey1 : nKey2;
95719  rc = memcmp(pKey1, pKey2, n);
95720  if( rc==0 ){
95721    if( padFlag
95722     && allSpaces(((char*)pKey1)+n, nKey1-n)
95723     && allSpaces(((char*)pKey2)+n, nKey2-n)
95724    ){
95725      /* Leave rc unchanged at 0 */
95726    }else{
95727      rc = nKey1 - nKey2;
95728    }
95729  }
95730  return rc;
95731}
95732
95733/*
95734** Another built-in collating sequence: NOCASE.
95735**
95736** This collating sequence is intended to be used for "case independant
95737** comparison". SQLite's knowledge of upper and lower case equivalents
95738** extends only to the 26 characters used in the English language.
95739**
95740** At the moment there is only a UTF-8 implementation.
95741*/
95742static int nocaseCollatingFunc(
95743  void *NotUsed,
95744  int nKey1, const void *pKey1,
95745  int nKey2, const void *pKey2
95746){
95747  int r = sqlite3StrNICmp(
95748      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
95749  UNUSED_PARAMETER(NotUsed);
95750  if( 0==r ){
95751    r = nKey1-nKey2;
95752  }
95753  return r;
95754}
95755
95756/*
95757** Return the ROWID of the most recent insert
95758*/
95759SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
95760  return db->lastRowid;
95761}
95762
95763/*
95764** Return the number of changes in the most recent call to sqlite3_exec().
95765*/
95766SQLITE_API int sqlite3_changes(sqlite3 *db){
95767  return db->nChange;
95768}
95769
95770/*
95771** Return the number of changes since the database handle was opened.
95772*/
95773SQLITE_API int sqlite3_total_changes(sqlite3 *db){
95774  return db->nTotalChange;
95775}
95776
95777/*
95778** Close all open savepoints. This function only manipulates fields of the
95779** database handle object, it does not close any savepoints that may be open
95780** at the b-tree/pager level.
95781*/
95782SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
95783  while( db->pSavepoint ){
95784    Savepoint *pTmp = db->pSavepoint;
95785    db->pSavepoint = pTmp->pNext;
95786    sqlite3DbFree(db, pTmp);
95787  }
95788  db->nSavepoint = 0;
95789  db->nStatement = 0;
95790  db->isTransactionSavepoint = 0;
95791}
95792
95793/*
95794** Close an existing SQLite database
95795*/
95796SQLITE_API int sqlite3_close(sqlite3 *db){
95797  HashElem *i;
95798  int j;
95799
95800  if( !db ){
95801    return SQLITE_OK;
95802  }
95803  if( !sqlite3SafetyCheckSickOrOk(db) ){
95804    return SQLITE_MISUSE;
95805  }
95806  sqlite3_mutex_enter(db->mutex);
95807
95808  sqlite3ResetInternalSchema(db, 0);
95809
95810  /* If a transaction is open, the ResetInternalSchema() call above
95811  ** will not have called the xDisconnect() method on any virtual
95812  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
95813  ** call will do so. We need to do this before the check for active
95814  ** SQL statements below, as the v-table implementation may be storing
95815  ** some prepared statements internally.
95816  */
95817  sqlite3VtabRollback(db);
95818
95819  /* If there are any outstanding VMs, return SQLITE_BUSY. */
95820  if( db->pVdbe ){
95821    sqlite3Error(db, SQLITE_BUSY,
95822        "unable to close due to unfinalised statements");
95823    sqlite3_mutex_leave(db->mutex);
95824    return SQLITE_BUSY;
95825  }
95826  assert( sqlite3SafetyCheckSickOrOk(db) );
95827
95828  for(j=0; j<db->nDb; j++){
95829    Btree *pBt = db->aDb[j].pBt;
95830    if( pBt && sqlite3BtreeIsInBackup(pBt) ){
95831      sqlite3Error(db, SQLITE_BUSY,
95832          "unable to close due to unfinished backup operation");
95833      sqlite3_mutex_leave(db->mutex);
95834      return SQLITE_BUSY;
95835    }
95836  }
95837
95838  /* Free any outstanding Savepoint structures. */
95839  sqlite3CloseSavepoints(db);
95840
95841  for(j=0; j<db->nDb; j++){
95842    struct Db *pDb = &db->aDb[j];
95843    if( pDb->pBt ){
95844      sqlite3BtreeClose(pDb->pBt);
95845      pDb->pBt = 0;
95846      if( j!=1 ){
95847        pDb->pSchema = 0;
95848      }
95849    }
95850  }
95851  sqlite3ResetInternalSchema(db, 0);
95852
95853  /* Tell the code in notify.c that the connection no longer holds any
95854  ** locks and does not require any further unlock-notify callbacks.
95855  */
95856  sqlite3ConnectionClosed(db);
95857
95858  assert( db->nDb<=2 );
95859  assert( db->aDb==db->aDbStatic );
95860  for(j=0; j<ArraySize(db->aFunc.a); j++){
95861    FuncDef *pNext, *pHash, *p;
95862    for(p=db->aFunc.a[j]; p; p=pHash){
95863      pHash = p->pHash;
95864      while( p ){
95865        pNext = p->pNext;
95866        sqlite3DbFree(db, p);
95867        p = pNext;
95868      }
95869    }
95870  }
95871  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
95872    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
95873    /* Invoke any destructors registered for collation sequence user data. */
95874    for(j=0; j<3; j++){
95875      if( pColl[j].xDel ){
95876        pColl[j].xDel(pColl[j].pUser);
95877      }
95878    }
95879    sqlite3DbFree(db, pColl);
95880  }
95881  sqlite3HashClear(&db->aCollSeq);
95882#ifndef SQLITE_OMIT_VIRTUALTABLE
95883  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
95884    Module *pMod = (Module *)sqliteHashData(i);
95885    if( pMod->xDestroy ){
95886      pMod->xDestroy(pMod->pAux);
95887    }
95888    sqlite3DbFree(db, pMod);
95889  }
95890  sqlite3HashClear(&db->aModule);
95891#endif
95892
95893  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
95894  if( db->pErr ){
95895    sqlite3ValueFree(db->pErr);
95896  }
95897  sqlite3CloseExtensions(db);
95898
95899  db->magic = SQLITE_MAGIC_ERROR;
95900
95901  /* The temp-database schema is allocated differently from the other schema
95902  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
95903  ** So it needs to be freed here. Todo: Why not roll the temp schema into
95904  ** the same sqliteMalloc() as the one that allocates the database
95905  ** structure?
95906  */
95907  sqlite3DbFree(db, db->aDb[1].pSchema);
95908  sqlite3_mutex_leave(db->mutex);
95909  db->magic = SQLITE_MAGIC_CLOSED;
95910  sqlite3_mutex_free(db->mutex);
95911  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
95912  if( db->lookaside.bMalloced ){
95913    sqlite3_free(db->lookaside.pStart);
95914  }
95915  sqlite3_free(db);
95916  return SQLITE_OK;
95917}
95918
95919/*
95920** Rollback all database files.
95921*/
95922SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
95923  int i;
95924  int inTrans = 0;
95925  assert( sqlite3_mutex_held(db->mutex) );
95926  sqlite3BeginBenignMalloc();
95927  for(i=0; i<db->nDb; i++){
95928    if( db->aDb[i].pBt ){
95929      if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
95930        inTrans = 1;
95931      }
95932      sqlite3BtreeRollback(db->aDb[i].pBt);
95933      db->aDb[i].inTrans = 0;
95934    }
95935  }
95936  sqlite3VtabRollback(db);
95937  sqlite3EndBenignMalloc();
95938
95939  if( db->flags&SQLITE_InternChanges ){
95940    sqlite3ExpirePreparedStatements(db);
95941    sqlite3ResetInternalSchema(db, 0);
95942  }
95943
95944  /* Any deferred constraint violations have now been resolved. */
95945  db->nDeferredCons = 0;
95946
95947  /* If one has been configured, invoke the rollback-hook callback */
95948  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
95949    db->xRollbackCallback(db->pRollbackArg);
95950  }
95951}
95952
95953/*
95954** Return a static string that describes the kind of error specified in the
95955** argument.
95956*/
95957SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
95958  static const char* const aMsg[] = {
95959    /* SQLITE_OK          */ "not an error",
95960    /* SQLITE_ERROR       */ "SQL logic error or missing database",
95961    /* SQLITE_INTERNAL    */ 0,
95962    /* SQLITE_PERM        */ "access permission denied",
95963    /* SQLITE_ABORT       */ "callback requested query abort",
95964    /* SQLITE_BUSY        */ "database is locked",
95965    /* SQLITE_LOCKED      */ "database table is locked",
95966    /* SQLITE_NOMEM       */ "out of memory",
95967    /* SQLITE_READONLY    */ "attempt to write a readonly database",
95968    /* SQLITE_INTERRUPT   */ "interrupted",
95969    /* SQLITE_IOERR       */ "disk I/O error",
95970    /* SQLITE_CORRUPT     */ "database disk image is malformed",
95971    /* SQLITE_NOTFOUND    */ 0,
95972    /* SQLITE_FULL        */ "database or disk is full",
95973    /* SQLITE_CANTOPEN    */ "unable to open database file",
95974    /* SQLITE_PROTOCOL    */ 0,
95975    /* SQLITE_EMPTY       */ "table contains no data",
95976    /* SQLITE_SCHEMA      */ "database schema has changed",
95977    /* SQLITE_TOOBIG      */ "string or blob too big",
95978    /* SQLITE_CONSTRAINT  */ "constraint failed",
95979    /* SQLITE_MISMATCH    */ "datatype mismatch",
95980    /* SQLITE_MISUSE      */ "library routine called out of sequence",
95981    /* SQLITE_NOLFS       */ "large file support is disabled",
95982    /* SQLITE_AUTH        */ "authorization denied",
95983    /* SQLITE_FORMAT      */ "auxiliary database format error",
95984    /* SQLITE_RANGE       */ "bind or column index out of range",
95985    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
95986  };
95987  rc &= 0xff;
95988  if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
95989    return aMsg[rc];
95990  }else{
95991    return "unknown error";
95992  }
95993}
95994
95995/*
95996** This routine implements a busy callback that sleeps and tries
95997** again until a timeout value is reached.  The timeout value is
95998** an integer number of milliseconds passed in as the first
95999** argument.
96000*/
96001static int sqliteDefaultBusyCallback(
96002 void *ptr,               /* Database connection */
96003 int count                /* Number of times table has been busy */
96004){
96005#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
96006  static const u8 delays[] =
96007     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
96008  static const u8 totals[] =
96009     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
96010# define NDELAY (sizeof(delays)/sizeof(delays[0]))
96011  sqlite3 *db = (sqlite3 *)ptr;
96012  int timeout = db->busyTimeout;
96013  int delay, prior;
96014
96015  assert( count>=0 );
96016  if( count < NDELAY ){
96017    delay = delays[count];
96018    prior = totals[count];
96019  }else{
96020    delay = delays[NDELAY-1];
96021    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
96022  }
96023  if( prior + delay > timeout ){
96024    delay = timeout - prior;
96025    if( delay<=0 ) return 0;
96026  }
96027  sqlite3OsSleep(db->pVfs, delay*1000);
96028  return 1;
96029#else
96030  sqlite3 *db = (sqlite3 *)ptr;
96031  int timeout = ((sqlite3 *)ptr)->busyTimeout;
96032  if( (count+1)*1000 > timeout ){
96033    return 0;
96034  }
96035  sqlite3OsSleep(db->pVfs, 1000000);
96036  return 1;
96037#endif
96038}
96039
96040/*
96041** Invoke the given busy handler.
96042**
96043** This routine is called when an operation failed with a lock.
96044** If this routine returns non-zero, the lock is retried.  If it
96045** returns 0, the operation aborts with an SQLITE_BUSY error.
96046*/
96047SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
96048  int rc;
96049  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
96050  rc = p->xFunc(p->pArg, p->nBusy);
96051  if( rc==0 ){
96052    p->nBusy = -1;
96053  }else{
96054    p->nBusy++;
96055  }
96056  return rc;
96057}
96058
96059/*
96060** This routine sets the busy callback for an Sqlite database to the
96061** given callback function with the given argument.
96062*/
96063SQLITE_API int sqlite3_busy_handler(
96064  sqlite3 *db,
96065  int (*xBusy)(void*,int),
96066  void *pArg
96067){
96068  sqlite3_mutex_enter(db->mutex);
96069  db->busyHandler.xFunc = xBusy;
96070  db->busyHandler.pArg = pArg;
96071  db->busyHandler.nBusy = 0;
96072  sqlite3_mutex_leave(db->mutex);
96073  return SQLITE_OK;
96074}
96075
96076#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
96077/*
96078** This routine sets the progress callback for an Sqlite database to the
96079** given callback function with the given argument. The progress callback will
96080** be invoked every nOps opcodes.
96081*/
96082SQLITE_API void sqlite3_progress_handler(
96083  sqlite3 *db,
96084  int nOps,
96085  int (*xProgress)(void*),
96086  void *pArg
96087){
96088  sqlite3_mutex_enter(db->mutex);
96089  if( nOps>0 ){
96090    db->xProgress = xProgress;
96091    db->nProgressOps = nOps;
96092    db->pProgressArg = pArg;
96093  }else{
96094    db->xProgress = 0;
96095    db->nProgressOps = 0;
96096    db->pProgressArg = 0;
96097  }
96098  sqlite3_mutex_leave(db->mutex);
96099}
96100#endif
96101
96102
96103/*
96104** This routine installs a default busy handler that waits for the
96105** specified number of milliseconds before returning 0.
96106*/
96107SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
96108  if( ms>0 ){
96109    db->busyTimeout = ms;
96110    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
96111  }else{
96112    sqlite3_busy_handler(db, 0, 0);
96113  }
96114  return SQLITE_OK;
96115}
96116
96117/*
96118** Cause any pending operation to stop at its earliest opportunity.
96119*/
96120SQLITE_API void sqlite3_interrupt(sqlite3 *db){
96121  db->u1.isInterrupted = 1;
96122}
96123
96124
96125/*
96126** This function is exactly the same as sqlite3_create_function(), except
96127** that it is designed to be called by internal code. The difference is
96128** that if a malloc() fails in sqlite3_create_function(), an error code
96129** is returned and the mallocFailed flag cleared.
96130*/
96131SQLITE_PRIVATE int sqlite3CreateFunc(
96132  sqlite3 *db,
96133  const char *zFunctionName,
96134  int nArg,
96135  int enc,
96136  void *pUserData,
96137  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
96138  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
96139  void (*xFinal)(sqlite3_context*)
96140){
96141  FuncDef *p;
96142  int nName;
96143
96144  assert( sqlite3_mutex_held(db->mutex) );
96145  if( zFunctionName==0 ||
96146      (xFunc && (xFinal || xStep)) ||
96147      (!xFunc && (xFinal && !xStep)) ||
96148      (!xFunc && (!xFinal && xStep)) ||
96149      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
96150      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
96151    return SQLITE_MISUSE;
96152  }
96153
96154#ifndef SQLITE_OMIT_UTF16
96155  /* If SQLITE_UTF16 is specified as the encoding type, transform this
96156  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
96157  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
96158  **
96159  ** If SQLITE_ANY is specified, add three versions of the function
96160  ** to the hash table.
96161  */
96162  if( enc==SQLITE_UTF16 ){
96163    enc = SQLITE_UTF16NATIVE;
96164  }else if( enc==SQLITE_ANY ){
96165    int rc;
96166    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
96167         pUserData, xFunc, xStep, xFinal);
96168    if( rc==SQLITE_OK ){
96169      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
96170          pUserData, xFunc, xStep, xFinal);
96171    }
96172    if( rc!=SQLITE_OK ){
96173      return rc;
96174    }
96175    enc = SQLITE_UTF16BE;
96176  }
96177#else
96178  enc = SQLITE_UTF8;
96179#endif
96180
96181  /* Check if an existing function is being overridden or deleted. If so,
96182  ** and there are active VMs, then return SQLITE_BUSY. If a function
96183  ** is being overridden/deleted but there are no active VMs, allow the
96184  ** operation to continue but invalidate all precompiled statements.
96185  */
96186  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
96187  if( p && p->iPrefEnc==enc && p->nArg==nArg ){
96188    if( db->activeVdbeCnt ){
96189      sqlite3Error(db, SQLITE_BUSY,
96190        "unable to delete/modify user-function due to active statements");
96191      assert( !db->mallocFailed );
96192      return SQLITE_BUSY;
96193    }else{
96194      sqlite3ExpirePreparedStatements(db);
96195    }
96196  }
96197
96198  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
96199  assert(p || db->mallocFailed);
96200  if( !p ){
96201    return SQLITE_NOMEM;
96202  }
96203  p->flags = 0;
96204  p->xFunc = xFunc;
96205  p->xStep = xStep;
96206  p->xFinalize = xFinal;
96207  p->pUserData = pUserData;
96208  p->nArg = (u16)nArg;
96209  return SQLITE_OK;
96210}
96211
96212/*
96213** Create new user functions.
96214*/
96215SQLITE_API int sqlite3_create_function(
96216  sqlite3 *db,
96217  const char *zFunctionName,
96218  int nArg,
96219  int enc,
96220  void *p,
96221  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
96222  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
96223  void (*xFinal)(sqlite3_context*)
96224){
96225  int rc;
96226  sqlite3_mutex_enter(db->mutex);
96227  rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
96228  rc = sqlite3ApiExit(db, rc);
96229  sqlite3_mutex_leave(db->mutex);
96230  return rc;
96231}
96232
96233#ifndef SQLITE_OMIT_UTF16
96234SQLITE_API int sqlite3_create_function16(
96235  sqlite3 *db,
96236  const void *zFunctionName,
96237  int nArg,
96238  int eTextRep,
96239  void *p,
96240  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
96241  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
96242  void (*xFinal)(sqlite3_context*)
96243){
96244  int rc;
96245  char *zFunc8;
96246  sqlite3_mutex_enter(db->mutex);
96247  assert( !db->mallocFailed );
96248  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1);
96249  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
96250  sqlite3DbFree(db, zFunc8);
96251  rc = sqlite3ApiExit(db, rc);
96252  sqlite3_mutex_leave(db->mutex);
96253  return rc;
96254}
96255#endif
96256
96257
96258/*
96259** Declare that a function has been overloaded by a virtual table.
96260**
96261** If the function already exists as a regular global function, then
96262** this routine is a no-op.  If the function does not exist, then create
96263** a new one that always throws a run-time error.
96264**
96265** When virtual tables intend to provide an overloaded function, they
96266** should call this routine to make sure the global function exists.
96267** A global function must exist in order for name resolution to work
96268** properly.
96269*/
96270SQLITE_API int sqlite3_overload_function(
96271  sqlite3 *db,
96272  const char *zName,
96273  int nArg
96274){
96275  int nName = sqlite3Strlen30(zName);
96276  int rc;
96277  sqlite3_mutex_enter(db->mutex);
96278  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
96279    sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
96280                      0, sqlite3InvalidFunction, 0, 0);
96281  }
96282  rc = sqlite3ApiExit(db, SQLITE_OK);
96283  sqlite3_mutex_leave(db->mutex);
96284  return rc;
96285}
96286
96287#ifndef SQLITE_OMIT_TRACE
96288/*
96289** Register a trace function.  The pArg from the previously registered trace
96290** is returned.
96291**
96292** A NULL trace function means that no tracing is executes.  A non-NULL
96293** trace is a pointer to a function that is invoked at the start of each
96294** SQL statement.
96295*/
96296SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
96297  void *pOld;
96298  sqlite3_mutex_enter(db->mutex);
96299  pOld = db->pTraceArg;
96300  db->xTrace = xTrace;
96301  db->pTraceArg = pArg;
96302  sqlite3_mutex_leave(db->mutex);
96303  return pOld;
96304}
96305/*
96306** Register a profile function.  The pArg from the previously registered
96307** profile function is returned.
96308**
96309** A NULL profile function means that no profiling is executes.  A non-NULL
96310** profile is a pointer to a function that is invoked at the conclusion of
96311** each SQL statement that is run.
96312*/
96313SQLITE_API void *sqlite3_profile(
96314  sqlite3 *db,
96315  void (*xProfile)(void*,const char*,sqlite_uint64),
96316  void *pArg
96317){
96318  void *pOld;
96319  sqlite3_mutex_enter(db->mutex);
96320  pOld = db->pProfileArg;
96321  db->xProfile = xProfile;
96322  db->pProfileArg = pArg;
96323  sqlite3_mutex_leave(db->mutex);
96324  return pOld;
96325}
96326#endif /* SQLITE_OMIT_TRACE */
96327
96328/*** EXPERIMENTAL ***
96329**
96330** Register a function to be invoked when a transaction comments.
96331** If the invoked function returns non-zero, then the commit becomes a
96332** rollback.
96333*/
96334SQLITE_API void *sqlite3_commit_hook(
96335  sqlite3 *db,              /* Attach the hook to this database */
96336  int (*xCallback)(void*),  /* Function to invoke on each commit */
96337  void *pArg                /* Argument to the function */
96338){
96339  void *pOld;
96340  sqlite3_mutex_enter(db->mutex);
96341  pOld = db->pCommitArg;
96342  db->xCommitCallback = xCallback;
96343  db->pCommitArg = pArg;
96344  sqlite3_mutex_leave(db->mutex);
96345  return pOld;
96346}
96347
96348/*
96349** Register a callback to be invoked each time a row is updated,
96350** inserted or deleted using this database connection.
96351*/
96352SQLITE_API void *sqlite3_update_hook(
96353  sqlite3 *db,              /* Attach the hook to this database */
96354  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
96355  void *pArg                /* Argument to the function */
96356){
96357  void *pRet;
96358  sqlite3_mutex_enter(db->mutex);
96359  pRet = db->pUpdateArg;
96360  db->xUpdateCallback = xCallback;
96361  db->pUpdateArg = pArg;
96362  sqlite3_mutex_leave(db->mutex);
96363  return pRet;
96364}
96365
96366/*
96367** Register a callback to be invoked each time a transaction is rolled
96368** back by this database connection.
96369*/
96370SQLITE_API void *sqlite3_rollback_hook(
96371  sqlite3 *db,              /* Attach the hook to this database */
96372  void (*xCallback)(void*), /* Callback function */
96373  void *pArg                /* Argument to the function */
96374){
96375  void *pRet;
96376  sqlite3_mutex_enter(db->mutex);
96377  pRet = db->pRollbackArg;
96378  db->xRollbackCallback = xCallback;
96379  db->pRollbackArg = pArg;
96380  sqlite3_mutex_leave(db->mutex);
96381  return pRet;
96382}
96383
96384/*
96385** This function returns true if main-memory should be used instead of
96386** a temporary file for transient pager files and statement journals.
96387** The value returned depends on the value of db->temp_store (runtime
96388** parameter) and the compile time value of SQLITE_TEMP_STORE. The
96389** following table describes the relationship between these two values
96390** and this functions return value.
96391**
96392**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
96393**   -----------------     --------------     ------------------------------
96394**   0                     any                file      (return 0)
96395**   1                     1                  file      (return 0)
96396**   1                     2                  memory    (return 1)
96397**   1                     0                  file      (return 0)
96398**   2                     1                  file      (return 0)
96399**   2                     2                  memory    (return 1)
96400**   2                     0                  memory    (return 1)
96401**   3                     any                memory    (return 1)
96402*/
96403SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
96404#if SQLITE_TEMP_STORE==1
96405  return ( db->temp_store==2 );
96406#endif
96407#if SQLITE_TEMP_STORE==2
96408  return ( db->temp_store!=1 );
96409#endif
96410#if SQLITE_TEMP_STORE==3
96411  return 1;
96412#endif
96413#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
96414  return 0;
96415#endif
96416}
96417
96418/*
96419** This routine is called to create a connection to a database BTree
96420** driver.  If zFilename is the name of a file, then that file is
96421** opened and used.  If zFilename is the magic name ":memory:" then
96422** the database is stored in memory (and is thus forgotten as soon as
96423** the connection is closed.)  If zFilename is NULL then the database
96424** is a "virtual" database for transient use only and is deleted as
96425** soon as the connection is closed.
96426**
96427** A virtual database can be either a disk file (that is automatically
96428** deleted when the file is closed) or it an be held entirely in memory.
96429** The sqlite3TempInMemory() function is used to determine which.
96430*/
96431SQLITE_PRIVATE int sqlite3BtreeFactory(
96432  sqlite3 *db,              /* Main database when opening aux otherwise 0 */
96433  const char *zFilename,    /* Name of the file containing the BTree database */
96434  int omitJournal,          /* if TRUE then do not journal this file */
96435  int nCache,               /* How many pages in the page cache */
96436  int vfsFlags,             /* Flags passed through to vfsOpen */
96437  Btree **ppBtree           /* Pointer to new Btree object written here */
96438){
96439  int btFlags = 0;
96440  int rc;
96441
96442  assert( sqlite3_mutex_held(db->mutex) );
96443  assert( ppBtree != 0);
96444  if( omitJournal ){
96445    btFlags |= BTREE_OMIT_JOURNAL;
96446  }
96447  if( db->flags & SQLITE_NoReadlock ){
96448    btFlags |= BTREE_NO_READLOCK;
96449  }
96450#ifndef SQLITE_OMIT_MEMORYDB
96451  if( zFilename==0 && sqlite3TempInMemory(db) ){
96452    zFilename = ":memory:";
96453  }
96454#endif
96455
96456  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
96457    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
96458  }
96459  rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
96460
96461  /* If the B-Tree was successfully opened, set the pager-cache size to the
96462  ** default value. Except, if the call to BtreeOpen() returned a handle
96463  ** open on an existing shared pager-cache, do not change the pager-cache
96464  ** size.
96465  */
96466  if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
96467    sqlite3BtreeSetCacheSize(*ppBtree, nCache);
96468  }
96469  return rc;
96470}
96471
96472/*
96473** Return UTF-8 encoded English language explanation of the most recent
96474** error.
96475*/
96476SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
96477  const char *z;
96478  if( !db ){
96479    return sqlite3ErrStr(SQLITE_NOMEM);
96480  }
96481  if( !sqlite3SafetyCheckSickOrOk(db) ){
96482    return sqlite3ErrStr(SQLITE_MISUSE);
96483  }
96484  sqlite3_mutex_enter(db->mutex);
96485  if( db->mallocFailed ){
96486    z = sqlite3ErrStr(SQLITE_NOMEM);
96487  }else{
96488    z = (char*)sqlite3_value_text(db->pErr);
96489    assert( !db->mallocFailed );
96490    if( z==0 ){
96491      z = sqlite3ErrStr(db->errCode);
96492    }
96493  }
96494  sqlite3_mutex_leave(db->mutex);
96495  return z;
96496}
96497
96498#ifndef SQLITE_OMIT_UTF16
96499/*
96500** Return UTF-16 encoded English language explanation of the most recent
96501** error.
96502*/
96503SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
96504  static const u16 outOfMem[] = {
96505    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
96506  };
96507  static const u16 misuse[] = {
96508    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
96509    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
96510    'c', 'a', 'l', 'l', 'e', 'd', ' ',
96511    'o', 'u', 't', ' ',
96512    'o', 'f', ' ',
96513    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
96514  };
96515
96516  const void *z;
96517  if( !db ){
96518    return (void *)outOfMem;
96519  }
96520  if( !sqlite3SafetyCheckSickOrOk(db) ){
96521    return (void *)misuse;
96522  }
96523  sqlite3_mutex_enter(db->mutex);
96524  if( db->mallocFailed ){
96525    z = (void *)outOfMem;
96526  }else{
96527    z = sqlite3_value_text16(db->pErr);
96528    if( z==0 ){
96529      sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
96530           SQLITE_UTF8, SQLITE_STATIC);
96531      z = sqlite3_value_text16(db->pErr);
96532    }
96533    /* A malloc() may have failed within the call to sqlite3_value_text16()
96534    ** above. If this is the case, then the db->mallocFailed flag needs to
96535    ** be cleared before returning. Do this directly, instead of via
96536    ** sqlite3ApiExit(), to avoid setting the database handle error message.
96537    */
96538    db->mallocFailed = 0;
96539  }
96540  sqlite3_mutex_leave(db->mutex);
96541  return z;
96542}
96543#endif /* SQLITE_OMIT_UTF16 */
96544
96545/*
96546** Return the most recent error code generated by an SQLite routine. If NULL is
96547** passed to this function, we assume a malloc() failed during sqlite3_open().
96548*/
96549SQLITE_API int sqlite3_errcode(sqlite3 *db){
96550  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
96551    return SQLITE_MISUSE;
96552  }
96553  if( !db || db->mallocFailed ){
96554    return SQLITE_NOMEM;
96555  }
96556  return db->errCode & db->errMask;
96557}
96558SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
96559  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
96560    return SQLITE_MISUSE;
96561  }
96562  if( !db || db->mallocFailed ){
96563    return SQLITE_NOMEM;
96564  }
96565  return db->errCode;
96566}
96567
96568/*
96569** Create a new collating function for database "db".  The name is zName
96570** and the encoding is enc.
96571*/
96572static int createCollation(
96573  sqlite3* db,
96574  const char *zName,
96575  u8 enc,
96576  u8 collType,
96577  void* pCtx,
96578  int(*xCompare)(void*,int,const void*,int,const void*),
96579  void(*xDel)(void*)
96580){
96581  CollSeq *pColl;
96582  int enc2;
96583  int nName = sqlite3Strlen30(zName);
96584
96585  assert( sqlite3_mutex_held(db->mutex) );
96586
96587  /* If SQLITE_UTF16 is specified as the encoding type, transform this
96588  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
96589  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
96590  */
96591  enc2 = enc;
96592  testcase( enc2==SQLITE_UTF16 );
96593  testcase( enc2==SQLITE_UTF16_ALIGNED );
96594  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
96595    enc2 = SQLITE_UTF16NATIVE;
96596  }
96597  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
96598    return SQLITE_MISUSE;
96599  }
96600
96601  /* Check if this call is removing or replacing an existing collation
96602  ** sequence. If so, and there are active VMs, return busy. If there
96603  ** are no active VMs, invalidate any pre-compiled statements.
96604  */
96605  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
96606  if( pColl && pColl->xCmp ){
96607    if( db->activeVdbeCnt ){
96608      sqlite3Error(db, SQLITE_BUSY,
96609        "unable to delete/modify collation sequence due to active statements");
96610      return SQLITE_BUSY;
96611    }
96612    sqlite3ExpirePreparedStatements(db);
96613
96614    /* If collation sequence pColl was created directly by a call to
96615    ** sqlite3_create_collation, and not generated by synthCollSeq(),
96616    ** then any copies made by synthCollSeq() need to be invalidated.
96617    ** Also, collation destructor - CollSeq.xDel() - function may need
96618    ** to be called.
96619    */
96620    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
96621      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
96622      int j;
96623      for(j=0; j<3; j++){
96624        CollSeq *p = &aColl[j];
96625        if( p->enc==pColl->enc ){
96626          if( p->xDel ){
96627            p->xDel(p->pUser);
96628          }
96629          p->xCmp = 0;
96630        }
96631      }
96632    }
96633  }
96634
96635  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
96636  if( pColl ){
96637    pColl->xCmp = xCompare;
96638    pColl->pUser = pCtx;
96639    pColl->xDel = xDel;
96640    pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
96641    pColl->type = collType;
96642  }
96643  sqlite3Error(db, SQLITE_OK, 0);
96644  return SQLITE_OK;
96645}
96646
96647
96648/*
96649** This array defines hard upper bounds on limit values.  The
96650** initializer must be kept in sync with the SQLITE_LIMIT_*
96651** #defines in sqlite3.h.
96652*/
96653static const int aHardLimit[] = {
96654  SQLITE_MAX_LENGTH,
96655  SQLITE_MAX_SQL_LENGTH,
96656  SQLITE_MAX_COLUMN,
96657  SQLITE_MAX_EXPR_DEPTH,
96658  SQLITE_MAX_COMPOUND_SELECT,
96659  SQLITE_MAX_VDBE_OP,
96660  SQLITE_MAX_FUNCTION_ARG,
96661  SQLITE_MAX_ATTACHED,
96662  SQLITE_MAX_LIKE_PATTERN_LENGTH,
96663  SQLITE_MAX_VARIABLE_NUMBER,
96664  SQLITE_MAX_TRIGGER_DEPTH,
96665};
96666
96667/*
96668** Make sure the hard limits are set to reasonable values
96669*/
96670#if SQLITE_MAX_LENGTH<100
96671# error SQLITE_MAX_LENGTH must be at least 100
96672#endif
96673#if SQLITE_MAX_SQL_LENGTH<100
96674# error SQLITE_MAX_SQL_LENGTH must be at least 100
96675#endif
96676#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
96677# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
96678#endif
96679#if SQLITE_MAX_COMPOUND_SELECT<2
96680# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
96681#endif
96682#if SQLITE_MAX_VDBE_OP<40
96683# error SQLITE_MAX_VDBE_OP must be at least 40
96684#endif
96685#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
96686# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
96687#endif
96688#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
96689# error SQLITE_MAX_ATTACHED must be between 0 and 30
96690#endif
96691#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
96692# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
96693#endif
96694#if SQLITE_MAX_COLUMN>32767
96695# error SQLITE_MAX_COLUMN must not exceed 32767
96696#endif
96697#if SQLITE_MAX_TRIGGER_DEPTH<1
96698# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
96699#endif
96700
96701
96702/*
96703** Change the value of a limit.  Report the old value.
96704** If an invalid limit index is supplied, report -1.
96705** Make no changes but still report the old value if the
96706** new limit is negative.
96707**
96708** A new lower limit does not shrink existing constructs.
96709** It merely prevents new constructs that exceed the limit
96710** from forming.
96711*/
96712SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
96713  int oldLimit;
96714  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
96715    return -1;
96716  }
96717  oldLimit = db->aLimit[limitId];
96718  if( newLimit>=0 ){
96719    if( newLimit>aHardLimit[limitId] ){
96720      newLimit = aHardLimit[limitId];
96721    }
96722    db->aLimit[limitId] = newLimit;
96723  }
96724  return oldLimit;
96725}
96726
96727/*
96728** This routine does the work of opening a database on behalf of
96729** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
96730** is UTF-8 encoded.
96731*/
96732static int openDatabase(
96733  const char *zFilename, /* Database filename UTF-8 encoded */
96734  sqlite3 **ppDb,        /* OUT: Returned database handle */
96735  unsigned flags,        /* Operational flags */
96736  const char *zVfs       /* Name of the VFS to use */
96737){
96738  sqlite3 *db;
96739  int rc;
96740  int isThreadsafe;
96741
96742  *ppDb = 0;
96743#ifndef SQLITE_OMIT_AUTOINIT
96744  rc = sqlite3_initialize();
96745  if( rc ) return rc;
96746#endif
96747
96748  if( sqlite3GlobalConfig.bCoreMutex==0 ){
96749    isThreadsafe = 0;
96750  }else if( flags & SQLITE_OPEN_NOMUTEX ){
96751    isThreadsafe = 0;
96752  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
96753    isThreadsafe = 1;
96754  }else{
96755    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
96756  }
96757  if( flags & SQLITE_OPEN_PRIVATECACHE ){
96758    flags &= ~SQLITE_OPEN_SHAREDCACHE;
96759  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
96760    flags |= SQLITE_OPEN_SHAREDCACHE;
96761  }
96762
96763  /* Remove harmful bits from the flags parameter
96764  **
96765  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
96766  ** dealt with in the previous code block.  Besides these, the only
96767  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
96768  ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
96769  ** off all other flags.
96770  */
96771  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
96772               SQLITE_OPEN_EXCLUSIVE |
96773               SQLITE_OPEN_MAIN_DB |
96774               SQLITE_OPEN_TEMP_DB |
96775               SQLITE_OPEN_TRANSIENT_DB |
96776               SQLITE_OPEN_MAIN_JOURNAL |
96777               SQLITE_OPEN_TEMP_JOURNAL |
96778               SQLITE_OPEN_SUBJOURNAL |
96779               SQLITE_OPEN_MASTER_JOURNAL |
96780               SQLITE_OPEN_NOMUTEX |
96781               SQLITE_OPEN_FULLMUTEX
96782             );
96783
96784  /* Allocate the sqlite data structure */
96785  db = sqlite3MallocZero( sizeof(sqlite3) );
96786  if( db==0 ) goto opendb_out;
96787  if( isThreadsafe ){
96788    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
96789    if( db->mutex==0 ){
96790      sqlite3_free(db);
96791      db = 0;
96792      goto opendb_out;
96793    }
96794  }
96795  sqlite3_mutex_enter(db->mutex);
96796  db->errMask = 0xff;
96797  db->nDb = 2;
96798  db->magic = SQLITE_MAGIC_BUSY;
96799  db->aDb = db->aDbStatic;
96800
96801  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
96802  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
96803  db->autoCommit = 1;
96804  db->nextAutovac = -1;
96805  db->nextPagesize = 0;
96806  db->flags |= SQLITE_ShortColNames
96807#if SQLITE_DEFAULT_FILE_FORMAT<4
96808                 | SQLITE_LegacyFileFmt
96809#endif
96810#ifdef SQLITE_ENABLE_LOAD_EXTENSION
96811                 | SQLITE_LoadExtension
96812#endif
96813#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
96814                 | SQLITE_RecTriggers
96815#endif
96816      ;
96817  sqlite3HashInit(&db->aCollSeq);
96818#ifndef SQLITE_OMIT_VIRTUALTABLE
96819  sqlite3HashInit(&db->aModule);
96820#endif
96821
96822  db->pVfs = sqlite3_vfs_find(zVfs);
96823  if( !db->pVfs ){
96824    rc = SQLITE_ERROR;
96825    sqlite3Error(db, rc, "no such vfs: %s", zVfs);
96826    goto opendb_out;
96827  }
96828
96829  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
96830  ** and UTF-16, so add a version for each to avoid any unnecessary
96831  ** conversions. The only error that can occur here is a malloc() failure.
96832  */
96833  createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
96834                  binCollFunc, 0);
96835  createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
96836                  binCollFunc, 0);
96837  createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
96838                  binCollFunc, 0);
96839  createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
96840                  binCollFunc, 0);
96841  if( db->mallocFailed ){
96842    goto opendb_out;
96843  }
96844  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
96845  assert( db->pDfltColl!=0 );
96846
96847  /* Also add a UTF-8 case-insensitive collation sequence. */
96848  createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
96849                  nocaseCollatingFunc, 0);
96850
96851  /* Open the backend database driver */
96852  db->openFlags = flags;
96853  rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE,
96854                           flags | SQLITE_OPEN_MAIN_DB,
96855                           &db->aDb[0].pBt);
96856  if( rc!=SQLITE_OK ){
96857    if( rc==SQLITE_IOERR_NOMEM ){
96858      rc = SQLITE_NOMEM;
96859    }
96860    sqlite3Error(db, rc, 0);
96861    goto opendb_out;
96862  }
96863  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
96864  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
96865
96866
96867  /* The default safety_level for the main database is 'full'; for the temp
96868  ** database it is 'NONE'. This matches the pager layer defaults.
96869  */
96870  db->aDb[0].zName = "main";
96871  db->aDb[0].safety_level = 3;
96872  db->aDb[1].zName = "temp";
96873  db->aDb[1].safety_level = 1;
96874
96875  db->magic = SQLITE_MAGIC_OPEN;
96876  if( db->mallocFailed ){
96877    goto opendb_out;
96878  }
96879
96880  /* Register all built-in functions, but do not attempt to read the
96881  ** database schema yet. This is delayed until the first time the database
96882  ** is accessed.
96883  */
96884  sqlite3Error(db, SQLITE_OK, 0);
96885  sqlite3RegisterBuiltinFunctions(db);
96886
96887  /* Load automatic extensions - extensions that have been registered
96888  ** using the sqlite3_automatic_extension() API.
96889  */
96890  sqlite3AutoLoadExtensions(db);
96891  rc = sqlite3_errcode(db);
96892  if( rc!=SQLITE_OK ){
96893    goto opendb_out;
96894  }
96895
96896#ifdef SQLITE_ENABLE_FTS1
96897  if( !db->mallocFailed ){
96898    extern int sqlite3Fts1Init(sqlite3*);
96899    rc = sqlite3Fts1Init(db);
96900  }
96901#endif
96902
96903#ifdef SQLITE_ENABLE_FTS2
96904  if( !db->mallocFailed && rc==SQLITE_OK ){
96905    extern int sqlite3Fts2Init(sqlite3*);
96906    rc = sqlite3Fts2Init(db);
96907  }
96908#endif
96909
96910#ifdef SQLITE_ENABLE_FTS3
96911  if( !db->mallocFailed && rc==SQLITE_OK ){
96912    rc = sqlite3Fts3Init(db);
96913  }
96914#endif
96915
96916#ifdef SQLITE_ENABLE_ICU
96917  if( !db->mallocFailed && rc==SQLITE_OK ){
96918    rc = sqlite3IcuInit(db);
96919  }
96920#endif
96921
96922#ifdef SQLITE_ENABLE_RTREE
96923  if( !db->mallocFailed && rc==SQLITE_OK){
96924    rc = sqlite3RtreeInit(db);
96925  }
96926#endif
96927
96928  sqlite3Error(db, rc, 0);
96929
96930  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
96931  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
96932  ** mode.  Doing nothing at all also makes NORMAL the default.
96933  */
96934#ifdef SQLITE_DEFAULT_LOCKING_MODE
96935  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
96936  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
96937                          SQLITE_DEFAULT_LOCKING_MODE);
96938#endif
96939
96940  /* Enable the lookaside-malloc subsystem */
96941  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
96942                        sqlite3GlobalConfig.nLookaside);
96943
96944opendb_out:
96945  if( db ){
96946    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
96947    sqlite3_mutex_leave(db->mutex);
96948  }
96949  rc = sqlite3_errcode(db);
96950  if( rc==SQLITE_NOMEM ){
96951    sqlite3_close(db);
96952    db = 0;
96953  }else if( rc!=SQLITE_OK ){
96954    db->magic = SQLITE_MAGIC_SICK;
96955  }
96956  *ppDb = db;
96957  return sqlite3ApiExit(0, rc);
96958}
96959
96960/*
96961** Open a new database handle.
96962*/
96963SQLITE_API int sqlite3_open(
96964  const char *zFilename,
96965  sqlite3 **ppDb
96966){
96967  return openDatabase(zFilename, ppDb,
96968                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
96969}
96970SQLITE_API int sqlite3_open_v2(
96971  const char *filename,   /* Database filename (UTF-8) */
96972  sqlite3 **ppDb,         /* OUT: SQLite db handle */
96973  int flags,              /* Flags */
96974  const char *zVfs        /* Name of VFS module to use */
96975){
96976  return openDatabase(filename, ppDb, flags, zVfs);
96977}
96978
96979#ifndef SQLITE_OMIT_UTF16
96980/*
96981** Open a new database handle.
96982*/
96983SQLITE_API int sqlite3_open16(
96984  const void *zFilename,
96985  sqlite3 **ppDb
96986){
96987  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
96988  sqlite3_value *pVal;
96989  int rc;
96990
96991  assert( zFilename );
96992  assert( ppDb );
96993  *ppDb = 0;
96994#ifndef SQLITE_OMIT_AUTOINIT
96995  rc = sqlite3_initialize();
96996  if( rc ) return rc;
96997#endif
96998  pVal = sqlite3ValueNew(0);
96999  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
97000  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
97001  if( zFilename8 ){
97002    rc = openDatabase(zFilename8, ppDb,
97003                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
97004    assert( *ppDb || rc==SQLITE_NOMEM );
97005    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
97006      ENC(*ppDb) = SQLITE_UTF16NATIVE;
97007    }
97008  }else{
97009    rc = SQLITE_NOMEM;
97010  }
97011  sqlite3ValueFree(pVal);
97012
97013  return sqlite3ApiExit(0, rc);
97014}
97015#endif /* SQLITE_OMIT_UTF16 */
97016
97017/*
97018** Register a new collation sequence with the database handle db.
97019*/
97020SQLITE_API int sqlite3_create_collation(
97021  sqlite3* db,
97022  const char *zName,
97023  int enc,
97024  void* pCtx,
97025  int(*xCompare)(void*,int,const void*,int,const void*)
97026){
97027  int rc;
97028  sqlite3_mutex_enter(db->mutex);
97029  assert( !db->mallocFailed );
97030  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
97031  rc = sqlite3ApiExit(db, rc);
97032  sqlite3_mutex_leave(db->mutex);
97033  return rc;
97034}
97035
97036/*
97037** Register a new collation sequence with the database handle db.
97038*/
97039SQLITE_API int sqlite3_create_collation_v2(
97040  sqlite3* db,
97041  const char *zName,
97042  int enc,
97043  void* pCtx,
97044  int(*xCompare)(void*,int,const void*,int,const void*),
97045  void(*xDel)(void*)
97046){
97047  int rc;
97048  sqlite3_mutex_enter(db->mutex);
97049  assert( !db->mallocFailed );
97050  rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
97051  rc = sqlite3ApiExit(db, rc);
97052  sqlite3_mutex_leave(db->mutex);
97053  return rc;
97054}
97055
97056#ifndef SQLITE_OMIT_UTF16
97057/*
97058** Register a new collation sequence with the database handle db.
97059*/
97060SQLITE_API int sqlite3_create_collation16(
97061  sqlite3* db,
97062  const void *zName,
97063  int enc,
97064  void* pCtx,
97065  int(*xCompare)(void*,int,const void*,int,const void*)
97066){
97067  int rc = SQLITE_OK;
97068  char *zName8;
97069  sqlite3_mutex_enter(db->mutex);
97070  assert( !db->mallocFailed );
97071  zName8 = sqlite3Utf16to8(db, zName, -1);
97072  if( zName8 ){
97073    rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
97074    sqlite3DbFree(db, zName8);
97075  }
97076  rc = sqlite3ApiExit(db, rc);
97077  sqlite3_mutex_leave(db->mutex);
97078  return rc;
97079}
97080#endif /* SQLITE_OMIT_UTF16 */
97081
97082/*
97083** Register a collation sequence factory callback with the database handle
97084** db. Replace any previously installed collation sequence factory.
97085*/
97086SQLITE_API int sqlite3_collation_needed(
97087  sqlite3 *db,
97088  void *pCollNeededArg,
97089  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
97090){
97091  sqlite3_mutex_enter(db->mutex);
97092  db->xCollNeeded = xCollNeeded;
97093  db->xCollNeeded16 = 0;
97094  db->pCollNeededArg = pCollNeededArg;
97095  sqlite3_mutex_leave(db->mutex);
97096  return SQLITE_OK;
97097}
97098
97099#ifndef SQLITE_OMIT_UTF16
97100/*
97101** Register a collation sequence factory callback with the database handle
97102** db. Replace any previously installed collation sequence factory.
97103*/
97104SQLITE_API int sqlite3_collation_needed16(
97105  sqlite3 *db,
97106  void *pCollNeededArg,
97107  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
97108){
97109  sqlite3_mutex_enter(db->mutex);
97110  db->xCollNeeded = 0;
97111  db->xCollNeeded16 = xCollNeeded16;
97112  db->pCollNeededArg = pCollNeededArg;
97113  sqlite3_mutex_leave(db->mutex);
97114  return SQLITE_OK;
97115}
97116#endif /* SQLITE_OMIT_UTF16 */
97117
97118#ifndef SQLITE_OMIT_GLOBALRECOVER
97119#ifndef SQLITE_OMIT_DEPRECATED
97120/*
97121** This function is now an anachronism. It used to be used to recover from a
97122** malloc() failure, but SQLite now does this automatically.
97123*/
97124SQLITE_API int sqlite3_global_recover(void){
97125  return SQLITE_OK;
97126}
97127#endif
97128#endif
97129
97130/*
97131** Test to see whether or not the database connection is in autocommit
97132** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
97133** by default.  Autocommit is disabled by a BEGIN statement and reenabled
97134** by the next COMMIT or ROLLBACK.
97135**
97136******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
97137*/
97138SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
97139  return db->autoCommit;
97140}
97141
97142#ifdef SQLITE_DEBUG
97143/*
97144** The following routine is subtituted for constant SQLITE_CORRUPT in
97145** debugging builds.  This provides a way to set a breakpoint for when
97146** corruption is first detected.
97147*/
97148SQLITE_PRIVATE int sqlite3Corrupt(void){
97149  return SQLITE_CORRUPT;
97150}
97151#endif
97152
97153#ifndef SQLITE_OMIT_DEPRECATED
97154/*
97155** This is a convenience routine that makes sure that all thread-specific
97156** data for this thread has been deallocated.
97157**
97158** SQLite no longer uses thread-specific data so this routine is now a
97159** no-op.  It is retained for historical compatibility.
97160*/
97161SQLITE_API void sqlite3_thread_cleanup(void){
97162}
97163#endif
97164
97165/*
97166** Return meta information about a specific column of a database table.
97167** See comment in sqlite3.h (sqlite.h.in) for details.
97168*/
97169#ifdef SQLITE_ENABLE_COLUMN_METADATA
97170SQLITE_API int sqlite3_table_column_metadata(
97171  sqlite3 *db,                /* Connection handle */
97172  const char *zDbName,        /* Database name or NULL */
97173  const char *zTableName,     /* Table name */
97174  const char *zColumnName,    /* Column name */
97175  char const **pzDataType,    /* OUTPUT: Declared data type */
97176  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
97177  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
97178  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
97179  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
97180){
97181  int rc;
97182  char *zErrMsg = 0;
97183  Table *pTab = 0;
97184  Column *pCol = 0;
97185  int iCol;
97186
97187  char const *zDataType = 0;
97188  char const *zCollSeq = 0;
97189  int notnull = 0;
97190  int primarykey = 0;
97191  int autoinc = 0;
97192
97193  /* Ensure the database schema has been loaded */
97194  sqlite3_mutex_enter(db->mutex);
97195  (void)sqlite3SafetyOn(db);
97196  sqlite3BtreeEnterAll(db);
97197  rc = sqlite3Init(db, &zErrMsg);
97198  if( SQLITE_OK!=rc ){
97199    goto error_out;
97200  }
97201
97202  /* Locate the table in question */
97203  pTab = sqlite3FindTable(db, zTableName, zDbName);
97204  if( !pTab || pTab->pSelect ){
97205    pTab = 0;
97206    goto error_out;
97207  }
97208
97209  /* Find the column for which info is requested */
97210  if( sqlite3IsRowid(zColumnName) ){
97211    iCol = pTab->iPKey;
97212    if( iCol>=0 ){
97213      pCol = &pTab->aCol[iCol];
97214    }
97215  }else{
97216    for(iCol=0; iCol<pTab->nCol; iCol++){
97217      pCol = &pTab->aCol[iCol];
97218      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
97219        break;
97220      }
97221    }
97222    if( iCol==pTab->nCol ){
97223      pTab = 0;
97224      goto error_out;
97225    }
97226  }
97227
97228  /* The following block stores the meta information that will be returned
97229  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
97230  ** and autoinc. At this point there are two possibilities:
97231  **
97232  **     1. The specified column name was rowid", "oid" or "_rowid_"
97233  **        and there is no explicitly declared IPK column.
97234  **
97235  **     2. The table is not a view and the column name identified an
97236  **        explicitly declared column. Copy meta information from *pCol.
97237  */
97238  if( pCol ){
97239    zDataType = pCol->zType;
97240    zCollSeq = pCol->zColl;
97241    notnull = pCol->notNull!=0;
97242    primarykey  = pCol->isPrimKey!=0;
97243    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
97244  }else{
97245    zDataType = "INTEGER";
97246    primarykey = 1;
97247  }
97248  if( !zCollSeq ){
97249    zCollSeq = "BINARY";
97250  }
97251
97252error_out:
97253  sqlite3BtreeLeaveAll(db);
97254  (void)sqlite3SafetyOff(db);
97255
97256  /* Whether the function call succeeded or failed, set the output parameters
97257  ** to whatever their local counterparts contain. If an error did occur,
97258  ** this has the effect of zeroing all output parameters.
97259  */
97260  if( pzDataType ) *pzDataType = zDataType;
97261  if( pzCollSeq ) *pzCollSeq = zCollSeq;
97262  if( pNotNull ) *pNotNull = notnull;
97263  if( pPrimaryKey ) *pPrimaryKey = primarykey;
97264  if( pAutoinc ) *pAutoinc = autoinc;
97265
97266  if( SQLITE_OK==rc && !pTab ){
97267    sqlite3DbFree(db, zErrMsg);
97268    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
97269        zColumnName);
97270    rc = SQLITE_ERROR;
97271  }
97272  sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
97273  sqlite3DbFree(db, zErrMsg);
97274  rc = sqlite3ApiExit(db, rc);
97275  sqlite3_mutex_leave(db->mutex);
97276  return rc;
97277}
97278#endif
97279
97280/*
97281** Sleep for a little while.  Return the amount of time slept.
97282*/
97283SQLITE_API int sqlite3_sleep(int ms){
97284  sqlite3_vfs *pVfs;
97285  int rc;
97286  pVfs = sqlite3_vfs_find(0);
97287  if( pVfs==0 ) return 0;
97288
97289  /* This function works in milliseconds, but the underlying OsSleep()
97290  ** API uses microseconds. Hence the 1000's.
97291  */
97292  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
97293  return rc;
97294}
97295
97296/*
97297** Enable or disable the extended result codes.
97298*/
97299SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
97300  sqlite3_mutex_enter(db->mutex);
97301  db->errMask = onoff ? 0xffffffff : 0xff;
97302  sqlite3_mutex_leave(db->mutex);
97303  return SQLITE_OK;
97304}
97305
97306/*
97307** Invoke the xFileControl method on a particular database.
97308*/
97309SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
97310  int rc = SQLITE_ERROR;
97311  int iDb;
97312  sqlite3_mutex_enter(db->mutex);
97313  if( zDbName==0 ){
97314    iDb = 0;
97315  }else{
97316    for(iDb=0; iDb<db->nDb; iDb++){
97317      if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
97318    }
97319  }
97320  if( iDb<db->nDb ){
97321    Btree *pBtree = db->aDb[iDb].pBt;
97322    if( pBtree ){
97323      Pager *pPager;
97324      sqlite3_file *fd;
97325      sqlite3BtreeEnter(pBtree);
97326      pPager = sqlite3BtreePager(pBtree);
97327      assert( pPager!=0 );
97328      fd = sqlite3PagerFile(pPager);
97329      assert( fd!=0 );
97330      if( fd->pMethods ){
97331        rc = sqlite3OsFileControl(fd, op, pArg);
97332      }
97333      sqlite3BtreeLeave(pBtree);
97334    }
97335  }
97336  sqlite3_mutex_leave(db->mutex);
97337  return rc;
97338}
97339
97340/*
97341** Interface to the testing logic.
97342*/
97343SQLITE_API int sqlite3_test_control(int op, ...){
97344  int rc = 0;
97345#ifndef SQLITE_OMIT_BUILTIN_TEST
97346  va_list ap;
97347  va_start(ap, op);
97348  switch( op ){
97349
97350    /*
97351    ** Save the current state of the PRNG.
97352    */
97353    case SQLITE_TESTCTRL_PRNG_SAVE: {
97354      sqlite3PrngSaveState();
97355      break;
97356    }
97357
97358    /*
97359    ** Restore the state of the PRNG to the last state saved using
97360    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
97361    ** this verb acts like PRNG_RESET.
97362    */
97363    case SQLITE_TESTCTRL_PRNG_RESTORE: {
97364      sqlite3PrngRestoreState();
97365      break;
97366    }
97367
97368    /*
97369    ** Reset the PRNG back to its uninitialized state.  The next call
97370    ** to sqlite3_randomness() will reseed the PRNG using a single call
97371    ** to the xRandomness method of the default VFS.
97372    */
97373    case SQLITE_TESTCTRL_PRNG_RESET: {
97374      sqlite3PrngResetState();
97375      break;
97376    }
97377
97378    /*
97379    **  sqlite3_test_control(BITVEC_TEST, size, program)
97380    **
97381    ** Run a test against a Bitvec object of size.  The program argument
97382    ** is an array of integers that defines the test.  Return -1 on a
97383    ** memory allocation error, 0 on success, or non-zero for an error.
97384    ** See the sqlite3BitvecBuiltinTest() for additional information.
97385    */
97386    case SQLITE_TESTCTRL_BITVEC_TEST: {
97387      int sz = va_arg(ap, int);
97388      int *aProg = va_arg(ap, int*);
97389      rc = sqlite3BitvecBuiltinTest(sz, aProg);
97390      break;
97391    }
97392
97393    /*
97394    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
97395    **
97396    ** Register hooks to call to indicate which malloc() failures
97397    ** are benign.
97398    */
97399    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
97400      typedef void (*void_function)(void);
97401      void_function xBenignBegin;
97402      void_function xBenignEnd;
97403      xBenignBegin = va_arg(ap, void_function);
97404      xBenignEnd = va_arg(ap, void_function);
97405      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
97406      break;
97407    }
97408
97409    /*
97410    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
97411    **
97412    ** Set the PENDING byte to the value in the argument, if X>0.
97413    ** Make no changes if X==0.  Return the value of the pending byte
97414    ** as it existing before this routine was called.
97415    **
97416    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
97417    ** an incompatible database file format.  Changing the PENDING byte
97418    ** while any database connection is open results in undefined and
97419    ** dileterious behavior.
97420    */
97421    case SQLITE_TESTCTRL_PENDING_BYTE: {
97422      unsigned int newVal = va_arg(ap, unsigned int);
97423      rc = sqlite3PendingByte;
97424      if( newVal ) sqlite3PendingByte = newVal;
97425      break;
97426    }
97427
97428    /*
97429    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
97430    **
97431    ** This action provides a run-time test to see whether or not
97432    ** assert() was enabled at compile-time.  If X is true and assert()
97433    ** is enabled, then the return value is true.  If X is true and
97434    ** assert() is disabled, then the return value is zero.  If X is
97435    ** false and assert() is enabled, then the assertion fires and the
97436    ** process aborts.  If X is false and assert() is disabled, then the
97437    ** return value is zero.
97438    */
97439    case SQLITE_TESTCTRL_ASSERT: {
97440      volatile int x = 0;
97441      assert( (x = va_arg(ap,int))!=0 );
97442      rc = x;
97443      break;
97444    }
97445
97446
97447    /*
97448    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
97449    **
97450    ** This action provides a run-time test to see how the ALWAYS and
97451    ** NEVER macros were defined at compile-time.
97452    **
97453    ** The return value is ALWAYS(X).
97454    **
97455    ** The recommended test is X==2.  If the return value is 2, that means
97456    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
97457    ** default setting.  If the return value is 1, then ALWAYS() is either
97458    ** hard-coded to true or else it asserts if its argument is false.
97459    ** The first behavior (hard-coded to true) is the case if
97460    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
97461    ** behavior (assert if the argument to ALWAYS() is false) is the case if
97462    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
97463    **
97464    ** The run-time test procedure might look something like this:
97465    **
97466    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
97467    **      // ALWAYS() and NEVER() are no-op pass-through macros
97468    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
97469    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
97470    **    }else{
97471    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
97472    **    }
97473    */
97474    case SQLITE_TESTCTRL_ALWAYS: {
97475      int x = va_arg(ap,int);
97476      rc = ALWAYS(x);
97477      break;
97478    }
97479
97480    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
97481    **
97482    ** Set the nReserve size to N for the main database on the database
97483    ** connection db.
97484    */
97485    case SQLITE_TESTCTRL_RESERVE: {
97486      sqlite3 *db = va_arg(ap, sqlite3*);
97487      int x = va_arg(ap,int);
97488      sqlite3_mutex_enter(db->mutex);
97489      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
97490      sqlite3_mutex_leave(db->mutex);
97491      break;
97492    }
97493
97494    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
97495    **
97496    ** Enable or disable various optimizations for testing purposes.  The
97497    ** argument N is a bitmask of optimizations to be disabled.  For normal
97498    ** operation N should be 0.  The idea is that a test program (like the
97499    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
97500    ** with various optimizations disabled to verify that the same answer
97501    ** is obtained in every case.
97502    */
97503    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
97504      sqlite3 *db = va_arg(ap, sqlite3*);
97505      int x = va_arg(ap,int);
97506      db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
97507      break;
97508    }
97509
97510#ifdef SQLITE_N_KEYWORD
97511    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
97512    **
97513    ** If zWord is a keyword recognized by the parser, then return the
97514    ** number of keywords.  Or if zWord is not a keyword, return 0.
97515    **
97516    ** This test feature is only available in the amalgamation since
97517    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
97518    ** is built using separate source files.
97519    */
97520    case SQLITE_TESTCTRL_ISKEYWORD: {
97521      const char *zWord = va_arg(ap, const char*);
97522      int n = sqlite3Strlen30(zWord);
97523      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
97524      break;
97525    }
97526#endif
97527
97528  }
97529  va_end(ap);
97530#endif /* SQLITE_OMIT_BUILTIN_TEST */
97531  return rc;
97532}
97533
97534/************** End of main.c ************************************************/
97535/************** Begin file notify.c ******************************************/
97536/*
97537** 2009 March 3
97538**
97539** The author disclaims copyright to this source code.  In place of
97540** a legal notice, here is a blessing:
97541**
97542**    May you do good and not evil.
97543**    May you find forgiveness for yourself and forgive others.
97544**    May you share freely, never taking more than you give.
97545**
97546*************************************************************************
97547**
97548** This file contains the implementation of the sqlite3_unlock_notify()
97549** API method and its associated functionality.
97550*/
97551
97552/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
97553#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
97554
97555/*
97556** Public interfaces:
97557**
97558**   sqlite3ConnectionBlocked()
97559**   sqlite3ConnectionUnlocked()
97560**   sqlite3ConnectionClosed()
97561**   sqlite3_unlock_notify()
97562*/
97563
97564#define assertMutexHeld() \
97565  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
97566
97567/*
97568** Head of a linked list of all sqlite3 objects created by this process
97569** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
97570** is not NULL. This variable may only accessed while the STATIC_MASTER
97571** mutex is held.
97572*/
97573static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
97574
97575#ifndef NDEBUG
97576/*
97577** This function is a complex assert() that verifies the following
97578** properties of the blocked connections list:
97579**
97580**   1) Each entry in the list has a non-NULL value for either
97581**      pUnlockConnection or pBlockingConnection, or both.
97582**
97583**   2) All entries in the list that share a common value for
97584**      xUnlockNotify are grouped together.
97585**
97586**   3) If the argument db is not NULL, then none of the entries in the
97587**      blocked connections list have pUnlockConnection or pBlockingConnection
97588**      set to db. This is used when closing connection db.
97589*/
97590static void checkListProperties(sqlite3 *db){
97591  sqlite3 *p;
97592  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
97593    int seen = 0;
97594    sqlite3 *p2;
97595
97596    /* Verify property (1) */
97597    assert( p->pUnlockConnection || p->pBlockingConnection );
97598
97599    /* Verify property (2) */
97600    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
97601      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
97602      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
97603      assert( db==0 || p->pUnlockConnection!=db );
97604      assert( db==0 || p->pBlockingConnection!=db );
97605    }
97606  }
97607}
97608#else
97609# define checkListProperties(x)
97610#endif
97611
97612/*
97613** Remove connection db from the blocked connections list. If connection
97614** db is not currently a part of the list, this function is a no-op.
97615*/
97616static void removeFromBlockedList(sqlite3 *db){
97617  sqlite3 **pp;
97618  assertMutexHeld();
97619  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
97620    if( *pp==db ){
97621      *pp = (*pp)->pNextBlocked;
97622      break;
97623    }
97624  }
97625}
97626
97627/*
97628** Add connection db to the blocked connections list. It is assumed
97629** that it is not already a part of the list.
97630*/
97631static void addToBlockedList(sqlite3 *db){
97632  sqlite3 **pp;
97633  assertMutexHeld();
97634  for(
97635    pp=&sqlite3BlockedList;
97636    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
97637    pp=&(*pp)->pNextBlocked
97638  );
97639  db->pNextBlocked = *pp;
97640  *pp = db;
97641}
97642
97643/*
97644** Obtain the STATIC_MASTER mutex.
97645*/
97646static void enterMutex(void){
97647  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
97648  checkListProperties(0);
97649}
97650
97651/*
97652** Release the STATIC_MASTER mutex.
97653*/
97654static void leaveMutex(void){
97655  assertMutexHeld();
97656  checkListProperties(0);
97657  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
97658}
97659
97660/*
97661** Register an unlock-notify callback.
97662**
97663** This is called after connection "db" has attempted some operation
97664** but has received an SQLITE_LOCKED error because another connection
97665** (call it pOther) in the same process was busy using the same shared
97666** cache.  pOther is found by looking at db->pBlockingConnection.
97667**
97668** If there is no blocking connection, the callback is invoked immediately,
97669** before this routine returns.
97670**
97671** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
97672** a deadlock.
97673**
97674** Otherwise, make arrangements to invoke xNotify when pOther drops
97675** its locks.
97676**
97677** Each call to this routine overrides any prior callbacks registered
97678** on the same "db".  If xNotify==0 then any prior callbacks are immediately
97679** cancelled.
97680*/
97681SQLITE_API int sqlite3_unlock_notify(
97682  sqlite3 *db,
97683  void (*xNotify)(void **, int),
97684  void *pArg
97685){
97686  int rc = SQLITE_OK;
97687
97688  sqlite3_mutex_enter(db->mutex);
97689  enterMutex();
97690
97691  if( xNotify==0 ){
97692    removeFromBlockedList(db);
97693    db->pUnlockConnection = 0;
97694    db->xUnlockNotify = 0;
97695    db->pUnlockArg = 0;
97696  }else if( 0==db->pBlockingConnection ){
97697    /* The blocking transaction has been concluded. Or there never was a
97698    ** blocking transaction. In either case, invoke the notify callback
97699    ** immediately.
97700    */
97701    xNotify(&pArg, 1);
97702  }else{
97703    sqlite3 *p;
97704
97705    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
97706    if( p ){
97707      rc = SQLITE_LOCKED;              /* Deadlock detected. */
97708    }else{
97709      db->pUnlockConnection = db->pBlockingConnection;
97710      db->xUnlockNotify = xNotify;
97711      db->pUnlockArg = pArg;
97712      removeFromBlockedList(db);
97713      addToBlockedList(db);
97714    }
97715  }
97716
97717  leaveMutex();
97718  assert( !db->mallocFailed );
97719  sqlite3Error(db, rc, (rc?"database is deadlocked":0));
97720  sqlite3_mutex_leave(db->mutex);
97721  return rc;
97722}
97723
97724/*
97725** This function is called while stepping or preparing a statement
97726** associated with connection db. The operation will return SQLITE_LOCKED
97727** to the user because it requires a lock that will not be available
97728** until connection pBlocker concludes its current transaction.
97729*/
97730SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
97731  enterMutex();
97732  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
97733    addToBlockedList(db);
97734  }
97735  db->pBlockingConnection = pBlocker;
97736  leaveMutex();
97737}
97738
97739/*
97740** This function is called when
97741** the transaction opened by database db has just finished. Locks held
97742** by database connection db have been released.
97743**
97744** This function loops through each entry in the blocked connections
97745** list and does the following:
97746**
97747**   1) If the sqlite3.pBlockingConnection member of a list entry is
97748**      set to db, then set pBlockingConnection=0.
97749**
97750**   2) If the sqlite3.pUnlockConnection member of a list entry is
97751**      set to db, then invoke the configured unlock-notify callback and
97752**      set pUnlockConnection=0.
97753**
97754**   3) If the two steps above mean that pBlockingConnection==0 and
97755**      pUnlockConnection==0, remove the entry from the blocked connections
97756**      list.
97757*/
97758SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
97759  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
97760  int nArg = 0;                            /* Number of entries in aArg[] */
97761  sqlite3 **pp;                            /* Iterator variable */
97762  void **aArg;               /* Arguments to the unlock callback */
97763  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
97764  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
97765
97766  aArg = aStatic;
97767  enterMutex();         /* Enter STATIC_MASTER mutex */
97768
97769  /* This loop runs once for each entry in the blocked-connections list. */
97770  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
97771    sqlite3 *p = *pp;
97772
97773    /* Step 1. */
97774    if( p->pBlockingConnection==db ){
97775      p->pBlockingConnection = 0;
97776    }
97777
97778    /* Step 2. */
97779    if( p->pUnlockConnection==db ){
97780      assert( p->xUnlockNotify );
97781      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
97782        xUnlockNotify(aArg, nArg);
97783        nArg = 0;
97784      }
97785
97786      sqlite3BeginBenignMalloc();
97787      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
97788      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
97789      if( (!aDyn && nArg==(int)ArraySize(aStatic))
97790       || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
97791      ){
97792        /* The aArg[] array needs to grow. */
97793        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
97794        if( pNew ){
97795          memcpy(pNew, aArg, nArg*sizeof(void *));
97796          sqlite3_free(aDyn);
97797          aDyn = aArg = pNew;
97798        }else{
97799          /* This occurs when the array of context pointers that need to
97800          ** be passed to the unlock-notify callback is larger than the
97801          ** aStatic[] array allocated on the stack and the attempt to
97802          ** allocate a larger array from the heap has failed.
97803          **
97804          ** This is a difficult situation to handle. Returning an error
97805          ** code to the caller is insufficient, as even if an error code
97806          ** is returned the transaction on connection db will still be
97807          ** closed and the unlock-notify callbacks on blocked connections
97808          ** will go unissued. This might cause the application to wait
97809          ** indefinitely for an unlock-notify callback that will never
97810          ** arrive.
97811          **
97812          ** Instead, invoke the unlock-notify callback with the context
97813          ** array already accumulated. We can then clear the array and
97814          ** begin accumulating any further context pointers without
97815          ** requiring any dynamic allocation. This is sub-optimal because
97816          ** it means that instead of one callback with a large array of
97817          ** context pointers the application will receive two or more
97818          ** callbacks with smaller arrays of context pointers, which will
97819          ** reduce the applications ability to prioritize multiple
97820          ** connections. But it is the best that can be done under the
97821          ** circumstances.
97822          */
97823          xUnlockNotify(aArg, nArg);
97824          nArg = 0;
97825        }
97826      }
97827      sqlite3EndBenignMalloc();
97828
97829      aArg[nArg++] = p->pUnlockArg;
97830      xUnlockNotify = p->xUnlockNotify;
97831      p->pUnlockConnection = 0;
97832      p->xUnlockNotify = 0;
97833      p->pUnlockArg = 0;
97834    }
97835
97836    /* Step 3. */
97837    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
97838      /* Remove connection p from the blocked connections list. */
97839      *pp = p->pNextBlocked;
97840      p->pNextBlocked = 0;
97841    }else{
97842      pp = &p->pNextBlocked;
97843    }
97844  }
97845
97846  if( nArg!=0 ){
97847    xUnlockNotify(aArg, nArg);
97848  }
97849  sqlite3_free(aDyn);
97850  leaveMutex();         /* Leave STATIC_MASTER mutex */
97851}
97852
97853/*
97854** This is called when the database connection passed as an argument is
97855** being closed. The connection is removed from the blocked list.
97856*/
97857SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
97858  sqlite3ConnectionUnlocked(db);
97859  enterMutex();
97860  removeFromBlockedList(db);
97861  checkListProperties(db);
97862  leaveMutex();
97863}
97864#endif
97865
97866/************** End of notify.c **********************************************/
97867/************** Begin file fts3.c ********************************************/
97868/*
97869** 2006 Oct 10
97870**
97871** The author disclaims copyright to this source code.  In place of
97872** a legal notice, here is a blessing:
97873**
97874**    May you do good and not evil.
97875**    May you find forgiveness for yourself and forgive others.
97876**    May you share freely, never taking more than you give.
97877**
97878******************************************************************************
97879**
97880** This is an SQLite module implementing full-text search.
97881*/
97882
97883/*
97884** The code in this file is only compiled if:
97885**
97886**     * The FTS3 module is being built as an extension
97887**       (in which case SQLITE_CORE is not defined), or
97888**
97889**     * The FTS3 module is being built into the core of
97890**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
97891*/
97892
97893/* TODO(shess) Consider exporting this comment to an HTML file or the
97894** wiki.
97895*/
97896/* The full-text index is stored in a series of b+tree (-like)
97897** structures called segments which map terms to doclists.  The
97898** structures are like b+trees in layout, but are constructed from the
97899** bottom up in optimal fashion and are not updatable.  Since trees
97900** are built from the bottom up, things will be described from the
97901** bottom up.
97902**
97903**
97904**** Varints ****
97905** The basic unit of encoding is a variable-length integer called a
97906** varint.  We encode variable-length integers in little-endian order
97907** using seven bits * per byte as follows:
97908**
97909** KEY:
97910**         A = 0xxxxxxx    7 bits of data and one flag bit
97911**         B = 1xxxxxxx    7 bits of data and one flag bit
97912**
97913**  7 bits - A
97914** 14 bits - BA
97915** 21 bits - BBA
97916** and so on.
97917**
97918** This is identical to how sqlite encodes varints (see util.c).
97919**
97920**
97921**** Document lists ****
97922** A doclist (document list) holds a docid-sorted list of hits for a
97923** given term.  Doclists hold docids, and can optionally associate
97924** token positions and offsets with docids.
97925**
97926** A DL_POSITIONS_OFFSETS doclist is stored like this:
97927**
97928** array {
97929**   varint docid;
97930**   array {                (position list for column 0)
97931**     varint position;     (delta from previous position plus POS_BASE)
97932**     varint startOffset;  (delta from previous startOffset)
97933**     varint endOffset;    (delta from startOffset)
97934**   }
97935**   array {
97936**     varint POS_COLUMN;   (marks start of position list for new column)
97937**     varint column;       (index of new column)
97938**     array {
97939**       varint position;   (delta from previous position plus POS_BASE)
97940**       varint startOffset;(delta from previous startOffset)
97941**       varint endOffset;  (delta from startOffset)
97942**     }
97943**   }
97944**   varint POS_END;        (marks end of positions for this document.
97945** }
97946**
97947** Here, array { X } means zero or more occurrences of X, adjacent in
97948** memory.  A "position" is an index of a token in the token stream
97949** generated by the tokenizer, while an "offset" is a byte offset,
97950** both based at 0.  Note that POS_END and POS_COLUMN occur in the
97951** same logical place as the position element, and act as sentinals
97952** ending a position list array.
97953**
97954** A DL_POSITIONS doclist omits the startOffset and endOffset
97955** information.  A DL_DOCIDS doclist omits both the position and
97956** offset information, becoming an array of varint-encoded docids.
97957**
97958** On-disk data is stored as type DL_DEFAULT, so we don't serialize
97959** the type.  Due to how deletion is implemented in the segmentation
97960** system, on-disk doclists MUST store at least positions.
97961**
97962**
97963**** Segment leaf nodes ****
97964** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
97965** nodes are written using LeafWriter, and read using LeafReader (to
97966** iterate through a single leaf node's data) and LeavesReader (to
97967** iterate through a segment's entire leaf layer).  Leaf nodes have
97968** the format:
97969**
97970** varint iHeight;             (height from leaf level, always 0)
97971** varint nTerm;               (length of first term)
97972** char pTerm[nTerm];          (content of first term)
97973** varint nDoclist;            (length of term's associated doclist)
97974** char pDoclist[nDoclist];    (content of doclist)
97975** array {
97976**                             (further terms are delta-encoded)
97977**   varint nPrefix;           (length of prefix shared with previous term)
97978**   varint nSuffix;           (length of unshared suffix)
97979**   char pTermSuffix[nSuffix];(unshared suffix of next term)
97980**   varint nDoclist;          (length of term's associated doclist)
97981**   char pDoclist[nDoclist];  (content of doclist)
97982** }
97983**
97984** Here, array { X } means zero or more occurrences of X, adjacent in
97985** memory.
97986**
97987** Leaf nodes are broken into blocks which are stored contiguously in
97988** the %_segments table in sorted order.  This means that when the end
97989** of a node is reached, the next term is in the node with the next
97990** greater node id.
97991**
97992** New data is spilled to a new leaf node when the current node
97993** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
97994** larger than STANDALONE_MIN (default 1024) is placed in a standalone
97995** node (a leaf node with a single term and doclist).  The goal of
97996** these settings is to pack together groups of small doclists while
97997** making it efficient to directly access large doclists.  The
97998** assumption is that large doclists represent terms which are more
97999** likely to be query targets.
98000**
98001** TODO(shess) It may be useful for blocking decisions to be more
98002** dynamic.  For instance, it may make more sense to have a 2.5k leaf
98003** node rather than splitting into 2k and .5k nodes.  My intuition is
98004** that this might extend through 2x or 4x the pagesize.
98005**
98006**
98007**** Segment interior nodes ****
98008** Segment interior nodes store blockids for subtree nodes and terms
98009** to describe what data is stored by the each subtree.  Interior
98010** nodes are written using InteriorWriter, and read using
98011** InteriorReader.  InteriorWriters are created as needed when
98012** SegmentWriter creates new leaf nodes, or when an interior node
98013** itself grows too big and must be split.  The format of interior
98014** nodes:
98015**
98016** varint iHeight;           (height from leaf level, always >0)
98017** varint iBlockid;          (block id of node's leftmost subtree)
98018** optional {
98019**   varint nTerm;           (length of first term)
98020**   char pTerm[nTerm];      (content of first term)
98021**   array {
98022**                                (further terms are delta-encoded)
98023**     varint nPrefix;            (length of shared prefix with previous term)
98024**     varint nSuffix;            (length of unshared suffix)
98025**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
98026**   }
98027** }
98028**
98029** Here, optional { X } means an optional element, while array { X }
98030** means zero or more occurrences of X, adjacent in memory.
98031**
98032** An interior node encodes n terms separating n+1 subtrees.  The
98033** subtree blocks are contiguous, so only the first subtree's blockid
98034** is encoded.  The subtree at iBlockid will contain all terms less
98035** than the first term encoded (or all terms if no term is encoded).
98036** Otherwise, for terms greater than or equal to pTerm[i] but less
98037** than pTerm[i+1], the subtree for that term will be rooted at
98038** iBlockid+i.  Interior nodes only store enough term data to
98039** distinguish adjacent children (if the rightmost term of the left
98040** child is "something", and the leftmost term of the right child is
98041** "wicked", only "w" is stored).
98042**
98043** New data is spilled to a new interior node at the same height when
98044** the current node exceeds INTERIOR_MAX bytes (default 2048).
98045** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
98046** interior nodes and making the tree too skinny.  The interior nodes
98047** at a given height are naturally tracked by interior nodes at
98048** height+1, and so on.
98049**
98050**
98051**** Segment directory ****
98052** The segment directory in table %_segdir stores meta-information for
98053** merging and deleting segments, and also the root node of the
98054** segment's tree.
98055**
98056** The root node is the top node of the segment's tree after encoding
98057** the entire segment, restricted to ROOT_MAX bytes (default 1024).
98058** This could be either a leaf node or an interior node.  If the top
98059** node requires more than ROOT_MAX bytes, it is flushed to %_segments
98060** and a new root interior node is generated (which should always fit
98061** within ROOT_MAX because it only needs space for 2 varints, the
98062** height and the blockid of the previous root).
98063**
98064** The meta-information in the segment directory is:
98065**   level               - segment level (see below)
98066**   idx                 - index within level
98067**                       - (level,idx uniquely identify a segment)
98068**   start_block         - first leaf node
98069**   leaves_end_block    - last leaf node
98070**   end_block           - last block (including interior nodes)
98071**   root                - contents of root node
98072**
98073** If the root node is a leaf node, then start_block,
98074** leaves_end_block, and end_block are all 0.
98075**
98076**
98077**** Segment merging ****
98078** To amortize update costs, segments are grouped into levels and
98079** merged in batches.  Each increase in level represents exponentially
98080** more documents.
98081**
98082** New documents (actually, document updates) are tokenized and
98083** written individually (using LeafWriter) to a level 0 segment, with
98084** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
98085** level 0 segments are merged into a single level 1 segment.  Level 1
98086** is populated like level 0, and eventually MERGE_COUNT level 1
98087** segments are merged to a single level 2 segment (representing
98088** MERGE_COUNT^2 updates), and so on.
98089**
98090** A segment merge traverses all segments at a given level in
98091** parallel, performing a straightforward sorted merge.  Since segment
98092** leaf nodes are written in to the %_segments table in order, this
98093** merge traverses the underlying sqlite disk structures efficiently.
98094** After the merge, all segment blocks from the merged level are
98095** deleted.
98096**
98097** MERGE_COUNT controls how often we merge segments.  16 seems to be
98098** somewhat of a sweet spot for insertion performance.  32 and 64 show
98099** very similar performance numbers to 16 on insertion, though they're
98100** a tiny bit slower (perhaps due to more overhead in merge-time
98101** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
98102** 16, 2 about 66% slower than 16.
98103**
98104** At query time, high MERGE_COUNT increases the number of segments
98105** which need to be scanned and merged.  For instance, with 100k docs
98106** inserted:
98107**
98108**    MERGE_COUNT   segments
98109**       16           25
98110**        8           12
98111**        4           10
98112**        2            6
98113**
98114** This appears to have only a moderate impact on queries for very
98115** frequent terms (which are somewhat dominated by segment merge
98116** costs), and infrequent and non-existent terms still seem to be fast
98117** even with many segments.
98118**
98119** TODO(shess) That said, it would be nice to have a better query-side
98120** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
98121** optimizations to things like doclist merging will swing the sweet
98122** spot around.
98123**
98124**
98125**
98126**** Handling of deletions and updates ****
98127** Since we're using a segmented structure, with no docid-oriented
98128** index into the term index, we clearly cannot simply update the term
98129** index when a document is deleted or updated.  For deletions, we
98130** write an empty doclist (varint(docid) varint(POS_END)), for updates
98131** we simply write the new doclist.  Segment merges overwrite older
98132** data for a particular docid with newer data, so deletes or updates
98133** will eventually overtake the earlier data and knock it out.  The
98134** query logic likewise merges doclists so that newer data knocks out
98135** older data.
98136**
98137** TODO(shess) Provide a VACUUM type operation to clear out all
98138** deletions and duplications.  This would basically be a forced merge
98139** into a single segment.
98140*/
98141
98142#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
98143
98144#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
98145# define SQLITE_CORE 1
98146#endif
98147
98148/************** Include fts3Int.h in the middle of fts3.c ********************/
98149/************** Begin file fts3Int.h *****************************************/
98150/*
98151** 2009 Nov 12
98152**
98153** The author disclaims copyright to this source code.  In place of
98154** a legal notice, here is a blessing:
98155**
98156**    May you do good and not evil.
98157**    May you find forgiveness for yourself and forgive others.
98158**    May you share freely, never taking more than you give.
98159**
98160******************************************************************************
98161**
98162*/
98163
98164#ifndef _FTSINT_H
98165#define _FTSINT_H
98166
98167#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
98168# define NDEBUG 1
98169#endif
98170
98171/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
98172/************** Begin file fts3_tokenizer.h **********************************/
98173/*
98174** 2006 July 10
98175**
98176** The author disclaims copyright to this source code.
98177**
98178*************************************************************************
98179** Defines the interface to tokenizers used by fulltext-search.  There
98180** are three basic components:
98181**
98182** sqlite3_tokenizer_module is a singleton defining the tokenizer
98183** interface functions.  This is essentially the class structure for
98184** tokenizers.
98185**
98186** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
98187** including customization information defined at creation time.
98188**
98189** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
98190** tokens from a particular input.
98191*/
98192#ifndef _FTS3_TOKENIZER_H_
98193#define _FTS3_TOKENIZER_H_
98194
98195/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
98196** If tokenizers are to be allowed to call sqlite3_*() functions, then
98197** we will need a way to register the API consistently.
98198*/
98199
98200/*
98201** Structures used by the tokenizer interface. When a new tokenizer
98202** implementation is registered, the caller provides a pointer to
98203** an sqlite3_tokenizer_module containing pointers to the callback
98204** functions that make up an implementation.
98205**
98206** When an fts3 table is created, it passes any arguments passed to
98207** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
98208** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
98209** implementation. The xCreate() function in turn returns an
98210** sqlite3_tokenizer structure representing the specific tokenizer to
98211** be used for the fts3 table (customized by the tokenizer clause arguments).
98212**
98213** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
98214** method is called. It returns an sqlite3_tokenizer_cursor object
98215** that may be used to tokenize a specific input buffer based on
98216** the tokenization rules supplied by a specific sqlite3_tokenizer
98217** object.
98218*/
98219typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
98220typedef struct sqlite3_tokenizer sqlite3_tokenizer;
98221typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
98222
98223struct sqlite3_tokenizer_module {
98224
98225  /*
98226  ** Structure version. Should always be set to 0.
98227  */
98228  int iVersion;
98229
98230  /*
98231  ** Create a new tokenizer. The values in the argv[] array are the
98232  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
98233  ** TABLE statement that created the fts3 table. For example, if
98234  ** the following SQL is executed:
98235  **
98236  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
98237  **
98238  ** then argc is set to 2, and the argv[] array contains pointers
98239  ** to the strings "arg1" and "arg2".
98240  **
98241  ** This method should return either SQLITE_OK (0), or an SQLite error
98242  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
98243  ** to point at the newly created tokenizer structure. The generic
98244  ** sqlite3_tokenizer.pModule variable should not be initialised by
98245  ** this callback. The caller will do so.
98246  */
98247  int (*xCreate)(
98248    int argc,                           /* Size of argv array */
98249    const char *const*argv,             /* Tokenizer argument strings */
98250    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
98251  );
98252
98253  /*
98254  ** Destroy an existing tokenizer. The fts3 module calls this method
98255  ** exactly once for each successful call to xCreate().
98256  */
98257  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
98258
98259  /*
98260  ** Create a tokenizer cursor to tokenize an input buffer. The caller
98261  ** is responsible for ensuring that the input buffer remains valid
98262  ** until the cursor is closed (using the xClose() method).
98263  */
98264  int (*xOpen)(
98265    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
98266    const char *pInput, int nBytes,      /* Input buffer */
98267    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
98268  );
98269
98270  /*
98271  ** Destroy an existing tokenizer cursor. The fts3 module calls this
98272  ** method exactly once for each successful call to xOpen().
98273  */
98274  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
98275
98276  /*
98277  ** Retrieve the next token from the tokenizer cursor pCursor. This
98278  ** method should either return SQLITE_OK and set the values of the
98279  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
98280  ** the end of the buffer has been reached, or an SQLite error code.
98281  **
98282  ** *ppToken should be set to point at a buffer containing the
98283  ** normalized version of the token (i.e. after any case-folding and/or
98284  ** stemming has been performed). *pnBytes should be set to the length
98285  ** of this buffer in bytes. The input text that generated the token is
98286  ** identified by the byte offsets returned in *piStartOffset and
98287  ** *piEndOffset. *piStartOffset should be set to the index of the first
98288  ** byte of the token in the input buffer. *piEndOffset should be set
98289  ** to the index of the first byte just past the end of the token in
98290  ** the input buffer.
98291  **
98292  ** The buffer *ppToken is set to point at is managed by the tokenizer
98293  ** implementation. It is only required to be valid until the next call
98294  ** to xNext() or xClose().
98295  */
98296  /* TODO(shess) current implementation requires pInput to be
98297  ** nul-terminated.  This should either be fixed, or pInput/nBytes
98298  ** should be converted to zInput.
98299  */
98300  int (*xNext)(
98301    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
98302    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
98303    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
98304    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
98305    int *piPosition      /* OUT: Number of tokens returned before this one */
98306  );
98307};
98308
98309struct sqlite3_tokenizer {
98310  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
98311  /* Tokenizer implementations will typically add additional fields */
98312};
98313
98314struct sqlite3_tokenizer_cursor {
98315  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
98316  /* Tokenizer implementations will typically add additional fields */
98317};
98318
98319int fts3_global_term_cnt(int iTerm, int iCol);
98320int fts3_term_cnt(int iTerm, int iCol);
98321
98322
98323#endif /* _FTS3_TOKENIZER_H_ */
98324
98325/************** End of fts3_tokenizer.h **************************************/
98326/************** Continuing where we left off in fts3Int.h ********************/
98327/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
98328/************** Begin file fts3_hash.h ***************************************/
98329/*
98330** 2001 September 22
98331**
98332** The author disclaims copyright to this source code.  In place of
98333** a legal notice, here is a blessing:
98334**
98335**    May you do good and not evil.
98336**    May you find forgiveness for yourself and forgive others.
98337**    May you share freely, never taking more than you give.
98338**
98339*************************************************************************
98340** This is the header file for the generic hash-table implemenation
98341** used in SQLite.  We've modified it slightly to serve as a standalone
98342** hash table implementation for the full-text indexing module.
98343**
98344*/
98345#ifndef _FTS3_HASH_H_
98346#define _FTS3_HASH_H_
98347
98348/* Forward declarations of structures. */
98349typedef struct Fts3Hash Fts3Hash;
98350typedef struct Fts3HashElem Fts3HashElem;
98351
98352/* A complete hash table is an instance of the following structure.
98353** The internals of this structure are intended to be opaque -- client
98354** code should not attempt to access or modify the fields of this structure
98355** directly.  Change this structure only by using the routines below.
98356** However, many of the "procedures" and "functions" for modifying and
98357** accessing this structure are really macros, so we can't really make
98358** this structure opaque.
98359*/
98360struct Fts3Hash {
98361  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
98362  char copyKey;           /* True if copy of key made on insert */
98363  int count;              /* Number of entries in this table */
98364  Fts3HashElem *first;    /* The first element of the array */
98365  int htsize;             /* Number of buckets in the hash table */
98366  struct _fts3ht {        /* the hash table */
98367    int count;               /* Number of entries with this hash */
98368    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
98369  } *ht;
98370};
98371
98372/* Each element in the hash table is an instance of the following
98373** structure.  All elements are stored on a single doubly-linked list.
98374**
98375** Again, this structure is intended to be opaque, but it can't really
98376** be opaque because it is used by macros.
98377*/
98378struct Fts3HashElem {
98379  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
98380  void *data;                /* Data associated with this element */
98381  void *pKey; int nKey;      /* Key associated with this element */
98382};
98383
98384/*
98385** There are 2 different modes of operation for a hash table:
98386**
98387**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
98388**                           (including the null-terminator, if any).  Case
98389**                           is respected in comparisons.
98390**
98391**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
98392**                           memcmp() is used to compare keys.
98393**
98394** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
98395*/
98396#define FTS3_HASH_STRING    1
98397#define FTS3_HASH_BINARY    2
98398
98399/*
98400** Access routines.  To delete, insert a NULL pointer.
98401*/
98402SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
98403SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
98404SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
98405SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
98406SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
98407
98408/*
98409** Shorthand for the functions above
98410*/
98411#define fts3HashInit     sqlite3Fts3HashInit
98412#define fts3HashInsert   sqlite3Fts3HashInsert
98413#define fts3HashFind     sqlite3Fts3HashFind
98414#define fts3HashClear    sqlite3Fts3HashClear
98415#define fts3HashFindElem sqlite3Fts3HashFindElem
98416
98417/*
98418** Macros for looping over all elements of a hash table.  The idiom is
98419** like this:
98420**
98421**   Fts3Hash h;
98422**   Fts3HashElem *p;
98423**   ...
98424**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
98425**     SomeStructure *pData = fts3HashData(p);
98426**     // do something with pData
98427**   }
98428*/
98429#define fts3HashFirst(H)  ((H)->first)
98430#define fts3HashNext(E)   ((E)->next)
98431#define fts3HashData(E)   ((E)->data)
98432#define fts3HashKey(E)    ((E)->pKey)
98433#define fts3HashKeysize(E) ((E)->nKey)
98434
98435/*
98436** Number of entries in a hash table
98437*/
98438#define fts3HashCount(H)  ((H)->count)
98439
98440#endif /* _FTS3_HASH_H_ */
98441
98442/************** End of fts3_hash.h *******************************************/
98443/************** Continuing where we left off in fts3Int.h ********************/
98444
98445/*
98446** This constant controls how often segments are merged. Once there are
98447** FTS3_MERGE_COUNT segments of level N, they are merged into a single
98448** segment of level N+1.
98449*/
98450#define FTS3_MERGE_COUNT 16
98451
98452/*
98453** This is the maximum amount of data (in bytes) to store in the
98454** Fts3Table.pendingTerms hash table. Normally, the hash table is
98455** populated as documents are inserted/updated/deleted in a transaction
98456** and used to create a new segment when the transaction is committed.
98457** However if this limit is reached midway through a transaction, a new
98458** segment is created and the hash table cleared immediately.
98459*/
98460#define FTS3_MAX_PENDING_DATA (1*1024*1024)
98461
98462/*
98463** Macro to return the number of elements in an array. SQLite has a
98464** similar macro called ArraySize(). Use a different name to avoid
98465** a collision when building an amalgamation with built-in FTS3.
98466*/
98467#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
98468
98469/*
98470** Maximum length of a varint encoded integer. The varint format is different
98471** from that used by SQLite, so the maximum length is 10, not 9.
98472*/
98473#define FTS3_VARINT_MAX 10
98474
98475/*
98476** This section provides definitions to allow the
98477** FTS3 extension to be compiled outside of the
98478** amalgamation.
98479*/
98480#ifndef SQLITE_AMALGAMATION
98481/*
98482** Macros indicating that conditional expressions are always true or
98483** false.
98484*/
98485# define ALWAYS(x) (x)
98486# define NEVER(X)  (x)
98487/*
98488** Internal types used by SQLite.
98489*/
98490typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
98491typedef short int i16;            /* 2-byte (or larger) signed integer */
98492typedef unsigned int u32;         /* 4-byte unsigned integer */
98493typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
98494/*
98495** Macro used to suppress compiler warnings for unused parameters.
98496*/
98497#define UNUSED_PARAMETER(x) (void)(x)
98498#endif
98499
98500typedef struct Fts3Table Fts3Table;
98501typedef struct Fts3Cursor Fts3Cursor;
98502typedef struct Fts3Expr Fts3Expr;
98503typedef struct Fts3Phrase Fts3Phrase;
98504typedef struct Fts3SegReader Fts3SegReader;
98505typedef struct Fts3SegFilter Fts3SegFilter;
98506
98507/*
98508** A connection to a fulltext index is an instance of the following
98509** structure. The xCreate and xConnect methods create an instance
98510** of this structure and xDestroy and xDisconnect free that instance.
98511** All other methods receive a pointer to the structure as one of their
98512** arguments.
98513*/
98514struct Fts3Table {
98515  sqlite3_vtab base;              /* Base class used by SQLite core */
98516  sqlite3 *db;                    /* The database connection */
98517  const char *zDb;                /* logical database name */
98518  const char *zName;              /* virtual table name */
98519  int nColumn;                    /* number of named columns in virtual table */
98520  char **azColumn;                /* column names.  malloced */
98521  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
98522
98523  /* Precompiled statements used by the implementation. Each of these
98524  ** statements is run and reset within a single virtual table API call.
98525  */
98526  sqlite3_stmt *aStmt[18];
98527
98528  /* Pointer to string containing the SQL:
98529  **
98530  ** "SELECT block FROM %_segments WHERE blockid BETWEEN ? AND ?
98531  **    ORDER BY blockid"
98532  */
98533  char *zSelectLeaves;
98534  int nLeavesStmt;                /* Valid statements in aLeavesStmt */
98535  int nLeavesTotal;               /* Total number of prepared leaves stmts */
98536  int nLeavesAlloc;               /* Allocated size of aLeavesStmt */
98537  sqlite3_stmt **aLeavesStmt;     /* Array of prepared zSelectLeaves stmts */
98538
98539  int nNodeSize;                  /* Soft limit for node size */
98540
98541  /* The following hash table is used to buffer pending index updates during
98542  ** transactions. Variable nPendingData estimates the memory size of the
98543  ** pending data, including hash table overhead, but not malloc overhead.
98544  ** When nPendingData exceeds nMaxPendingData, the buffer is flushed
98545  ** automatically. Variable iPrevDocid is the docid of the most recently
98546  ** inserted record.
98547  */
98548  int nMaxPendingData;
98549  int nPendingData;
98550  sqlite_int64 iPrevDocid;
98551  Fts3Hash pendingTerms;
98552};
98553
98554/*
98555** When the core wants to read from the virtual table, it creates a
98556** virtual table cursor (an instance of the following structure) using
98557** the xOpen method. Cursors are destroyed using the xClose method.
98558*/
98559struct Fts3Cursor {
98560  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
98561  i16 eSearch;                    /* Search strategy (see below) */
98562  u8 isEof;                       /* True if at End Of Results */
98563  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
98564  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
98565  Fts3Expr *pExpr;                /* Parsed MATCH query string */
98566  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
98567  char *pNextId;                  /* Pointer into the body of aDoclist */
98568  char *aDoclist;                 /* List of docids for full-text queries */
98569  int nDoclist;                   /* Size of buffer at aDoclist */
98570  int isMatchinfoOk;              /* True when aMatchinfo[] matches iPrevId */
98571  u32 *aMatchinfo;
98572};
98573
98574/*
98575** The Fts3Cursor.eSearch member is always set to one of the following.
98576** Actualy, Fts3Cursor.eSearch can be greater than or equal to
98577** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
98578** of the column to be searched.  For example, in
98579**
98580**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
98581**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
98582**
98583** Because the LHS of the MATCH operator is 2nd column "b",
98584** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
98585** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
98586** indicating that all columns should be searched,
98587** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
98588*/
98589#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
98590#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
98591#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
98592
98593/*
98594** A "phrase" is a sequence of one or more tokens that must match in
98595** sequence.  A single token is the base case and the most common case.
98596** For a sequence of tokens contained in "...", nToken will be the number
98597** of tokens in the string.
98598*/
98599struct Fts3Phrase {
98600  int nToken;                /* Number of tokens in the phrase */
98601  int iColumn;               /* Index of column this phrase must match */
98602  int isNot;                 /* Phrase prefixed by unary not (-) operator */
98603  struct PhraseToken {
98604    char *z;                 /* Text of the token */
98605    int n;                   /* Number of bytes in buffer pointed to by z */
98606    int isPrefix;            /* True if token ends in with a "*" character */
98607  } aToken[1];               /* One entry for each token in the phrase */
98608};
98609
98610/*
98611** A tree of these objects forms the RHS of a MATCH operator.
98612**
98613** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
98614** is true, then aDoclist points to a malloced buffer, size nDoclist bytes,
98615** containing the results of the NEAR or phrase query in FTS3 doclist
98616** format. As usual, the initial "Length" field found in doclists stored
98617** on disk is omitted from this buffer.
98618**
98619** Variable pCurrent always points to the start of a docid field within
98620** aDoclist. Since the doclist is usually scanned in docid order, this can
98621** be used to accelerate seeking to the required docid within the doclist.
98622*/
98623struct Fts3Expr {
98624  int eType;                 /* One of the FTSQUERY_XXX values defined below */
98625  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
98626  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
98627  Fts3Expr *pLeft;           /* Left operand */
98628  Fts3Expr *pRight;          /* Right operand */
98629  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
98630
98631  int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
98632  char *aDoclist;            /* Buffer containing doclist */
98633  int nDoclist;              /* Size of aDoclist in bytes */
98634
98635  sqlite3_int64 iCurrent;
98636  char *pCurrent;
98637};
98638
98639/*
98640** Candidate values for Fts3Query.eType. Note that the order of the first
98641** four values is in order of precedence when parsing expressions. For
98642** example, the following:
98643**
98644**   "a OR b AND c NOT d NEAR e"
98645**
98646** is equivalent to:
98647**
98648**   "a OR (b AND (c NOT (d NEAR e)))"
98649*/
98650#define FTSQUERY_NEAR   1
98651#define FTSQUERY_NOT    2
98652#define FTSQUERY_AND    3
98653#define FTSQUERY_OR     4
98654#define FTSQUERY_PHRASE 5
98655
98656
98657/* fts3_init.c */
98658SQLITE_PRIVATE int sqlite3Fts3DeleteVtab(int, sqlite3_vtab *);
98659SQLITE_PRIVATE int sqlite3Fts3InitVtab(int, sqlite3*, void*, int, const char*const*,
98660                        sqlite3_vtab **, char **);
98661
98662/* fts3_write.c */
98663SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
98664SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
98665SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
98666SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
98667SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(Fts3Table *,int, sqlite3_int64,
98668  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
98669SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
98670SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *, Fts3SegReader *);
98671SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
98672  Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
98673  int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
98674);
98675SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
98676SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
98677
98678/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
98679#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
98680#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
98681#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
98682#define FTS3_SEGMENT_PREFIX        0x00000008
98683
98684/* Type passed as 4th argument to SegmentReaderIterate() */
98685struct Fts3SegFilter {
98686  const char *zTerm;
98687  int nTerm;
98688  int iCol;
98689  int flags;
98690};
98691
98692/* fts3.c */
98693SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
98694SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
98695SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
98696SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
98697SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
98698
98699SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
98700SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *, Fts3Expr *);
98701
98702/* fts3_tokenizer.c */
98703SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
98704SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
98705SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash,
98706  const char *, sqlite3_tokenizer **, const char **, char **
98707);
98708
98709/* fts3_snippet.c */
98710SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
98711SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context*, Fts3Cursor*,
98712  const char *, const char *, const char *
98713);
98714SQLITE_PRIVATE void sqlite3Fts3Snippet2(sqlite3_context *, Fts3Cursor *, const char *,
98715  const char *, const char *, int, int
98716);
98717SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *);
98718
98719/* fts3_expr.c */
98720SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *,
98721  char **, int, int, const char *, int, Fts3Expr **
98722);
98723SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
98724#ifdef SQLITE_TEST
98725SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
98726#endif
98727
98728#endif /* _FTSINT_H */
98729
98730/************** End of fts3Int.h *********************************************/
98731/************** Continuing where we left off in fts3.c ***********************/
98732
98733
98734#ifndef SQLITE_CORE
98735  SQLITE_EXTENSION_INIT1
98736#endif
98737
98738/*
98739** Write a 64-bit variable-length integer to memory starting at p[0].
98740** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
98741** The number of bytes written is returned.
98742*/
98743SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
98744  unsigned char *q = (unsigned char *) p;
98745  sqlite_uint64 vu = v;
98746  do{
98747    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
98748    vu >>= 7;
98749  }while( vu!=0 );
98750  q[-1] &= 0x7f;  /* turn off high bit in final byte */
98751  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
98752  return (int) (q - (unsigned char *)p);
98753}
98754
98755/*
98756** Read a 64-bit variable-length integer from memory starting at p[0].
98757** Return the number of bytes read, or 0 on error.
98758** The value is stored in *v.
98759*/
98760SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
98761  const unsigned char *q = (const unsigned char *) p;
98762  sqlite_uint64 x = 0, y = 1;
98763  while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
98764    x += y * (*q++ & 0x7f);
98765    y <<= 7;
98766  }
98767  x += y * (*q++);
98768  *v = (sqlite_int64) x;
98769  return (int) (q - (unsigned char *)p);
98770}
98771
98772/*
98773** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
98774** 32-bit integer before it is returned.
98775*/
98776SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
98777 sqlite_int64 i;
98778 int ret = sqlite3Fts3GetVarint(p, &i);
98779 *pi = (int) i;
98780 return ret;
98781}
98782
98783/*
98784** Return the number of bytes required to store the value passed as the
98785** first argument in varint form.
98786*/
98787SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
98788  int i = 0;
98789  do{
98790    i++;
98791    v >>= 7;
98792  }while( v!=0 );
98793  return i;
98794}
98795
98796/*
98797** Convert an SQL-style quoted string into a normal string by removing
98798** the quote characters.  The conversion is done in-place.  If the
98799** input does not begin with a quote character, then this routine
98800** is a no-op.
98801**
98802** Examples:
98803**
98804**     "abc"   becomes   abc
98805**     'xyz'   becomes   xyz
98806**     [pqr]   becomes   pqr
98807**     `mno`   becomes   mno
98808**
98809*/
98810SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
98811  char quote;                     /* Quote character (if any ) */
98812
98813  quote = z[0];
98814  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
98815    int iIn = 1;                  /* Index of next byte to read from input */
98816    int iOut = 0;                 /* Index of next byte to write to output */
98817
98818    /* If the first byte was a '[', then the close-quote character is a ']' */
98819    if( quote=='[' ) quote = ']';
98820
98821    while( ALWAYS(z[iIn]) ){
98822      if( z[iIn]==quote ){
98823        if( z[iIn+1]!=quote ) break;
98824        z[iOut++] = quote;
98825        iIn += 2;
98826      }else{
98827        z[iOut++] = z[iIn++];
98828      }
98829    }
98830    z[iOut] = '\0';
98831  }
98832}
98833
98834static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
98835  sqlite3_int64 iVal;
98836  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
98837  *pVal += iVal;
98838}
98839
98840static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
98841  if( *pp>=pEnd ){
98842    *pp = 0;
98843  }else{
98844    fts3GetDeltaVarint(pp, pVal);
98845  }
98846}
98847
98848/*
98849** The xDisconnect() virtual table method.
98850*/
98851static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
98852  Fts3Table *p = (Fts3Table *)pVtab;
98853  int i;
98854
98855  assert( p->nPendingData==0 );
98856
98857  /* Free any prepared statements held */
98858  for(i=0; i<SizeofArray(p->aStmt); i++){
98859    sqlite3_finalize(p->aStmt[i]);
98860  }
98861  for(i=0; i<p->nLeavesStmt; i++){
98862    sqlite3_finalize(p->aLeavesStmt[i]);
98863  }
98864  sqlite3_free(p->zSelectLeaves);
98865  sqlite3_free(p->aLeavesStmt);
98866
98867  /* Invoke the tokenizer destructor to free the tokenizer. */
98868  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
98869
98870  sqlite3_free(p);
98871  return SQLITE_OK;
98872}
98873
98874/*
98875** The xDestroy() virtual table method.
98876*/
98877static int fts3DestroyMethod(sqlite3_vtab *pVtab){
98878  int rc;                         /* Return code */
98879  Fts3Table *p = (Fts3Table *)pVtab;
98880
98881  /* Create a script to drop the underlying three storage tables. */
98882  char *zSql = sqlite3_mprintf(
98883      "DROP TABLE IF EXISTS %Q.'%q_content';"
98884      "DROP TABLE IF EXISTS %Q.'%q_segments';"
98885      "DROP TABLE IF EXISTS %Q.'%q_segdir';",
98886      p->zDb, p->zName, p->zDb, p->zName, p->zDb, p->zName
98887  );
98888
98889  /* If malloc has failed, set rc to SQLITE_NOMEM. Otherwise, try to
98890  ** execute the SQL script created above.
98891  */
98892  if( zSql ){
98893    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
98894    sqlite3_free(zSql);
98895  }else{
98896    rc = SQLITE_NOMEM;
98897  }
98898
98899  /* If everything has worked, invoke fts3DisconnectMethod() to free the
98900  ** memory associated with the Fts3Table structure and return SQLITE_OK.
98901  ** Otherwise, return an SQLite error code.
98902  */
98903  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
98904}
98905
98906
98907/*
98908** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
98909** passed as the first argument. This is done as part of the xConnect()
98910** and xCreate() methods.
98911*/
98912static int fts3DeclareVtab(Fts3Table *p){
98913  int i;                          /* Iterator variable */
98914  int rc;                         /* Return code */
98915  char *zSql;                     /* SQL statement passed to declare_vtab() */
98916  char *zCols;                    /* List of user defined columns */
98917
98918  /* Create a list of user columns for the virtual table */
98919  zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
98920  for(i=1; zCols && i<p->nColumn; i++){
98921    zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
98922  }
98923
98924  /* Create the whole "CREATE TABLE" statement to pass to SQLite */
98925  zSql = sqlite3_mprintf(
98926      "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
98927  );
98928
98929  if( !zCols || !zSql ){
98930    rc = SQLITE_NOMEM;
98931  }else{
98932    rc = sqlite3_declare_vtab(p->db, zSql);
98933  }
98934
98935  sqlite3_free(zSql);
98936  sqlite3_free(zCols);
98937  return rc;
98938}
98939
98940/*
98941** Create the backing store tables (%_content, %_segments and %_segdir)
98942** required by the FTS3 table passed as the only argument. This is done
98943** as part of the vtab xCreate() method.
98944*/
98945static int fts3CreateTables(Fts3Table *p){
98946  int rc;                         /* Return code */
98947  int i;                          /* Iterator variable */
98948  char *zContentCols;             /* Columns of %_content table */
98949  char *zSql;                     /* SQL script to create required tables */
98950
98951  /* Create a list of user columns for the content table */
98952  zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
98953  for(i=0; zContentCols && i<p->nColumn; i++){
98954    char *z = p->azColumn[i];
98955    zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
98956  }
98957
98958  /* Create the whole SQL script */
98959  zSql = sqlite3_mprintf(
98960      "CREATE TABLE %Q.'%q_content'(%s);"
98961      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);"
98962      "CREATE TABLE %Q.'%q_segdir'("
98963        "level INTEGER,"
98964        "idx INTEGER,"
98965        "start_block INTEGER,"
98966        "leaves_end_block INTEGER,"
98967        "end_block INTEGER,"
98968        "root BLOB,"
98969        "PRIMARY KEY(level, idx)"
98970      ");",
98971      p->zDb, p->zName, zContentCols, p->zDb, p->zName, p->zDb, p->zName
98972  );
98973
98974  /* Unless a malloc() failure has occurred, execute the SQL script to
98975  ** create the tables used to store data for this FTS3 virtual table.
98976  */
98977  if( zContentCols==0 || zSql==0 ){
98978    rc = SQLITE_NOMEM;
98979  }else{
98980    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
98981  }
98982
98983  sqlite3_free(zSql);
98984  sqlite3_free(zContentCols);
98985  return rc;
98986}
98987
98988/*
98989** This function is the implementation of both the xConnect and xCreate
98990** methods of the FTS3 virtual table.
98991**
98992** The argv[] array contains the following:
98993**
98994**   argv[0]   -> module name
98995**   argv[1]   -> database name
98996**   argv[2]   -> table name
98997**   argv[...] -> "column name" and other module argument fields.
98998*/
98999static int fts3InitVtab(
99000  int isCreate,                   /* True for xCreate, false for xConnect */
99001  sqlite3 *db,                    /* The SQLite database connection */
99002  void *pAux,                     /* Hash table containing tokenizers */
99003  int argc,                       /* Number of elements in argv array */
99004  const char * const *argv,       /* xCreate/xConnect argument array */
99005  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
99006  char **pzErr                    /* Write any error message here */
99007){
99008  Fts3Hash *pHash = (Fts3Hash *)pAux;
99009  Fts3Table *p;                   /* Pointer to allocated vtab */
99010  int rc;                         /* Return code */
99011  int i;                          /* Iterator variable */
99012  int nByte;                      /* Size of allocation used for *p */
99013  int iCol;
99014  int nString = 0;
99015  int nCol = 0;
99016  char *zCsr;
99017  int nDb;
99018  int nName;
99019
99020  const char *zTokenizer = 0;               /* Name of tokenizer to use */
99021  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
99022
99023  nDb = (int)strlen(argv[1]) + 1;
99024  nName = (int)strlen(argv[2]) + 1;
99025  for(i=3; i<argc; i++){
99026    char const *z = argv[i];
99027    rc = sqlite3Fts3InitTokenizer(pHash, z, &pTokenizer, &zTokenizer, pzErr);
99028    if( rc!=SQLITE_OK ){
99029      return rc;
99030    }
99031    if( z!=zTokenizer ){
99032      nString += (int)(strlen(z) + 1);
99033    }
99034  }
99035  nCol = argc - 3 - (zTokenizer!=0);
99036  if( zTokenizer==0 ){
99037    rc = sqlite3Fts3InitTokenizer(pHash, 0, &pTokenizer, 0, pzErr);
99038    if( rc!=SQLITE_OK ){
99039      return rc;
99040    }
99041    assert( pTokenizer );
99042  }
99043
99044  if( nCol==0 ){
99045    nCol = 1;
99046  }
99047
99048  /* Allocate and populate the Fts3Table structure. */
99049  nByte = sizeof(Fts3Table) +              /* Fts3Table */
99050          nCol * sizeof(char *) +              /* azColumn */
99051          nName +                              /* zName */
99052          nDb +                                /* zDb */
99053          nString;                             /* Space for azColumn strings */
99054  p = (Fts3Table*)sqlite3_malloc(nByte);
99055  if( p==0 ){
99056    rc = SQLITE_NOMEM;
99057    goto fts3_init_out;
99058  }
99059  memset(p, 0, nByte);
99060
99061  p->db = db;
99062  p->nColumn = nCol;
99063  p->nPendingData = 0;
99064  p->azColumn = (char **)&p[1];
99065  p->pTokenizer = pTokenizer;
99066  p->nNodeSize = 1000;
99067  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
99068  zCsr = (char *)&p->azColumn[nCol];
99069
99070  fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
99071
99072  /* Fill in the zName and zDb fields of the vtab structure. */
99073  p->zName = zCsr;
99074  memcpy(zCsr, argv[2], nName);
99075  zCsr += nName;
99076  p->zDb = zCsr;
99077  memcpy(zCsr, argv[1], nDb);
99078  zCsr += nDb;
99079
99080  /* Fill in the azColumn array */
99081  iCol = 0;
99082  for(i=3; i<argc; i++){
99083    if( argv[i]!=zTokenizer ){
99084      char *z;
99085      int n;
99086      z = (char *)sqlite3Fts3NextToken(argv[i], &n);
99087      memcpy(zCsr, z, n);
99088      zCsr[n] = '\0';
99089      sqlite3Fts3Dequote(zCsr);
99090      p->azColumn[iCol++] = zCsr;
99091      zCsr += n+1;
99092      assert( zCsr <= &((char *)p)[nByte] );
99093    }
99094  }
99095  if( iCol==0 ){
99096    assert( nCol==1 );
99097    p->azColumn[0] = "content";
99098  }
99099
99100  /* If this is an xCreate call, create the underlying tables in the
99101  ** database. TODO: For xConnect(), it could verify that said tables exist.
99102  */
99103  if( isCreate ){
99104    rc = fts3CreateTables(p);
99105    if( rc!=SQLITE_OK ) goto fts3_init_out;
99106  }
99107
99108  rc = fts3DeclareVtab(p);
99109  if( rc!=SQLITE_OK ) goto fts3_init_out;
99110
99111  *ppVTab = &p->base;
99112
99113fts3_init_out:
99114  assert( p || (pTokenizer && rc!=SQLITE_OK) );
99115  if( rc!=SQLITE_OK ){
99116    if( p ){
99117      fts3DisconnectMethod((sqlite3_vtab *)p);
99118    }else{
99119      pTokenizer->pModule->xDestroy(pTokenizer);
99120    }
99121  }
99122  return rc;
99123}
99124
99125/*
99126** The xConnect() and xCreate() methods for the virtual table. All the
99127** work is done in function fts3InitVtab().
99128*/
99129static int fts3ConnectMethod(
99130  sqlite3 *db,                    /* Database connection */
99131  void *pAux,                     /* Pointer to tokenizer hash table */
99132  int argc,                       /* Number of elements in argv array */
99133  const char * const *argv,       /* xCreate/xConnect argument array */
99134  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
99135  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
99136){
99137  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
99138}
99139static int fts3CreateMethod(
99140  sqlite3 *db,                    /* Database connection */
99141  void *pAux,                     /* Pointer to tokenizer hash table */
99142  int argc,                       /* Number of elements in argv array */
99143  const char * const *argv,       /* xCreate/xConnect argument array */
99144  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
99145  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
99146){
99147  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
99148}
99149
99150/*
99151** Implementation of the xBestIndex method for FTS3 tables. There
99152** are three possible strategies, in order of preference:
99153**
99154**   1. Direct lookup by rowid or docid.
99155**   2. Full-text search using a MATCH operator on a non-docid column.
99156**   3. Linear scan of %_content table.
99157*/
99158static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
99159  Fts3Table *p = (Fts3Table *)pVTab;
99160  int i;                          /* Iterator variable */
99161  int iCons = -1;                 /* Index of constraint to use */
99162
99163  /* By default use a full table scan. This is an expensive option,
99164  ** so search through the constraints to see if a more efficient
99165  ** strategy is possible.
99166  */
99167  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
99168  pInfo->estimatedCost = 500000;
99169  for(i=0; i<pInfo->nConstraint; i++){
99170    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
99171    if( pCons->usable==0 ) continue;
99172
99173    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
99174    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
99175     && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
99176    ){
99177      pInfo->idxNum = FTS3_DOCID_SEARCH;
99178      pInfo->estimatedCost = 1.0;
99179      iCons = i;
99180    }
99181
99182    /* A MATCH constraint. Use a full-text search.
99183    **
99184    ** If there is more than one MATCH constraint available, use the first
99185    ** one encountered. If there is both a MATCH constraint and a direct
99186    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
99187    ** though the rowid/docid lookup is faster than a MATCH query, selecting
99188    ** it would lead to an "unable to use function MATCH in the requested
99189    ** context" error.
99190    */
99191    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
99192     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
99193    ){
99194      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
99195      pInfo->estimatedCost = 2.0;
99196      iCons = i;
99197      break;
99198    }
99199  }
99200
99201  if( iCons>=0 ){
99202    pInfo->aConstraintUsage[iCons].argvIndex = 1;
99203    pInfo->aConstraintUsage[iCons].omit = 1;
99204  }
99205  return SQLITE_OK;
99206}
99207
99208/*
99209** Implementation of xOpen method.
99210*/
99211static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
99212  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
99213
99214  UNUSED_PARAMETER(pVTab);
99215
99216  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
99217  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
99218  ** if the allocation fails, return SQLITE_NOMEM.
99219  */
99220  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
99221  if( !pCsr ){
99222    return SQLITE_NOMEM;
99223  }
99224  memset(pCsr, 0, sizeof(Fts3Cursor));
99225  return SQLITE_OK;
99226}
99227
99228/****************************************************************/
99229/****************************************************************/
99230/****************************************************************/
99231/****************************************************************/
99232
99233
99234/*
99235** Close the cursor.  For additional information see the documentation
99236** on the xClose method of the virtual table interface.
99237*/
99238static int fulltextClose(sqlite3_vtab_cursor *pCursor){
99239  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
99240  sqlite3_finalize(pCsr->pStmt);
99241  sqlite3Fts3ExprFree(pCsr->pExpr);
99242  sqlite3_free(pCsr->aDoclist);
99243  sqlite3_free(pCsr->aMatchinfo);
99244  sqlite3_free(pCsr);
99245  return SQLITE_OK;
99246}
99247
99248static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
99249  if( pCsr->isRequireSeek ){
99250    pCsr->isRequireSeek = 0;
99251    sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
99252    if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
99253      return SQLITE_OK;
99254    }else{
99255      int rc = sqlite3_reset(pCsr->pStmt);
99256      if( rc==SQLITE_OK ){
99257        /* If no row was found and no error has occured, then the %_content
99258        ** table is missing a row that is present in the full-text index.
99259        ** The data structures are corrupt.
99260        */
99261        rc = SQLITE_CORRUPT;
99262      }
99263      pCsr->isEof = 1;
99264      if( pContext ){
99265        sqlite3_result_error_code(pContext, rc);
99266      }
99267      return rc;
99268    }
99269  }else{
99270    return SQLITE_OK;
99271  }
99272}
99273
99274static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
99275  int rc = SQLITE_OK;             /* Return code */
99276  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
99277
99278  if( pCsr->aDoclist==0 ){
99279    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
99280      pCsr->isEof = 1;
99281      rc = sqlite3_reset(pCsr->pStmt);
99282    }
99283  }else if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
99284    pCsr->isEof = 1;
99285  }else{
99286    sqlite3_reset(pCsr->pStmt);
99287    fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
99288    pCsr->isRequireSeek = 1;
99289    pCsr->isMatchinfoOk = 1;
99290  }
99291  return rc;
99292}
99293
99294
99295/*
99296** The buffer pointed to by argument zNode (size nNode bytes) contains the
99297** root node of a b-tree segment. The segment is guaranteed to be at least
99298** one level high (i.e. the root node is not also a leaf). If successful,
99299** this function locates the leaf node of the segment that may contain the
99300** term specified by arguments zTerm and nTerm and writes its block number
99301** to *piLeaf.
99302**
99303** It is possible that the returned leaf node does not contain the specified
99304** term. However, if the segment does contain said term, it is stored on
99305** the identified leaf node. Because this function only inspects interior
99306** segment nodes (and never loads leaf nodes into memory), it is not possible
99307** to be sure.
99308**
99309** If an error occurs, an error code other than SQLITE_OK is returned.
99310*/
99311static int fts3SelectLeaf(
99312  Fts3Table *p,                   /* Virtual table handle */
99313  const char *zTerm,              /* Term to select leaves for */
99314  int nTerm,                      /* Size of term zTerm in bytes */
99315  const char *zNode,              /* Buffer containing segment interior node */
99316  int nNode,                      /* Size of buffer at zNode */
99317  sqlite3_int64 *piLeaf           /* Selected leaf node */
99318){
99319  int rc = SQLITE_OK;             /* Return code */
99320  const char *zCsr = zNode;       /* Cursor to iterate through node */
99321  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
99322  char *zBuffer = 0;              /* Buffer to load terms into */
99323  int nAlloc = 0;                 /* Size of allocated buffer */
99324
99325  while( 1 ){
99326    int isFirstTerm = 1;          /* True when processing first term on page */
99327    int iHeight;                  /* Height of this node in tree */
99328    sqlite3_int64 iChild;         /* Block id of child node to descend to */
99329    int nBlock;                   /* Size of child node in bytes */
99330
99331    zCsr += sqlite3Fts3GetVarint32(zCsr, &iHeight);
99332    zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
99333
99334    while( zCsr<zEnd ){
99335      int cmp;                    /* memcmp() result */
99336      int nSuffix;                /* Size of term suffix */
99337      int nPrefix = 0;            /* Size of term prefix */
99338      int nBuffer;                /* Total term size */
99339
99340      /* Load the next term on the node into zBuffer */
99341      if( !isFirstTerm ){
99342        zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
99343      }
99344      isFirstTerm = 0;
99345      zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
99346      if( nPrefix+nSuffix>nAlloc ){
99347        char *zNew;
99348        nAlloc = (nPrefix+nSuffix) * 2;
99349        zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
99350        if( !zNew ){
99351          sqlite3_free(zBuffer);
99352          return SQLITE_NOMEM;
99353        }
99354        zBuffer = zNew;
99355      }
99356      memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
99357      nBuffer = nPrefix + nSuffix;
99358      zCsr += nSuffix;
99359
99360      /* Compare the term we are searching for with the term just loaded from
99361      ** the interior node. If the specified term is greater than or equal
99362      ** to the term from the interior node, then all terms on the sub-tree
99363      ** headed by node iChild are smaller than zTerm. No need to search
99364      ** iChild.
99365      **
99366      ** If the interior node term is larger than the specified term, then
99367      ** the tree headed by iChild may contain the specified term.
99368      */
99369      cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
99370      if( cmp<0 || (cmp==0 && nBuffer>nTerm) ) break;
99371      iChild++;
99372    };
99373
99374    /* If (iHeight==1), the children of this interior node are leaves. The
99375    ** specified term may be present on leaf node iChild.
99376    */
99377    if( iHeight==1 ){
99378      *piLeaf = iChild;
99379      break;
99380    }
99381
99382    /* Descend to interior node iChild. */
99383    rc = sqlite3Fts3ReadBlock(p, iChild, &zCsr, &nBlock);
99384    if( rc!=SQLITE_OK ) break;
99385    zEnd = &zCsr[nBlock];
99386  }
99387  sqlite3_free(zBuffer);
99388  return rc;
99389}
99390
99391/*
99392** This function is used to create delta-encoded serialized lists of FTS3
99393** varints. Each call to this function appends a single varint to a list.
99394*/
99395static void fts3PutDeltaVarint(
99396  char **pp,                      /* IN/OUT: Output pointer */
99397  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
99398  sqlite3_int64 iVal              /* Write this value to the list */
99399){
99400  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
99401  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
99402  *piPrev = iVal;
99403}
99404
99405/*
99406** When this function is called, *ppPoslist is assumed to point to the
99407** start of a position-list.
99408*/
99409static void fts3PoslistCopy(char **pp, char **ppPoslist){
99410  char *pEnd = *ppPoslist;
99411  char c = 0;
99412
99413  /* The end of a position list is marked by a zero encoded as an FTS3
99414  ** varint. A single 0x00 byte. Except, if the 0x00 byte is preceded by
99415  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
99416  ** of some other, multi-byte, value.
99417  **
99418  ** The following block moves pEnd to point to the first byte that is not
99419  ** immediately preceded by a byte with the 0x80 bit set. Then increments
99420  ** pEnd once more so that it points to the byte immediately following the
99421  ** last byte in the position-list.
99422  */
99423  while( *pEnd | c ) c = *pEnd++ & 0x80;
99424  pEnd++;
99425
99426  if( pp ){
99427    int n = (int)(pEnd - *ppPoslist);
99428    char *p = *pp;
99429    memcpy(p, *ppPoslist, n);
99430    p += n;
99431    *pp = p;
99432  }
99433  *ppPoslist = pEnd;
99434}
99435
99436static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
99437  char *pEnd = *ppPoslist;
99438  char c = 0;
99439
99440  /* A column-list is terminated by either a 0x01 or 0x00. */
99441  while( 0xFE & (*pEnd | c) ) c = *pEnd++ & 0x80;
99442  if( pp ){
99443    int n = (int)(pEnd - *ppPoslist);
99444    char *p = *pp;
99445    memcpy(p, *ppPoslist, n);
99446    p += n;
99447    *pp = p;
99448  }
99449  *ppPoslist = pEnd;
99450}
99451
99452/*
99453** Value used to signify the end of an offset-list. This is safe because
99454** it is not possible to have a document with 2^31 terms.
99455*/
99456#define OFFSET_LIST_END 0x7fffffff
99457
99458/*
99459** This function is used to help parse offset-lists. When this function is
99460** called, *pp may point to the start of the next varint in the offset-list
99461** being parsed, or it may point to 1 byte past the end of the offset-list
99462** (in which case **pp will be 0x00 or 0x01).
99463**
99464** If *pp points past the end of the current offset list, set *pi to
99465** OFFSET_LIST_END and return. Otherwise, read the next varint from *pp,
99466** increment the current value of *pi by the value read, and set *pp to
99467** point to the next value before returning.
99468*/
99469static void fts3ReadNextPos(
99470  char **pp,                      /* IN/OUT: Pointer into offset-list buffer */
99471  sqlite3_int64 *pi               /* IN/OUT: Value read from offset-list */
99472){
99473  if( **pp&0xFE ){
99474    fts3GetDeltaVarint(pp, pi);
99475    *pi -= 2;
99476  }else{
99477    *pi = OFFSET_LIST_END;
99478  }
99479}
99480
99481/*
99482** If parameter iCol is not 0, write an 0x01 byte followed by the value of
99483** iCol encoded as a varint to *pp.
99484**
99485** Set *pp to point to the byte just after the last byte written before
99486** returning (do not modify it if iCol==0). Return the total number of bytes
99487** written (0 if iCol==0).
99488*/
99489static int fts3PutColNumber(char **pp, int iCol){
99490  int n = 0;                      /* Number of bytes written */
99491  if( iCol ){
99492    char *p = *pp;                /* Output pointer */
99493    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
99494    *p = 0x01;
99495    *pp = &p[n];
99496  }
99497  return n;
99498}
99499
99500/*
99501**
99502*/
99503static void fts3PoslistMerge(
99504  char **pp,                      /* Output buffer */
99505  char **pp1,                     /* Left input list */
99506  char **pp2                      /* Right input list */
99507){
99508  char *p = *pp;
99509  char *p1 = *pp1;
99510  char *p2 = *pp2;
99511
99512  while( *p1 || *p2 ){
99513    int iCol1;
99514    int iCol2;
99515
99516    if( *p1==0x01 ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
99517    else if( *p1==0x00 ) iCol1 = OFFSET_LIST_END;
99518    else iCol1 = 0;
99519
99520    if( *p2==0x01 ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
99521    else if( *p2==0x00 ) iCol2 = OFFSET_LIST_END;
99522    else iCol2 = 0;
99523
99524    if( iCol1==iCol2 ){
99525      sqlite3_int64 i1 = 0;
99526      sqlite3_int64 i2 = 0;
99527      sqlite3_int64 iPrev = 0;
99528      int n = fts3PutColNumber(&p, iCol1);
99529      p1 += n;
99530      p2 += n;
99531
99532      /* At this point, both p1 and p2 point to the start of offset-lists.
99533      ** An offset-list is a list of non-negative delta-encoded varints, each
99534      ** incremented by 2 before being stored. Each list is terminated by a 0
99535      ** or 1 value (0x00 or 0x01). The following block merges the two lists
99536      ** and writes the results to buffer p. p is left pointing to the byte
99537      ** after the list written. No terminator (0x00 or 0x01) is written to
99538      ** the output.
99539      */
99540      fts3GetDeltaVarint(&p1, &i1);
99541      fts3GetDeltaVarint(&p2, &i2);
99542      do {
99543        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
99544        iPrev -= 2;
99545        if( i1==i2 ){
99546          fts3ReadNextPos(&p1, &i1);
99547          fts3ReadNextPos(&p2, &i2);
99548        }else if( i1<i2 ){
99549          fts3ReadNextPos(&p1, &i1);
99550        }else{
99551          fts3ReadNextPos(&p2, &i2);
99552        }
99553      }while( i1!=OFFSET_LIST_END || i2!=OFFSET_LIST_END );
99554    }else if( iCol1<iCol2 ){
99555      p1 += fts3PutColNumber(&p, iCol1);
99556      fts3ColumnlistCopy(&p, &p1);
99557    }else{
99558      p2 += fts3PutColNumber(&p, iCol2);
99559      fts3ColumnlistCopy(&p, &p2);
99560    }
99561  }
99562
99563  *p++ = '\0';
99564  *pp = p;
99565  *pp1 = p1 + 1;
99566  *pp2 = p2 + 1;
99567}
99568
99569/*
99570** nToken==1 searches for adjacent positions.
99571*/
99572static int fts3PoslistPhraseMerge(
99573  char **pp,                      /* Output buffer */
99574  int nToken,                     /* Maximum difference in token positions */
99575  int isSaveLeft,                 /* Save the left position */
99576  char **pp1,                     /* Left input list */
99577  char **pp2                      /* Right input list */
99578){
99579  char *p = (pp ? *pp : 0);
99580  char *p1 = *pp1;
99581  char *p2 = *pp2;
99582
99583  int iCol1 = 0;
99584  int iCol2 = 0;
99585  assert( *p1!=0 && *p2!=0 );
99586  if( *p1==0x01 ){
99587    p1++;
99588    p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99589  }
99590  if( *p2==0x01 ){
99591    p2++;
99592    p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99593  }
99594
99595  while( 1 ){
99596    if( iCol1==iCol2 ){
99597      char *pSave = p;
99598      sqlite3_int64 iPrev = 0;
99599      sqlite3_int64 iPos1 = 0;
99600      sqlite3_int64 iPos2 = 0;
99601
99602      if( pp && iCol1 ){
99603        *p++ = 0x01;
99604        p += sqlite3Fts3PutVarint(p, iCol1);
99605      }
99606
99607      assert( *p1!=0x00 && *p2!=0x00 && *p1!=0x01 && *p2!=0x01 );
99608      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
99609      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
99610
99611      while( 1 ){
99612        if( iPos2>iPos1 && iPos2<=iPos1+nToken ){
99613          sqlite3_int64 iSave;
99614          if( !pp ){
99615            fts3PoslistCopy(0, &p2);
99616            fts3PoslistCopy(0, &p1);
99617            *pp1 = p1;
99618            *pp2 = p2;
99619            return 1;
99620          }
99621          iSave = isSaveLeft ? iPos1 : iPos2;
99622          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
99623          pSave = 0;
99624        }
99625        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
99626          if( (*p2&0xFE)==0 ) break;
99627          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
99628        }else{
99629          if( (*p1&0xFE)==0 ) break;
99630          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
99631        }
99632      }
99633
99634      if( pSave ){
99635        assert( pp && p );
99636        p = pSave;
99637      }
99638
99639      fts3ColumnlistCopy(0, &p1);
99640      fts3ColumnlistCopy(0, &p2);
99641      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
99642      if( 0==*p1 || 0==*p2 ) break;
99643
99644      p1++;
99645      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99646      p2++;
99647      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99648    }
99649
99650    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
99651    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
99652    ** end of the position list, or the 0x01 that precedes the next
99653    ** column-number in the position list.
99654    */
99655    else if( iCol1<iCol2 ){
99656      fts3ColumnlistCopy(0, &p1);
99657      if( 0==*p1 ) break;
99658      p1++;
99659      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
99660    }else{
99661      fts3ColumnlistCopy(0, &p2);
99662      if( 0==*p2 ) break;
99663      p2++;
99664      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
99665    }
99666  }
99667
99668  fts3PoslistCopy(0, &p2);
99669  fts3PoslistCopy(0, &p1);
99670  *pp1 = p1;
99671  *pp2 = p2;
99672  if( !pp || *pp==p ){
99673    return 0;
99674  }
99675  *p++ = 0x00;
99676  *pp = p;
99677  return 1;
99678}
99679
99680/*
99681** Merge two position-lists as required by the NEAR operator.
99682*/
99683static int fts3PoslistNearMerge(
99684  char **pp,                      /* Output buffer */
99685  char *aTmp,                     /* Temporary buffer space */
99686  int nRight,                     /* Maximum difference in token positions */
99687  int nLeft,                      /* Maximum difference in token positions */
99688  char **pp1,                     /* IN/OUT: Left input list */
99689  char **pp2                      /* IN/OUT: Right input list */
99690){
99691  char *p1 = *pp1;
99692  char *p2 = *pp2;
99693
99694  if( !pp ){
99695    if( fts3PoslistPhraseMerge(0, nRight, 0, pp1, pp2) ) return 1;
99696    *pp1 = p1;
99697    *pp2 = p2;
99698    return fts3PoslistPhraseMerge(0, nLeft, 0, pp2, pp1);
99699  }else{
99700    char *pTmp1 = aTmp;
99701    char *pTmp2;
99702    char *aTmp2;
99703    int res = 1;
99704
99705    fts3PoslistPhraseMerge(&pTmp1, nRight, 0, pp1, pp2);
99706    aTmp2 = pTmp2 = pTmp1;
99707    *pp1 = p1;
99708    *pp2 = p2;
99709    fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, pp2, pp1);
99710    if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
99711      fts3PoslistMerge(pp, &aTmp, &aTmp2);
99712    }else if( pTmp1!=aTmp ){
99713      fts3PoslistCopy(pp, &aTmp);
99714    }else if( pTmp2!=aTmp2 ){
99715      fts3PoslistCopy(pp, &aTmp2);
99716    }else{
99717      res = 0;
99718    }
99719
99720    return res;
99721  }
99722}
99723
99724/*
99725** Values that may be used as the first parameter to fts3DoclistMerge().
99726*/
99727#define MERGE_NOT        2        /* D + D -> D */
99728#define MERGE_AND        3        /* D + D -> D */
99729#define MERGE_OR         4        /* D + D -> D */
99730#define MERGE_POS_OR     5        /* P + P -> P */
99731#define MERGE_PHRASE     6        /* P + P -> D */
99732#define MERGE_POS_PHRASE 7        /* P + P -> P */
99733#define MERGE_NEAR       8        /* P + P -> D */
99734#define MERGE_POS_NEAR   9        /* P + P -> P */
99735
99736/*
99737** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
99738** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
99739** which is guaranteed to be large enough to hold the results. The number
99740** of bytes written to aBuffer is stored in *pnBuffer before returning.
99741**
99742** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
99743** occurs while allocating a temporary buffer as part of the merge operation,
99744** SQLITE_NOMEM is returned.
99745*/
99746static int fts3DoclistMerge(
99747  int mergetype,                  /* One of the MERGE_XXX constants */
99748  int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
99749  int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
99750  char *aBuffer,                  /* Pre-allocated output buffer */
99751  int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
99752  char *a1,                       /* Buffer containing first doclist */
99753  int n1,                         /* Size of buffer a1 */
99754  char *a2,                       /* Buffer containing second doclist */
99755  int n2                          /* Size of buffer a2 */
99756){
99757  sqlite3_int64 i1 = 0;
99758  sqlite3_int64 i2 = 0;
99759  sqlite3_int64 iPrev = 0;
99760
99761  char *p = aBuffer;
99762  char *p1 = a1;
99763  char *p2 = a2;
99764  char *pEnd1 = &a1[n1];
99765  char *pEnd2 = &a2[n2];
99766
99767  assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR
99768       || mergetype==MERGE_AND    || mergetype==MERGE_NOT
99769       || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
99770       || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
99771  );
99772
99773  if( !aBuffer ){
99774    *pnBuffer = 0;
99775    return SQLITE_NOMEM;
99776  }
99777
99778  /* Read the first docid from each doclist */
99779  fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99780  fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99781
99782  switch( mergetype ){
99783    case MERGE_OR:
99784    case MERGE_POS_OR:
99785      while( p1 || p2 ){
99786        if( p2 && p1 && i1==i2 ){
99787          fts3PutDeltaVarint(&p, &iPrev, i1);
99788          if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
99789          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99790          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99791        }else if( !p2 || (p1 && i1<i2) ){
99792          fts3PutDeltaVarint(&p, &iPrev, i1);
99793          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
99794          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99795        }else{
99796          fts3PutDeltaVarint(&p, &iPrev, i2);
99797          if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
99798          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99799        }
99800      }
99801      break;
99802
99803    case MERGE_AND:
99804      while( p1 && p2 ){
99805        if( i1==i2 ){
99806          fts3PutDeltaVarint(&p, &iPrev, i1);
99807          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99808          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99809        }else if( i1<i2 ){
99810          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99811        }else{
99812          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99813        }
99814      }
99815      break;
99816
99817    case MERGE_NOT:
99818      while( p1 ){
99819        if( p2 && i1==i2 ){
99820          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99821          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99822        }else if( !p2 || i1<i2 ){
99823          fts3PutDeltaVarint(&p, &iPrev, i1);
99824          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99825        }else{
99826          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99827        }
99828      }
99829      break;
99830
99831    case MERGE_POS_PHRASE:
99832    case MERGE_PHRASE: {
99833      char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
99834      while( p1 && p2 ){
99835        if( i1==i2 ){
99836          char *pSave = p;
99837          sqlite3_int64 iPrevSave = iPrev;
99838          fts3PutDeltaVarint(&p, &iPrev, i1);
99839          if( 0==fts3PoslistPhraseMerge(ppPos, 1, 0, &p1, &p2) ){
99840            p = pSave;
99841            iPrev = iPrevSave;
99842          }
99843          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99844          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99845        }else if( i1<i2 ){
99846          fts3PoslistCopy(0, &p1);
99847          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99848        }else{
99849          fts3PoslistCopy(0, &p2);
99850          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99851        }
99852      }
99853      break;
99854    }
99855
99856    default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
99857      char *aTmp = 0;
99858      char **ppPos = 0;
99859      if( mergetype==MERGE_POS_NEAR ){
99860        ppPos = &p;
99861        aTmp = sqlite3_malloc(2*(n1+n2+1));
99862        if( !aTmp ){
99863          return SQLITE_NOMEM;
99864        }
99865      }
99866
99867      while( p1 && p2 ){
99868        if( i1==i2 ){
99869          char *pSave = p;
99870          sqlite3_int64 iPrevSave = iPrev;
99871          fts3PutDeltaVarint(&p, &iPrev, i1);
99872
99873          if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
99874            iPrev = iPrevSave;
99875            p = pSave;
99876          }
99877
99878          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99879          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99880        }else if( i1<i2 ){
99881          fts3PoslistCopy(0, &p1);
99882          fts3GetDeltaVarint2(&p1, pEnd1, &i1);
99883        }else{
99884          fts3PoslistCopy(0, &p2);
99885          fts3GetDeltaVarint2(&p2, pEnd2, &i2);
99886        }
99887      }
99888      sqlite3_free(aTmp);
99889      break;
99890    }
99891  }
99892
99893  *pnBuffer = (int)(p-aBuffer);
99894  return SQLITE_OK;
99895}
99896
99897/*
99898** A pointer to an instance of this structure is used as the context
99899** argument to sqlite3Fts3SegReaderIterate()
99900*/
99901typedef struct TermSelect TermSelect;
99902struct TermSelect {
99903  int isReqPos;
99904  char *aOutput;                  /* Malloc'd output buffer */
99905  int nOutput;                    /* Size of output in bytes */
99906};
99907
99908/*
99909** This function is used as the sqlite3Fts3SegReaderIterate() callback when
99910** querying the full-text index for a doclist associated with a term or
99911** term-prefix.
99912*/
99913static int fts3TermSelectCb(
99914  Fts3Table *p,                   /* Virtual table object */
99915  void *pContext,                 /* Pointer to TermSelect structure */
99916  char *zTerm,
99917  int nTerm,
99918  char *aDoclist,
99919  int nDoclist
99920){
99921  TermSelect *pTS = (TermSelect *)pContext;
99922  int nNew = pTS->nOutput + nDoclist;
99923  char *aNew = sqlite3_malloc(nNew);
99924
99925  UNUSED_PARAMETER(p);
99926  UNUSED_PARAMETER(zTerm);
99927  UNUSED_PARAMETER(nTerm);
99928
99929  if( !aNew ){
99930    return SQLITE_NOMEM;
99931  }
99932
99933  if( pTS->nOutput==0 ){
99934    /* If this is the first term selected, copy the doclist to the output
99935    ** buffer using memcpy(). TODO: Add a way to transfer control of the
99936    ** aDoclist buffer from the caller so as to avoid the memcpy().
99937    */
99938    memcpy(aNew, aDoclist, nDoclist);
99939  }else{
99940    /* The output buffer is not empty. Merge doclist aDoclist with the
99941    ** existing output. This can only happen with prefix-searches (as
99942    ** searches for exact terms return exactly one doclist).
99943    */
99944    int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
99945    fts3DoclistMerge(mergetype, 0, 0,
99946        aNew, &nNew, pTS->aOutput, pTS->nOutput, aDoclist, nDoclist
99947    );
99948  }
99949
99950  sqlite3_free(pTS->aOutput);
99951  pTS->aOutput = aNew;
99952  pTS->nOutput = nNew;
99953
99954  return SQLITE_OK;
99955}
99956
99957/*
99958** This function retreives the doclist for the specified term (or term
99959** prefix) from the database.
99960**
99961** The returned doclist may be in one of two formats, depending on the
99962** value of parameter isReqPos. If isReqPos is zero, then the doclist is
99963** a sorted list of delta-compressed docids. If isReqPos is non-zero,
99964** then the returned list is in the same format as is stored in the
99965** database without the found length specifier at the start of on-disk
99966** doclists.
99967*/
99968static int fts3TermSelect(
99969  Fts3Table *p,                   /* Virtual table handle */
99970  int iColumn,                    /* Column to query (or -ve for all columns) */
99971  const char *zTerm,              /* Term to query for */
99972  int nTerm,                      /* Size of zTerm in bytes */
99973  int isPrefix,                   /* True for a prefix search */
99974  int isReqPos,                   /* True to include position lists in output */
99975  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
99976  char **ppOut                    /* OUT: Malloced result buffer */
99977){
99978  int i;
99979  TermSelect tsc;
99980  Fts3SegFilter filter;           /* Segment term filter configuration */
99981  Fts3SegReader **apSegment;      /* Array of segments to read data from */
99982  int nSegment = 0;               /* Size of apSegment array */
99983  int nAlloc = 16;                /* Allocated size of segment array */
99984  int rc;                         /* Return code */
99985  sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
99986  int iAge = 0;                   /* Used to assign ages to segments */
99987
99988  apSegment = (Fts3SegReader **)sqlite3_malloc(sizeof(Fts3SegReader*)*nAlloc);
99989  if( !apSegment ) return SQLITE_NOMEM;
99990  rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &apSegment[0]);
99991  if( rc!=SQLITE_OK ) goto finished;
99992  if( apSegment[0] ){
99993    nSegment = 1;
99994  }
99995
99996  /* Loop through the entire %_segdir table. For each segment, create a
99997  ** Fts3SegReader to iterate through the subset of the segment leaves
99998  ** that may contain a term that matches zTerm/nTerm. For non-prefix
99999  ** searches, this is always a single leaf. For prefix searches, this
100000  ** may be a contiguous block of leaves.
100001  **
100002  ** The code in this loop does not actually load any leaves into memory
100003  ** (unless the root node happens to be a leaf). It simply examines the
100004  ** b-tree structure to determine which leaves need to be inspected.
100005  */
100006  rc = sqlite3Fts3AllSegdirs(p, &pStmt);
100007  while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
100008    Fts3SegReader *pNew = 0;
100009    int nRoot = sqlite3_column_bytes(pStmt, 4);
100010    char const *zRoot = sqlite3_column_blob(pStmt, 4);
100011    if( sqlite3_column_int64(pStmt, 1)==0 ){
100012      /* The entire segment is stored on the root node (which must be a
100013      ** leaf). Do not bother inspecting any data in this case, just
100014      ** create a Fts3SegReader to scan the single leaf.
100015      */
100016      rc = sqlite3Fts3SegReaderNew(p, iAge, 0, 0, 0, zRoot, nRoot, &pNew);
100017    }else{
100018      int rc2;                    /* Return value of sqlite3Fts3ReadBlock() */
100019      sqlite3_int64 i1;           /* Blockid of leaf that may contain zTerm */
100020      rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1);
100021      if( rc==SQLITE_OK ){
100022        sqlite3_int64 i2 = sqlite3_column_int64(pStmt, 2);
100023        rc = sqlite3Fts3SegReaderNew(p, iAge, i1, i2, 0, 0, 0, &pNew);
100024      }
100025
100026      /* The following call to ReadBlock() serves to reset the SQL statement
100027      ** used to retrieve blocks of data from the %_segments table. If it is
100028      ** not reset here, then it may remain classified as an active statement
100029      ** by SQLite, which may lead to "DROP TABLE" or "DETACH" commands
100030      ** failing.
100031      */
100032      rc2 = sqlite3Fts3ReadBlock(p, 0, 0, 0);
100033      if( rc==SQLITE_OK ){
100034        rc = rc2;
100035      }
100036    }
100037    iAge++;
100038
100039    /* If a new Fts3SegReader was allocated, add it to the apSegment array. */
100040    assert( pNew!=0 || rc!=SQLITE_OK );
100041    if( pNew ){
100042      if( nSegment==nAlloc ){
100043        Fts3SegReader **pArray;
100044        nAlloc += 16;
100045        pArray = (Fts3SegReader **)sqlite3_realloc(
100046            apSegment, nAlloc*sizeof(Fts3SegReader *)
100047        );
100048        if( !pArray ){
100049          sqlite3Fts3SegReaderFree(p, pNew);
100050          rc = SQLITE_NOMEM;
100051          goto finished;
100052        }
100053        apSegment = pArray;
100054      }
100055      apSegment[nSegment++] = pNew;
100056    }
100057  }
100058  if( rc!=SQLITE_DONE ){
100059    assert( rc!=SQLITE_OK );
100060    goto finished;
100061  }
100062
100063  memset(&tsc, 0, sizeof(TermSelect));
100064  tsc.isReqPos = isReqPos;
100065
100066  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY
100067        | (isPrefix ? FTS3_SEGMENT_PREFIX : 0)
100068        | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
100069        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
100070  filter.iCol = iColumn;
100071  filter.zTerm = zTerm;
100072  filter.nTerm = nTerm;
100073
100074  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
100075      fts3TermSelectCb, (void *)&tsc
100076  );
100077
100078  if( rc==SQLITE_OK ){
100079    *ppOut = tsc.aOutput;
100080    *pnOut = tsc.nOutput;
100081  }else{
100082    sqlite3_free(tsc.aOutput);
100083  }
100084
100085finished:
100086  sqlite3_reset(pStmt);
100087  for(i=0; i<nSegment; i++){
100088    sqlite3Fts3SegReaderFree(p, apSegment[i]);
100089  }
100090  sqlite3_free(apSegment);
100091  return rc;
100092}
100093
100094
100095/*
100096** Return a DocList corresponding to the phrase *pPhrase.
100097*/
100098static int fts3PhraseSelect(
100099  Fts3Table *p,                   /* Virtual table handle */
100100  Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
100101  int isReqPos,                   /* True if output should contain positions */
100102  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
100103  int *pnOut                      /* OUT: Size of buffer at *paOut */
100104){
100105  char *pOut = 0;
100106  int nOut = 0;
100107  int rc = SQLITE_OK;
100108  int ii;
100109  int iCol = pPhrase->iColumn;
100110  int isTermPos = (pPhrase->nToken>1 || isReqPos);
100111
100112  for(ii=0; ii<pPhrase->nToken; ii++){
100113    struct PhraseToken *pTok = &pPhrase->aToken[ii];
100114    char *z = pTok->z;            /* Next token of the phrase */
100115    int n = pTok->n;              /* Size of z in bytes */
100116    int isPrefix = pTok->isPrefix;/* True if token is a prefix */
100117    char *pList;                  /* Pointer to token doclist */
100118    int nList;                    /* Size of buffer at pList */
100119
100120    rc = fts3TermSelect(p, iCol, z, n, isPrefix, isTermPos, &nList, &pList);
100121    if( rc!=SQLITE_OK ) break;
100122
100123    if( ii==0 ){
100124      pOut = pList;
100125      nOut = nList;
100126    }else{
100127      /* Merge the new term list and the current output. If this is the
100128      ** last term in the phrase, and positions are not required in the
100129      ** output of this function, the positions can be dropped as part
100130      ** of this merge. Either way, the result of this merge will be
100131      ** smaller than nList bytes. The code in fts3DoclistMerge() is written
100132      ** so that it is safe to use pList as the output as well as an input
100133      ** in this case.
100134      */
100135      int mergetype = MERGE_POS_PHRASE;
100136      if( ii==pPhrase->nToken-1 && !isReqPos ){
100137        mergetype = MERGE_PHRASE;
100138      }
100139      fts3DoclistMerge(mergetype, 0, 0, pList, &nOut, pOut, nOut, pList, nList);
100140      sqlite3_free(pOut);
100141      pOut = pList;
100142    }
100143    assert( nOut==0 || pOut!=0 );
100144  }
100145
100146  if( rc==SQLITE_OK ){
100147    *paOut = pOut;
100148    *pnOut = nOut;
100149  }else{
100150    sqlite3_free(pOut);
100151  }
100152  return rc;
100153}
100154
100155/*
100156** Evaluate the full-text expression pExpr against fts3 table pTab. Store
100157** the resulting doclist in *paOut and *pnOut.
100158*/
100159static int evalFts3Expr(
100160  Fts3Table *p,                   /* Virtual table handle */
100161  Fts3Expr *pExpr,                /* Parsed fts3 expression */
100162  char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
100163  int *pnOut,                     /* OUT: Size of buffer at *paOut */
100164  int isReqPos                    /* Require positions in output buffer */
100165){
100166  int rc = SQLITE_OK;             /* Return code */
100167
100168  /* Zero the output parameters. */
100169  *paOut = 0;
100170  *pnOut = 0;
100171
100172  if( pExpr ){
100173    assert( pExpr->eType==FTSQUERY_PHRASE
100174         || pExpr->eType==FTSQUERY_NEAR
100175         || isReqPos==0
100176    );
100177    if( pExpr->eType==FTSQUERY_PHRASE ){
100178      rc = fts3PhraseSelect(p, pExpr->pPhrase,
100179          isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
100180          paOut, pnOut
100181      );
100182    }else{
100183      char *aLeft;
100184      char *aRight;
100185      int nLeft;
100186      int nRight;
100187
100188      if( 0==(rc = evalFts3Expr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
100189       && 0==(rc = evalFts3Expr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
100190      ){
100191        assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR
100192            || pExpr->eType==FTSQUERY_AND  || pExpr->eType==FTSQUERY_NOT
100193        );
100194        switch( pExpr->eType ){
100195          case FTSQUERY_NEAR: {
100196            Fts3Expr *pLeft;
100197            Fts3Expr *pRight;
100198            int mergetype = isReqPos ? MERGE_POS_NEAR : MERGE_NEAR;
100199            int nParam1;
100200            int nParam2;
100201            char *aBuffer;
100202
100203            if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
100204              mergetype = MERGE_POS_NEAR;
100205            }
100206            pLeft = pExpr->pLeft;
100207            while( pLeft->eType==FTSQUERY_NEAR ){
100208              pLeft=pLeft->pRight;
100209            }
100210            pRight = pExpr->pRight;
100211            assert( pRight->eType==FTSQUERY_PHRASE );
100212            assert( pLeft->eType==FTSQUERY_PHRASE );
100213
100214            nParam1 = pExpr->nNear+1;
100215            nParam2 = nParam1+pLeft->pPhrase->nToken+pRight->pPhrase->nToken-2;
100216            aBuffer = sqlite3_malloc(nLeft+nRight+1);
100217            rc = fts3DoclistMerge(mergetype, nParam1, nParam2, aBuffer,
100218                pnOut, aLeft, nLeft, aRight, nRight
100219            );
100220            if( rc!=SQLITE_OK ){
100221              sqlite3_free(aBuffer);
100222            }else{
100223              *paOut = aBuffer;
100224            }
100225            sqlite3_free(aLeft);
100226            break;
100227          }
100228
100229          case FTSQUERY_OR: {
100230            /* Allocate a buffer for the output. The maximum size is the
100231            ** sum of the sizes of the two input buffers. The +1 term is
100232            ** so that a buffer of zero bytes is never allocated - this can
100233            ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
100234            */
100235            char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
100236            rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
100237                aLeft, nLeft, aRight, nRight
100238            );
100239            *paOut = aBuffer;
100240            sqlite3_free(aLeft);
100241            break;
100242          }
100243
100244          default: {
100245            assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
100246            fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
100247                aLeft, nLeft, aRight, nRight
100248            );
100249            *paOut = aLeft;
100250            break;
100251          }
100252        }
100253      }
100254      sqlite3_free(aRight);
100255    }
100256  }
100257
100258  return rc;
100259}
100260
100261/*
100262** This is the xFilter interface for the virtual table.  See
100263** the virtual table xFilter method documentation for additional
100264** information.
100265**
100266** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
100267** the %_content table.
100268**
100269** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
100270** in the %_content table.
100271**
100272** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
100273** column on the left-hand side of the MATCH operator is column
100274** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
100275** side of the MATCH operator.
100276*/
100277/* TODO(shess) Upgrade the cursor initialization and destruction to
100278** account for fts3FilterMethod() being called multiple times on the
100279** same cursor. The current solution is very fragile. Apply fix to
100280** fts3 as appropriate.
100281*/
100282static int fts3FilterMethod(
100283  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
100284  int idxNum,                     /* Strategy index */
100285  const char *idxStr,             /* Unused */
100286  int nVal,                       /* Number of elements in apVal */
100287  sqlite3_value **apVal           /* Arguments for the indexing scheme */
100288){
100289  const char *azSql[] = {
100290    "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
100291    "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
100292  };
100293  int rc;                         /* Return code */
100294  char *zSql;                     /* SQL statement used to access %_content */
100295  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
100296  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
100297
100298  UNUSED_PARAMETER(idxStr);
100299  UNUSED_PARAMETER(nVal);
100300
100301  assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
100302  assert( nVal==0 || nVal==1 );
100303  assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
100304
100305  /* In case the cursor has been used before, clear it now. */
100306  sqlite3_finalize(pCsr->pStmt);
100307  sqlite3_free(pCsr->aDoclist);
100308  sqlite3Fts3ExprFree(pCsr->pExpr);
100309  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
100310
100311  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
100312  ** statement loops through all rows of the %_content table. For a
100313  ** full-text query or docid lookup, the statement retrieves a single
100314  ** row by docid.
100315  */
100316  zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
100317  if( !zSql ){
100318    rc = SQLITE_NOMEM;
100319  }else{
100320    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
100321    sqlite3_free(zSql);
100322  }
100323  if( rc!=SQLITE_OK ) return rc;
100324  pCsr->eSearch = (i16)idxNum;
100325
100326  if( idxNum==FTS3_DOCID_SEARCH ){
100327    rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
100328  }else if( idxNum!=FTS3_FULLSCAN_SEARCH ){
100329    int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
100330    const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
100331
100332    if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
100333      return SQLITE_NOMEM;
100334    }
100335
100336    rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn,
100337        iCol, zQuery, -1, &pCsr->pExpr
100338    );
100339    if( rc!=SQLITE_OK ) return rc;
100340
100341    rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
100342    pCsr->pNextId = pCsr->aDoclist;
100343    pCsr->iPrevId = 0;
100344  }
100345
100346  if( rc!=SQLITE_OK ) return rc;
100347  return fts3NextMethod(pCursor);
100348}
100349
100350/*
100351** This is the xEof method of the virtual table. SQLite calls this
100352** routine to find out if it has reached the end of a result set.
100353*/
100354static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
100355  return ((Fts3Cursor *)pCursor)->isEof;
100356}
100357
100358/*
100359** This is the xRowid method. The SQLite core calls this routine to
100360** retrieve the rowid for the current row of the result set. fts3
100361** exposes %_content.docid as the rowid for the virtual table. The
100362** rowid should be written to *pRowid.
100363*/
100364static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
100365  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
100366  if( pCsr->aDoclist ){
100367    *pRowid = pCsr->iPrevId;
100368  }else{
100369    *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
100370  }
100371  return SQLITE_OK;
100372}
100373
100374/*
100375** This is the xColumn method, called by SQLite to request a value from
100376** the row that the supplied cursor currently points to.
100377*/
100378static int fts3ColumnMethod(
100379  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
100380  sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
100381  int iCol                        /* Index of column to read value from */
100382){
100383  int rc;                         /* Return Code */
100384  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
100385  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
100386
100387  /* The column value supplied by SQLite must be in range. */
100388  assert( iCol>=0 && iCol<=p->nColumn+1 );
100389
100390  if( iCol==p->nColumn+1 ){
100391    /* This call is a request for the "docid" column. Since "docid" is an
100392    ** alias for "rowid", use the xRowid() method to obtain the value.
100393    */
100394    sqlite3_int64 iRowid;
100395    rc = fts3RowidMethod(pCursor, &iRowid);
100396    sqlite3_result_int64(pContext, iRowid);
100397  }else if( iCol==p->nColumn ){
100398    /* The extra column whose name is the same as the table.
100399    ** Return a blob which is a pointer to the cursor.
100400    */
100401    sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
100402    rc = SQLITE_OK;
100403  }else{
100404    rc = fts3CursorSeek(0, pCsr);
100405    if( rc==SQLITE_OK ){
100406      sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
100407    }
100408  }
100409  return rc;
100410}
100411
100412/*
100413** This function is the implementation of the xUpdate callback used by
100414** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
100415** inserted, updated or deleted.
100416*/
100417static int fts3UpdateMethod(
100418  sqlite3_vtab *pVtab,            /* Virtual table handle */
100419  int nArg,                       /* Size of argument array */
100420  sqlite3_value **apVal,          /* Array of arguments */
100421  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
100422){
100423  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
100424}
100425
100426/*
100427** Implementation of xSync() method. Flush the contents of the pending-terms
100428** hash-table to the database.
100429*/
100430static int fts3SyncMethod(sqlite3_vtab *pVtab){
100431  return sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
100432}
100433
100434/*
100435** Implementation of xBegin() method. This is a no-op.
100436*/
100437static int fts3BeginMethod(sqlite3_vtab *pVtab){
100438  UNUSED_PARAMETER(pVtab);
100439  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
100440  return SQLITE_OK;
100441}
100442
100443/*
100444** Implementation of xCommit() method. This is a no-op. The contents of
100445** the pending-terms hash-table have already been flushed into the database
100446** by fts3SyncMethod().
100447*/
100448static int fts3CommitMethod(sqlite3_vtab *pVtab){
100449  UNUSED_PARAMETER(pVtab);
100450  assert( ((Fts3Table *)pVtab)->nPendingData==0 );
100451  return SQLITE_OK;
100452}
100453
100454/*
100455** Implementation of xRollback(). Discard the contents of the pending-terms
100456** hash-table. Any changes made to the database are reverted by SQLite.
100457*/
100458static int fts3RollbackMethod(sqlite3_vtab *pVtab){
100459  sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
100460  return SQLITE_OK;
100461}
100462
100463/*
100464** Load the doclist associated with expression pExpr to pExpr->aDoclist.
100465** The loaded doclist contains positions as well as the document ids.
100466** This is used by the matchinfo(), snippet() and offsets() auxillary
100467** functions.
100468*/
100469SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *pTab, Fts3Expr *pExpr){
100470  return evalFts3Expr(pTab, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
100471}
100472
100473/*
100474** After ExprLoadDoclist() (see above) has been called, this function is
100475** used to iterate through the position lists that make up the doclist
100476** stored in pExpr->aDoclist.
100477*/
100478SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
100479  Fts3Expr *pExpr,                /* Access this expressions doclist */
100480  sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
100481  int iCol                        /* Column of requested pos-list */
100482){
100483  assert( pExpr->isLoaded );
100484  if( pExpr->aDoclist ){
100485    char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
100486    char *pCsr = pExpr->pCurrent;
100487
100488    assert( pCsr );
100489    while( pCsr<pEnd ){
100490      if( pExpr->iCurrent<iDocid ){
100491        fts3PoslistCopy(0, &pCsr);
100492        fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
100493        pExpr->pCurrent = pCsr;
100494      }else{
100495        if( pExpr->iCurrent==iDocid ){
100496          int iThis = 0;
100497          if( iCol<0 ){
100498            /* If iCol is negative, return a pointer to the start of the
100499            ** position-list (instead of a pointer to the start of a list
100500            ** of offsets associated with a specific column).
100501            */
100502            return pCsr;
100503          }
100504          while( iThis<iCol ){
100505            fts3ColumnlistCopy(0, &pCsr);
100506            if( *pCsr==0x00 ) return 0;
100507            pCsr++;
100508            pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
100509          }
100510          if( iCol==iThis ) return pCsr;
100511        }
100512        return 0;
100513      }
100514    }
100515  }
100516
100517  return 0;
100518}
100519
100520/*
100521** Helper function used by the implementation of the overloaded snippet(),
100522** offsets() and optimize() SQL functions.
100523**
100524** If the value passed as the third argument is a blob of size
100525** sizeof(Fts3Cursor*), then the blob contents are copied to the
100526** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
100527** message is written to context pContext and SQLITE_ERROR returned. The
100528** string passed via zFunc is used as part of the error message.
100529*/
100530static int fts3FunctionArg(
100531  sqlite3_context *pContext,      /* SQL function call context */
100532  const char *zFunc,              /* Function name */
100533  sqlite3_value *pVal,            /* argv[0] passed to function */
100534  Fts3Cursor **ppCsr         /* OUT: Store cursor handle here */
100535){
100536  Fts3Cursor *pRet;
100537  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
100538   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
100539  ){
100540    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
100541    sqlite3_result_error(pContext, zErr, -1);
100542    sqlite3_free(zErr);
100543    return SQLITE_ERROR;
100544  }
100545  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
100546  *ppCsr = pRet;
100547  return SQLITE_OK;
100548}
100549
100550/*
100551** Implementation of the snippet() function for FTS3
100552*/
100553static void fts3SnippetFunc(
100554  sqlite3_context *pContext,      /* SQLite function call context */
100555  int nVal,                       /* Size of apVal[] array */
100556  sqlite3_value **apVal           /* Array of arguments */
100557){
100558  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100559  const char *zStart = "<b>";
100560  const char *zEnd = "</b>";
100561  const char *zEllipsis = "<b>...</b>";
100562
100563  /* There must be at least one argument passed to this function (otherwise
100564  ** the non-overloaded version would have been called instead of this one).
100565  */
100566  assert( nVal>=1 );
100567
100568  if( nVal>4 ){
100569    sqlite3_result_error(pContext,
100570        "wrong number of arguments to function snippet()", -1);
100571    return;
100572  }
100573  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
100574
100575  switch( nVal ){
100576    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
100577    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
100578    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
100579  }
100580  if( !zEllipsis || !zEnd || !zStart ){
100581    sqlite3_result_error_nomem(pContext);
100582  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100583    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis);
100584  }
100585}
100586
100587/*
100588** Implementation of the snippet2() function for FTS3
100589*/
100590static void fts3Snippet2Func(
100591  sqlite3_context *pContext,      /* SQLite function call context */
100592  int nVal,                       /* Size of apVal[] array */
100593  sqlite3_value **apVal           /* Array of arguments */
100594){
100595  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100596  const char *zStart = "<b>";
100597  const char *zEnd = "</b>";
100598  const char *zEllipsis = "<b>...</b>";
100599  int iCol = -1;
100600  int nToken = 10;
100601
100602  /* There must be at least one argument passed to this function (otherwise
100603  ** the non-overloaded version would have been called instead of this one).
100604  */
100605  assert( nVal>=1 );
100606
100607  if( nVal>6 ){
100608    sqlite3_result_error(pContext,
100609        "wrong number of arguments to function snippet()", -1);
100610    return;
100611  }
100612  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
100613
100614  switch( nVal ){
100615    case 6: nToken = sqlite3_value_int(apVal[5]);
100616    case 5: iCol = sqlite3_value_int(apVal[4]);
100617    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
100618    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
100619    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
100620  }
100621  if( !zEllipsis || !zEnd || !zStart ){
100622    sqlite3_result_error_nomem(pContext);
100623  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100624    sqlite3Fts3Snippet2(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
100625  }
100626}
100627
100628/*
100629** Implementation of the offsets() function for FTS3
100630*/
100631static void fts3OffsetsFunc(
100632  sqlite3_context *pContext,      /* SQLite function call context */
100633  int nVal,                       /* Size of argument array */
100634  sqlite3_value **apVal           /* Array of arguments */
100635){
100636  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100637
100638  UNUSED_PARAMETER(nVal);
100639
100640  assert( nVal==1 );
100641  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
100642  assert( pCsr );
100643  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
100644    sqlite3Fts3Offsets(pContext, pCsr);
100645  }
100646}
100647
100648/*
100649** Implementation of the special optimize() function for FTS3. This
100650** function merges all segments in the database to a single segment.
100651** Example usage is:
100652**
100653**   SELECT optimize(t) FROM t LIMIT 1;
100654**
100655** where 't' is the name of an FTS3 table.
100656*/
100657static void fts3OptimizeFunc(
100658  sqlite3_context *pContext,      /* SQLite function call context */
100659  int nVal,                       /* Size of argument array */
100660  sqlite3_value **apVal           /* Array of arguments */
100661){
100662  int rc;                         /* Return code */
100663  Fts3Table *p;                   /* Virtual table handle */
100664  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
100665
100666  UNUSED_PARAMETER(nVal);
100667
100668  assert( nVal==1 );
100669  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
100670  p = (Fts3Table *)pCursor->base.pVtab;
100671  assert( p );
100672
100673  rc = sqlite3Fts3Optimize(p);
100674
100675  switch( rc ){
100676    case SQLITE_OK:
100677      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
100678      break;
100679    case SQLITE_DONE:
100680      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
100681      break;
100682    default:
100683      sqlite3_result_error_code(pContext, rc);
100684      break;
100685  }
100686}
100687
100688/*
100689** Implementation of the matchinfo() function for FTS3
100690*/
100691static void fts3MatchinfoFunc(
100692  sqlite3_context *pContext,      /* SQLite function call context */
100693  int nVal,                       /* Size of argument array */
100694  sqlite3_value **apVal           /* Array of arguments */
100695){
100696  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
100697
100698  if( nVal!=1 ){
100699    sqlite3_result_error(pContext,
100700        "wrong number of arguments to function matchinfo()", -1);
100701    return;
100702  }
100703
100704  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
100705    sqlite3Fts3Matchinfo(pContext, pCsr);
100706  }
100707}
100708
100709/*
100710** This routine implements the xFindFunction method for the FTS3
100711** virtual table.
100712*/
100713static int fts3FindFunctionMethod(
100714  sqlite3_vtab *pVtab,            /* Virtual table handle */
100715  int nArg,                       /* Number of SQL function arguments */
100716  const char *zName,              /* Name of SQL function */
100717  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
100718  void **ppArg                    /* Unused */
100719){
100720  struct Overloaded {
100721    const char *zName;
100722    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
100723  } aOverload[] = {
100724    { "snippet", fts3SnippetFunc },
100725    { "snippet2", fts3Snippet2Func },
100726    { "offsets", fts3OffsetsFunc },
100727    { "optimize", fts3OptimizeFunc },
100728    { "matchinfo", fts3MatchinfoFunc },
100729  };
100730  int i;                          /* Iterator variable */
100731
100732  UNUSED_PARAMETER(pVtab);
100733  UNUSED_PARAMETER(nArg);
100734  UNUSED_PARAMETER(ppArg);
100735
100736  for(i=0; i<SizeofArray(aOverload); i++){
100737    if( strcmp(zName, aOverload[i].zName)==0 ){
100738      *pxFunc = aOverload[i].xFunc;
100739      return 1;
100740    }
100741  }
100742
100743  /* No function of the specified name was found. Return 0. */
100744  return 0;
100745}
100746
100747/*
100748** Implementation of FTS3 xRename method. Rename an fts3 table.
100749*/
100750static int fts3RenameMethod(
100751  sqlite3_vtab *pVtab,            /* Virtual table handle */
100752  const char *zName               /* New name of table */
100753){
100754  Fts3Table *p = (Fts3Table *)pVtab;
100755  int rc = SQLITE_NOMEM;          /* Return Code */
100756  char *zSql;                     /* SQL script to run to rename tables */
100757
100758  zSql = sqlite3_mprintf(
100759    "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
100760    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
100761    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
100762    , p->zDb, p->zName, zName
100763    , p->zDb, p->zName, zName
100764    , p->zDb, p->zName, zName
100765  );
100766  if( zSql ){
100767    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
100768    sqlite3_free(zSql);
100769  }
100770  return rc;
100771}
100772
100773static const sqlite3_module fts3Module = {
100774  /* iVersion      */ 0,
100775  /* xCreate       */ fts3CreateMethod,
100776  /* xConnect      */ fts3ConnectMethod,
100777  /* xBestIndex    */ fts3BestIndexMethod,
100778  /* xDisconnect   */ fts3DisconnectMethod,
100779  /* xDestroy      */ fts3DestroyMethod,
100780  /* xOpen         */ fts3OpenMethod,
100781  /* xClose        */ fulltextClose,
100782  /* xFilter       */ fts3FilterMethod,
100783  /* xNext         */ fts3NextMethod,
100784  /* xEof          */ fts3EofMethod,
100785  /* xColumn       */ fts3ColumnMethod,
100786  /* xRowid        */ fts3RowidMethod,
100787  /* xUpdate       */ fts3UpdateMethod,
100788  /* xBegin        */ fts3BeginMethod,
100789  /* xSync         */ fts3SyncMethod,
100790  /* xCommit       */ fts3CommitMethod,
100791  /* xRollback     */ fts3RollbackMethod,
100792  /* xFindFunction */ fts3FindFunctionMethod,
100793  /* xRename */       fts3RenameMethod,
100794};
100795
100796/*
100797** This function is registered as the module destructor (called when an
100798** FTS3 enabled database connection is closed). It frees the memory
100799** allocated for the tokenizer hash table.
100800*/
100801static void hashDestroy(void *p){
100802  Fts3Hash *pHash = (Fts3Hash *)p;
100803  sqlite3Fts3HashClear(pHash);
100804  sqlite3_free(pHash);
100805}
100806
100807/*
100808** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
100809** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
100810** two forward declarations are for functions declared in these files
100811** used to retrieve the respective implementations.
100812**
100813** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
100814** to by the argument to point a the "simple" tokenizer implementation.
100815** Function ...PorterTokenizerModule() sets *pModule to point to the
100816** porter tokenizer/stemmer implementation.
100817*/
100818SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
100819SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
100820SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
100821
100822/*
100823** Initialise the fts3 extension. If this extension is built as part
100824** of the sqlite library, then this function is called directly by
100825** SQLite. If fts3 is built as a dynamically loadable extension, this
100826** function is called by the sqlite3_extension_init() entry point.
100827*/
100828SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
100829  int rc = SQLITE_OK;
100830  Fts3Hash *pHash = 0;
100831  const sqlite3_tokenizer_module *pSimple = 0;
100832  const sqlite3_tokenizer_module *pPorter = 0;
100833
100834#ifdef SQLITE_ENABLE_ICU
100835  const sqlite3_tokenizer_module *pIcu = 0;
100836  sqlite3Fts3IcuTokenizerModule(&pIcu);
100837#endif
100838
100839  sqlite3Fts3SimpleTokenizerModule(&pSimple);
100840  sqlite3Fts3PorterTokenizerModule(&pPorter);
100841
100842  /* Allocate and initialise the hash-table used to store tokenizers. */
100843  pHash = sqlite3_malloc(sizeof(Fts3Hash));
100844  if( !pHash ){
100845    rc = SQLITE_NOMEM;
100846  }else{
100847    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
100848  }
100849
100850  /* Load the built-in tokenizers into the hash table */
100851  if( rc==SQLITE_OK ){
100852    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
100853     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
100854#ifdef SQLITE_ENABLE_ICU
100855     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
100856#endif
100857    ){
100858      rc = SQLITE_NOMEM;
100859    }
100860  }
100861
100862#ifdef SQLITE_TEST
100863  if( rc==SQLITE_OK ){
100864    rc = sqlite3Fts3ExprInitTestInterface(db);
100865  }
100866#endif
100867
100868  /* Create the virtual table wrapper around the hash-table and overload
100869  ** the two scalar functions. If this is successful, register the
100870  ** module with sqlite.
100871  */
100872  if( SQLITE_OK==rc
100873   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
100874   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
100875   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet2", -1))
100876   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
100877   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", -1))
100878   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
100879  ){
100880    return sqlite3_create_module_v2(
100881        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
100882    );
100883  }
100884
100885  /* An error has occurred. Delete the hash table and return the error code. */
100886  assert( rc!=SQLITE_OK );
100887  if( pHash ){
100888    sqlite3Fts3HashClear(pHash);
100889    sqlite3_free(pHash);
100890  }
100891  return rc;
100892}
100893
100894#if !SQLITE_CORE
100895SQLITE_API int sqlite3_extension_init(
100896  sqlite3 *db,
100897  char **pzErrMsg,
100898  const sqlite3_api_routines *pApi
100899){
100900  SQLITE_EXTENSION_INIT2(pApi)
100901  return sqlite3Fts3Init(db);
100902}
100903#endif
100904
100905#endif
100906
100907/************** End of fts3.c ************************************************/
100908/************** Begin file fts3_expr.c ***************************************/
100909/*
100910** 2008 Nov 28
100911**
100912** The author disclaims copyright to this source code.  In place of
100913** a legal notice, here is a blessing:
100914**
100915**    May you do good and not evil.
100916**    May you find forgiveness for yourself and forgive others.
100917**    May you share freely, never taking more than you give.
100918**
100919******************************************************************************
100920**
100921** This module contains code that implements a parser for fts3 query strings
100922** (the right-hand argument to the MATCH operator). Because the supported
100923** syntax is relatively simple, the whole tokenizer/parser system is
100924** hand-coded.
100925*/
100926#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
100927
100928/*
100929** By default, this module parses the legacy syntax that has been
100930** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
100931** is defined, then it uses the new syntax. The differences between
100932** the new and the old syntaxes are:
100933**
100934**  a) The new syntax supports parenthesis. The old does not.
100935**
100936**  b) The new syntax supports the AND and NOT operators. The old does not.
100937**
100938**  c) The old syntax supports the "-" token qualifier. This is not
100939**     supported by the new syntax (it is replaced by the NOT operator).
100940**
100941**  d) When using the old syntax, the OR operator has a greater precedence
100942**     than an implicit AND. When using the new, both implicity and explicit
100943**     AND operators have a higher precedence than OR.
100944**
100945** If compiled with SQLITE_TEST defined, then this module exports the
100946** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
100947** to zero causes the module to use the old syntax. If it is set to
100948** non-zero the new syntax is activated. This is so both syntaxes can
100949** be tested using a single build of testfixture.
100950**
100951** The following describes the syntax supported by the fts3 MATCH
100952** operator in a similar format to that used by the lemon parser
100953** generator. This module does not use actually lemon, it uses a
100954** custom parser.
100955**
100956**   query ::= andexpr (OR andexpr)*.
100957**
100958**   andexpr ::= notexpr (AND? notexpr)*.
100959**
100960**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
100961**   notexpr ::= LP query RP.
100962**
100963**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
100964**
100965**   distance_opt ::= .
100966**   distance_opt ::= / INTEGER.
100967**
100968**   phrase ::= TOKEN.
100969**   phrase ::= COLUMN:TOKEN.
100970**   phrase ::= "TOKEN TOKEN TOKEN...".
100971*/
100972
100973#ifdef SQLITE_TEST
100974SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
100975#else
100976# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
100977#  define sqlite3_fts3_enable_parentheses 1
100978# else
100979#  define sqlite3_fts3_enable_parentheses 0
100980# endif
100981#endif
100982
100983/*
100984** Default span for NEAR operators.
100985*/
100986#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
100987
100988
100989typedef struct ParseContext ParseContext;
100990struct ParseContext {
100991  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
100992  const char **azCol;                 /* Array of column names for fts3 table */
100993  int nCol;                           /* Number of entries in azCol[] */
100994  int iDefaultCol;                    /* Default column to query */
100995  sqlite3_context *pCtx;              /* Write error message here */
100996  int nNest;                          /* Number of nested brackets */
100997};
100998
100999/*
101000** This function is equivalent to the standard isspace() function.
101001**
101002** The standard isspace() can be awkward to use safely, because although it
101003** is defined to accept an argument of type int, its behaviour when passed
101004** an integer that falls outside of the range of the unsigned char type
101005** is undefined (and sometimes, "undefined" means segfault). This wrapper
101006** is defined to accept an argument of type char, and always returns 0 for
101007** any values that fall outside of the range of the unsigned char type (i.e.
101008** negative values).
101009*/
101010static int fts3isspace(char c){
101011  return (c&0x80)==0 ? isspace(c) : 0;
101012}
101013
101014/*
101015** Extract the next token from buffer z (length n) using the tokenizer
101016** and other information (column names etc.) in pParse. Create an Fts3Expr
101017** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
101018** single token and set *ppExpr to point to it. If the end of the buffer is
101019** reached before a token is found, set *ppExpr to zero. It is the
101020** responsibility of the caller to eventually deallocate the allocated
101021** Fts3Expr structure (if any) by passing it to sqlite3_free().
101022**
101023** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
101024** fails.
101025*/
101026static int getNextToken(
101027  ParseContext *pParse,                   /* fts3 query parse context */
101028  int iCol,                               /* Value for Fts3Phrase.iColumn */
101029  const char *z, int n,                   /* Input string */
101030  Fts3Expr **ppExpr,                      /* OUT: expression */
101031  int *pnConsumed                         /* OUT: Number of bytes consumed */
101032){
101033  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
101034  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
101035  int rc;
101036  sqlite3_tokenizer_cursor *pCursor;
101037  Fts3Expr *pRet = 0;
101038  int nConsumed = 0;
101039
101040  rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
101041  if( rc==SQLITE_OK ){
101042    const char *zToken;
101043    int nToken, iStart, iEnd, iPosition;
101044    int nByte;                               /* total space to allocate */
101045
101046    pCursor->pTokenizer = pTokenizer;
101047    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
101048
101049    if( rc==SQLITE_OK ){
101050      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
101051      pRet = (Fts3Expr *)sqlite3_malloc(nByte);
101052      if( !pRet ){
101053        rc = SQLITE_NOMEM;
101054      }else{
101055        memset(pRet, 0, nByte);
101056        pRet->eType = FTSQUERY_PHRASE;
101057        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
101058        pRet->pPhrase->nToken = 1;
101059        pRet->pPhrase->iColumn = iCol;
101060        pRet->pPhrase->aToken[0].n = nToken;
101061        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
101062        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
101063
101064        if( iEnd<n && z[iEnd]=='*' ){
101065          pRet->pPhrase->aToken[0].isPrefix = 1;
101066          iEnd++;
101067        }
101068        if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
101069          pRet->pPhrase->isNot = 1;
101070        }
101071      }
101072      nConsumed = iEnd;
101073    }
101074
101075    pModule->xClose(pCursor);
101076  }
101077
101078  *pnConsumed = nConsumed;
101079  *ppExpr = pRet;
101080  return rc;
101081}
101082
101083
101084/*
101085** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
101086** then free the old allocation.
101087*/
101088static void *fts3ReallocOrFree(void *pOrig, int nNew){
101089  void *pRet = sqlite3_realloc(pOrig, nNew);
101090  if( !pRet ){
101091    sqlite3_free(pOrig);
101092  }
101093  return pRet;
101094}
101095
101096/*
101097** Buffer zInput, length nInput, contains the contents of a quoted string
101098** that appeared as part of an fts3 query expression. Neither quote character
101099** is included in the buffer. This function attempts to tokenize the entire
101100** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
101101** containing the results.
101102**
101103** If successful, SQLITE_OK is returned and *ppExpr set to point at the
101104** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
101105** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
101106** to 0.
101107*/
101108static int getNextString(
101109  ParseContext *pParse,                   /* fts3 query parse context */
101110  const char *zInput, int nInput,         /* Input string */
101111  Fts3Expr **ppExpr                       /* OUT: expression */
101112){
101113  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
101114  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
101115  int rc;
101116  Fts3Expr *p = 0;
101117  sqlite3_tokenizer_cursor *pCursor = 0;
101118  char *zTemp = 0;
101119  int nTemp = 0;
101120
101121  rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
101122  if( rc==SQLITE_OK ){
101123    int ii;
101124    pCursor->pTokenizer = pTokenizer;
101125    for(ii=0; rc==SQLITE_OK; ii++){
101126      const char *zToken;
101127      int nToken, iBegin, iEnd, iPos;
101128      rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
101129      if( rc==SQLITE_OK ){
101130        int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
101131        p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
101132        zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
101133        if( !p || !zTemp ){
101134          goto no_mem;
101135        }
101136        if( ii==0 ){
101137          memset(p, 0, nByte);
101138          p->pPhrase = (Fts3Phrase *)&p[1];
101139        }
101140        p->pPhrase = (Fts3Phrase *)&p[1];
101141        p->pPhrase->nToken = ii+1;
101142        p->pPhrase->aToken[ii].n = nToken;
101143        memcpy(&zTemp[nTemp], zToken, nToken);
101144        nTemp += nToken;
101145        if( iEnd<nInput && zInput[iEnd]=='*' ){
101146          p->pPhrase->aToken[ii].isPrefix = 1;
101147        }else{
101148          p->pPhrase->aToken[ii].isPrefix = 0;
101149        }
101150      }
101151    }
101152
101153    pModule->xClose(pCursor);
101154    pCursor = 0;
101155  }
101156
101157  if( rc==SQLITE_DONE ){
101158    int jj;
101159    char *zNew = NULL;
101160    int nNew = 0;
101161    int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
101162    nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
101163    p = fts3ReallocOrFree(p, nByte + nTemp);
101164    if( !p ){
101165      goto no_mem;
101166    }
101167    if( zTemp ){
101168      zNew = &(((char *)p)[nByte]);
101169      memcpy(zNew, zTemp, nTemp);
101170    }else{
101171      memset(p, 0, nByte+nTemp);
101172    }
101173    p->pPhrase = (Fts3Phrase *)&p[1];
101174    for(jj=0; jj<p->pPhrase->nToken; jj++){
101175      p->pPhrase->aToken[jj].z = &zNew[nNew];
101176      nNew += p->pPhrase->aToken[jj].n;
101177    }
101178    sqlite3_free(zTemp);
101179    p->eType = FTSQUERY_PHRASE;
101180    p->pPhrase->iColumn = pParse->iDefaultCol;
101181    rc = SQLITE_OK;
101182  }
101183
101184  *ppExpr = p;
101185  return rc;
101186no_mem:
101187
101188  if( pCursor ){
101189    pModule->xClose(pCursor);
101190  }
101191  sqlite3_free(zTemp);
101192  sqlite3_free(p);
101193  *ppExpr = 0;
101194  return SQLITE_NOMEM;
101195}
101196
101197/*
101198** Function getNextNode(), which is called by fts3ExprParse(), may itself
101199** call fts3ExprParse(). So this forward declaration is required.
101200*/
101201static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
101202
101203/*
101204** The output variable *ppExpr is populated with an allocated Fts3Expr
101205** structure, or set to 0 if the end of the input buffer is reached.
101206**
101207** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
101208** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
101209** If SQLITE_ERROR is returned, pContext is populated with an error message.
101210*/
101211static int getNextNode(
101212  ParseContext *pParse,                   /* fts3 query parse context */
101213  const char *z, int n,                   /* Input string */
101214  Fts3Expr **ppExpr,                      /* OUT: expression */
101215  int *pnConsumed                         /* OUT: Number of bytes consumed */
101216){
101217  static const struct Fts3Keyword {
101218    char *z;                              /* Keyword text */
101219    unsigned char n;                      /* Length of the keyword */
101220    unsigned char parenOnly;              /* Only valid in paren mode */
101221    unsigned char eType;                  /* Keyword code */
101222  } aKeyword[] = {
101223    { "OR" ,  2, 0, FTSQUERY_OR   },
101224    { "AND",  3, 1, FTSQUERY_AND  },
101225    { "NOT",  3, 1, FTSQUERY_NOT  },
101226    { "NEAR", 4, 0, FTSQUERY_NEAR }
101227  };
101228  int ii;
101229  int iCol;
101230  int iColLen;
101231  int rc;
101232  Fts3Expr *pRet = 0;
101233
101234  const char *zInput = z;
101235  int nInput = n;
101236
101237  /* Skip over any whitespace before checking for a keyword, an open or
101238  ** close bracket, or a quoted string.
101239  */
101240  while( nInput>0 && fts3isspace(*zInput) ){
101241    nInput--;
101242    zInput++;
101243  }
101244  if( nInput==0 ){
101245    return SQLITE_DONE;
101246  }
101247
101248  /* See if we are dealing with a keyword. */
101249  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
101250    const struct Fts3Keyword *pKey = &aKeyword[ii];
101251
101252    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
101253      continue;
101254    }
101255
101256    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
101257      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
101258      int nKey = pKey->n;
101259      char cNext;
101260
101261      /* If this is a "NEAR" keyword, check for an explicit nearness. */
101262      if( pKey->eType==FTSQUERY_NEAR ){
101263        assert( nKey==4 );
101264        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
101265          nNear = 0;
101266          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
101267            nNear = nNear * 10 + (zInput[nKey] - '0');
101268          }
101269        }
101270      }
101271
101272      /* At this point this is probably a keyword. But for that to be true,
101273      ** the next byte must contain either whitespace, an open or close
101274      ** parenthesis, a quote character, or EOF.
101275      */
101276      cNext = zInput[nKey];
101277      if( fts3isspace(cNext)
101278       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
101279      ){
101280        pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
101281        if( !pRet ){
101282          return SQLITE_NOMEM;
101283        }
101284        memset(pRet, 0, sizeof(Fts3Expr));
101285        pRet->eType = pKey->eType;
101286        pRet->nNear = nNear;
101287        *ppExpr = pRet;
101288        *pnConsumed = (int)((zInput - z) + nKey);
101289        return SQLITE_OK;
101290      }
101291
101292      /* Turns out that wasn't a keyword after all. This happens if the
101293      ** user has supplied a token such as "ORacle". Continue.
101294      */
101295    }
101296  }
101297
101298  /* Check for an open bracket. */
101299  if( sqlite3_fts3_enable_parentheses ){
101300    if( *zInput=='(' ){
101301      int nConsumed;
101302      int rc;
101303      pParse->nNest++;
101304      rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
101305      if( rc==SQLITE_OK && !*ppExpr ){
101306        rc = SQLITE_DONE;
101307      }
101308      *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
101309      return rc;
101310    }
101311
101312    /* Check for a close bracket. */
101313    if( *zInput==')' ){
101314      pParse->nNest--;
101315      *pnConsumed = (int)((zInput - z) + 1);
101316      return SQLITE_DONE;
101317    }
101318  }
101319
101320  /* See if we are dealing with a quoted phrase. If this is the case, then
101321  ** search for the closing quote and pass the whole string to getNextString()
101322  ** for processing. This is easy to do, as fts3 has no syntax for escaping
101323  ** a quote character embedded in a string.
101324  */
101325  if( *zInput=='"' ){
101326    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
101327    *pnConsumed = (int)((zInput - z) + ii + 1);
101328    if( ii==nInput ){
101329      return SQLITE_ERROR;
101330    }
101331    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
101332  }
101333
101334
101335  /* If control flows to this point, this must be a regular token, or
101336  ** the end of the input. Read a regular token using the sqlite3_tokenizer
101337  ** interface. Before doing so, figure out if there is an explicit
101338  ** column specifier for the token.
101339  **
101340  ** TODO: Strangely, it is not possible to associate a column specifier
101341  ** with a quoted phrase, only with a single token. Not sure if this was
101342  ** an implementation artifact or an intentional decision when fts3 was
101343  ** first implemented. Whichever it was, this module duplicates the
101344  ** limitation.
101345  */
101346  iCol = pParse->iDefaultCol;
101347  iColLen = 0;
101348  for(ii=0; ii<pParse->nCol; ii++){
101349    const char *zStr = pParse->azCol[ii];
101350    int nStr = (int)strlen(zStr);
101351    if( nInput>nStr && zInput[nStr]==':'
101352     && sqlite3_strnicmp(zStr, zInput, nStr)==0
101353    ){
101354      iCol = ii;
101355      iColLen = (int)((zInput - z) + nStr + 1);
101356      break;
101357    }
101358  }
101359  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
101360  *pnConsumed += iColLen;
101361  return rc;
101362}
101363
101364/*
101365** The argument is an Fts3Expr structure for a binary operator (any type
101366** except an FTSQUERY_PHRASE). Return an integer value representing the
101367** precedence of the operator. Lower values have a higher precedence (i.e.
101368** group more tightly). For example, in the C language, the == operator
101369** groups more tightly than ||, and would therefore have a higher precedence.
101370**
101371** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
101372** is defined), the order of the operators in precedence from highest to
101373** lowest is:
101374**
101375**   NEAR
101376**   NOT
101377**   AND (including implicit ANDs)
101378**   OR
101379**
101380** Note that when using the old query syntax, the OR operator has a higher
101381** precedence than the AND operator.
101382*/
101383static int opPrecedence(Fts3Expr *p){
101384  assert( p->eType!=FTSQUERY_PHRASE );
101385  if( sqlite3_fts3_enable_parentheses ){
101386    return p->eType;
101387  }else if( p->eType==FTSQUERY_NEAR ){
101388    return 1;
101389  }else if( p->eType==FTSQUERY_OR ){
101390    return 2;
101391  }
101392  assert( p->eType==FTSQUERY_AND );
101393  return 3;
101394}
101395
101396/*
101397** Argument ppHead contains a pointer to the current head of a query
101398** expression tree being parsed. pPrev is the expression node most recently
101399** inserted into the tree. This function adds pNew, which is always a binary
101400** operator node, into the expression tree based on the relative precedence
101401** of pNew and the existing nodes of the tree. This may result in the head
101402** of the tree changing, in which case *ppHead is set to the new root node.
101403*/
101404static void insertBinaryOperator(
101405  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
101406  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
101407  Fts3Expr *pNew           /* New binary node to insert into expression tree */
101408){
101409  Fts3Expr *pSplit = pPrev;
101410  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
101411    pSplit = pSplit->pParent;
101412  }
101413
101414  if( pSplit->pParent ){
101415    assert( pSplit->pParent->pRight==pSplit );
101416    pSplit->pParent->pRight = pNew;
101417    pNew->pParent = pSplit->pParent;
101418  }else{
101419    *ppHead = pNew;
101420  }
101421  pNew->pLeft = pSplit;
101422  pSplit->pParent = pNew;
101423}
101424
101425/*
101426** Parse the fts3 query expression found in buffer z, length n. This function
101427** returns either when the end of the buffer is reached or an unmatched
101428** closing bracket - ')' - is encountered.
101429**
101430** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
101431** parsed form of the expression and *pnConsumed is set to the number of
101432** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
101433** (out of memory error) or SQLITE_ERROR (parse error) is returned.
101434*/
101435static int fts3ExprParse(
101436  ParseContext *pParse,                   /* fts3 query parse context */
101437  const char *z, int n,                   /* Text of MATCH query */
101438  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
101439  int *pnConsumed                         /* OUT: Number of bytes consumed */
101440){
101441  Fts3Expr *pRet = 0;
101442  Fts3Expr *pPrev = 0;
101443  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
101444  int nIn = n;
101445  const char *zIn = z;
101446  int rc = SQLITE_OK;
101447  int isRequirePhrase = 1;
101448
101449  while( rc==SQLITE_OK ){
101450    Fts3Expr *p = 0;
101451    int nByte = 0;
101452    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
101453    if( rc==SQLITE_OK ){
101454      int isPhrase;
101455
101456      if( !sqlite3_fts3_enable_parentheses
101457       && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot
101458      ){
101459        /* Create an implicit NOT operator. */
101460        Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
101461        if( !pNot ){
101462          sqlite3Fts3ExprFree(p);
101463          rc = SQLITE_NOMEM;
101464          goto exprparse_out;
101465        }
101466        memset(pNot, 0, sizeof(Fts3Expr));
101467        pNot->eType = FTSQUERY_NOT;
101468        pNot->pRight = p;
101469        if( pNotBranch ){
101470          pNot->pLeft = pNotBranch;
101471        }
101472        pNotBranch = pNot;
101473        p = pPrev;
101474      }else{
101475        int eType = p->eType;
101476        assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
101477        isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
101478
101479        /* The isRequirePhrase variable is set to true if a phrase or
101480        ** an expression contained in parenthesis is required. If a
101481        ** binary operator (AND, OR, NOT or NEAR) is encounted when
101482        ** isRequirePhrase is set, this is a syntax error.
101483        */
101484        if( !isPhrase && isRequirePhrase ){
101485          sqlite3Fts3ExprFree(p);
101486          rc = SQLITE_ERROR;
101487          goto exprparse_out;
101488        }
101489
101490        if( isPhrase && !isRequirePhrase ){
101491          /* Insert an implicit AND operator. */
101492          Fts3Expr *pAnd;
101493          assert( pRet && pPrev );
101494          pAnd = sqlite3_malloc(sizeof(Fts3Expr));
101495          if( !pAnd ){
101496            sqlite3Fts3ExprFree(p);
101497            rc = SQLITE_NOMEM;
101498            goto exprparse_out;
101499          }
101500          memset(pAnd, 0, sizeof(Fts3Expr));
101501          pAnd->eType = FTSQUERY_AND;
101502          insertBinaryOperator(&pRet, pPrev, pAnd);
101503          pPrev = pAnd;
101504        }
101505
101506        /* This test catches attempts to make either operand of a NEAR
101507        ** operator something other than a phrase. For example, either of
101508        ** the following:
101509        **
101510        **    (bracketed expression) NEAR phrase
101511        **    phrase NEAR (bracketed expression)
101512        **
101513        ** Return an error in either case.
101514        */
101515        if( pPrev && (
101516            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
101517         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
101518        )){
101519          sqlite3Fts3ExprFree(p);
101520          rc = SQLITE_ERROR;
101521          goto exprparse_out;
101522        }
101523
101524        if( isPhrase ){
101525          if( pRet ){
101526            assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
101527            pPrev->pRight = p;
101528            p->pParent = pPrev;
101529          }else{
101530            pRet = p;
101531          }
101532        }else{
101533          insertBinaryOperator(&pRet, pPrev, p);
101534        }
101535        isRequirePhrase = !isPhrase;
101536      }
101537      assert( nByte>0 );
101538    }
101539    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
101540    nIn -= nByte;
101541    zIn += nByte;
101542    pPrev = p;
101543  }
101544
101545  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
101546    rc = SQLITE_ERROR;
101547  }
101548
101549  if( rc==SQLITE_DONE ){
101550    rc = SQLITE_OK;
101551    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
101552      if( !pRet ){
101553        rc = SQLITE_ERROR;
101554      }else{
101555        Fts3Expr *pIter = pNotBranch;
101556        while( pIter->pLeft ){
101557          pIter = pIter->pLeft;
101558        }
101559        pIter->pLeft = pRet;
101560        pRet = pNotBranch;
101561      }
101562    }
101563  }
101564  *pnConsumed = n - nIn;
101565
101566exprparse_out:
101567  if( rc!=SQLITE_OK ){
101568    sqlite3Fts3ExprFree(pRet);
101569    sqlite3Fts3ExprFree(pNotBranch);
101570    pRet = 0;
101571  }
101572  *ppExpr = pRet;
101573  return rc;
101574}
101575
101576/*
101577** Parameters z and n contain a pointer to and length of a buffer containing
101578** an fts3 query expression, respectively. This function attempts to parse the
101579** query expression and create a tree of Fts3Expr structures representing the
101580** parsed expression. If successful, *ppExpr is set to point to the head
101581** of the parsed expression tree and SQLITE_OK is returned. If an error
101582** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
101583** error) is returned and *ppExpr is set to 0.
101584**
101585** If parameter n is a negative number, then z is assumed to point to a
101586** nul-terminated string and the length is determined using strlen().
101587**
101588** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
101589** use to normalize query tokens while parsing the expression. The azCol[]
101590** array, which is assumed to contain nCol entries, should contain the names
101591** of each column in the target fts3 table, in order from left to right.
101592** Column names must be nul-terminated strings.
101593**
101594** The iDefaultCol parameter should be passed the index of the table column
101595** that appears on the left-hand-side of the MATCH operator (the default
101596** column to match against for tokens for which a column name is not explicitly
101597** specified as part of the query string), or -1 if tokens may by default
101598** match any table column.
101599*/
101600SQLITE_PRIVATE int sqlite3Fts3ExprParse(
101601  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
101602  char **azCol,                       /* Array of column names for fts3 table */
101603  int nCol,                           /* Number of entries in azCol[] */
101604  int iDefaultCol,                    /* Default column to query */
101605  const char *z, int n,               /* Text of MATCH query */
101606  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
101607){
101608  int nParsed;
101609  int rc;
101610  ParseContext sParse;
101611  sParse.pTokenizer = pTokenizer;
101612  sParse.azCol = (const char **)azCol;
101613  sParse.nCol = nCol;
101614  sParse.iDefaultCol = iDefaultCol;
101615  sParse.nNest = 0;
101616  if( z==0 ){
101617    *ppExpr = 0;
101618    return SQLITE_OK;
101619  }
101620  if( n<0 ){
101621    n = (int)strlen(z);
101622  }
101623  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
101624
101625  /* Check for mismatched parenthesis */
101626  if( rc==SQLITE_OK && sParse.nNest ){
101627    rc = SQLITE_ERROR;
101628    sqlite3Fts3ExprFree(*ppExpr);
101629    *ppExpr = 0;
101630  }
101631
101632  return rc;
101633}
101634
101635/*
101636** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
101637*/
101638SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
101639  if( p ){
101640    sqlite3Fts3ExprFree(p->pLeft);
101641    sqlite3Fts3ExprFree(p->pRight);
101642    sqlite3_free(p->aDoclist);
101643    sqlite3_free(p);
101644  }
101645}
101646
101647/****************************************************************************
101648*****************************************************************************
101649** Everything after this point is just test code.
101650*/
101651
101652#ifdef SQLITE_TEST
101653
101654
101655/*
101656** Function to query the hash-table of tokenizers (see README.tokenizers).
101657*/
101658static int queryTestTokenizer(
101659  sqlite3 *db,
101660  const char *zName,
101661  const sqlite3_tokenizer_module **pp
101662){
101663  int rc;
101664  sqlite3_stmt *pStmt;
101665  const char zSql[] = "SELECT fts3_tokenizer(?)";
101666
101667  *pp = 0;
101668  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
101669  if( rc!=SQLITE_OK ){
101670    return rc;
101671  }
101672
101673  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
101674  if( SQLITE_ROW==sqlite3_step(pStmt) ){
101675    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
101676      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
101677    }
101678  }
101679
101680  return sqlite3_finalize(pStmt);
101681}
101682
101683/*
101684** This function is part of the test interface for the query parser. It
101685** writes a text representation of the query expression pExpr into the
101686** buffer pointed to by argument zBuf. It is assumed that zBuf is large
101687** enough to store the required text representation.
101688*/
101689static void exprToString(Fts3Expr *pExpr, char *zBuf){
101690  switch( pExpr->eType ){
101691    case FTSQUERY_PHRASE: {
101692      Fts3Phrase *pPhrase = pExpr->pPhrase;
101693      int i;
101694      zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
101695      for(i=0; i<pPhrase->nToken; i++){
101696        zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
101697        zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
101698      }
101699      return;
101700    }
101701
101702    case FTSQUERY_NEAR:
101703      zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
101704      break;
101705    case FTSQUERY_NOT:
101706      zBuf += sprintf(zBuf, "NOT ");
101707      break;
101708    case FTSQUERY_AND:
101709      zBuf += sprintf(zBuf, "AND ");
101710      break;
101711    case FTSQUERY_OR:
101712      zBuf += sprintf(zBuf, "OR ");
101713      break;
101714  }
101715
101716  zBuf += sprintf(zBuf, "{");
101717  exprToString(pExpr->pLeft, zBuf);
101718  zBuf += strlen(zBuf);
101719  zBuf += sprintf(zBuf, "} ");
101720
101721  zBuf += sprintf(zBuf, "{");
101722  exprToString(pExpr->pRight, zBuf);
101723  zBuf += strlen(zBuf);
101724  zBuf += sprintf(zBuf, "}");
101725}
101726
101727/*
101728** This is the implementation of a scalar SQL function used to test the
101729** expression parser. It should be called as follows:
101730**
101731**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
101732**
101733** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
101734** to parse the query expression (see README.tokenizers). The second argument
101735** is the query expression to parse. Each subsequent argument is the name
101736** of a column of the fts3 table that the query expression may refer to.
101737** For example:
101738**
101739**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
101740*/
101741static void fts3ExprTest(
101742  sqlite3_context *context,
101743  int argc,
101744  sqlite3_value **argv
101745){
101746  sqlite3_tokenizer_module const *pModule = 0;
101747  sqlite3_tokenizer *pTokenizer = 0;
101748  int rc;
101749  char **azCol = 0;
101750  const char *zExpr;
101751  int nExpr;
101752  int nCol;
101753  int ii;
101754  Fts3Expr *pExpr;
101755  sqlite3 *db = sqlite3_context_db_handle(context);
101756
101757  if( argc<3 ){
101758    sqlite3_result_error(context,
101759        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
101760    );
101761    return;
101762  }
101763
101764  rc = queryTestTokenizer(db,
101765                          (const char *)sqlite3_value_text(argv[0]), &pModule);
101766  if( rc==SQLITE_NOMEM ){
101767    sqlite3_result_error_nomem(context);
101768    goto exprtest_out;
101769  }else if( !pModule ){
101770    sqlite3_result_error(context, "No such tokenizer module", -1);
101771    goto exprtest_out;
101772  }
101773
101774  rc = pModule->xCreate(0, 0, &pTokenizer);
101775  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
101776  if( rc==SQLITE_NOMEM ){
101777    sqlite3_result_error_nomem(context);
101778    goto exprtest_out;
101779  }
101780  pTokenizer->pModule = pModule;
101781
101782  zExpr = (const char *)sqlite3_value_text(argv[1]);
101783  nExpr = sqlite3_value_bytes(argv[1]);
101784  nCol = argc-2;
101785  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
101786  if( !azCol ){
101787    sqlite3_result_error_nomem(context);
101788    goto exprtest_out;
101789  }
101790  for(ii=0; ii<nCol; ii++){
101791    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
101792  }
101793
101794  rc = sqlite3Fts3ExprParse(
101795      pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
101796  );
101797  if( rc==SQLITE_NOMEM ){
101798    sqlite3_result_error_nomem(context);
101799    goto exprtest_out;
101800  }else if( rc==SQLITE_OK ){
101801    char zBuf[4096];
101802    exprToString(pExpr, zBuf);
101803    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
101804    sqlite3Fts3ExprFree(pExpr);
101805  }else{
101806    sqlite3_result_error(context, "Error parsing expression", -1);
101807  }
101808
101809exprtest_out:
101810  if( pModule && pTokenizer ){
101811    rc = pModule->xDestroy(pTokenizer);
101812  }
101813  sqlite3_free(azCol);
101814}
101815
101816/*
101817** Register the query expression parser test function fts3_exprtest()
101818** with database connection db.
101819*/
101820SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
101821  return sqlite3_create_function(
101822      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
101823  );
101824}
101825
101826#endif
101827#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
101828
101829/************** End of fts3_expr.c *******************************************/
101830/************** Begin file fts3_hash.c ***************************************/
101831/*
101832** 2001 September 22
101833**
101834** The author disclaims copyright to this source code.  In place of
101835** a legal notice, here is a blessing:
101836**
101837**    May you do good and not evil.
101838**    May you find forgiveness for yourself and forgive others.
101839**    May you share freely, never taking more than you give.
101840**
101841*************************************************************************
101842** This is the implementation of generic hash-tables used in SQLite.
101843** We've modified it slightly to serve as a standalone hash table
101844** implementation for the full-text indexing module.
101845*/
101846
101847/*
101848** The code in this file is only compiled if:
101849**
101850**     * The FTS3 module is being built as an extension
101851**       (in which case SQLITE_CORE is not defined), or
101852**
101853**     * The FTS3 module is being built into the core of
101854**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
101855*/
101856#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
101857
101858
101859
101860/*
101861** Malloc and Free functions
101862*/
101863static void *fts3HashMalloc(int n){
101864  void *p = sqlite3_malloc(n);
101865  if( p ){
101866    memset(p, 0, n);
101867  }
101868  return p;
101869}
101870static void fts3HashFree(void *p){
101871  sqlite3_free(p);
101872}
101873
101874/* Turn bulk memory into a hash table object by initializing the
101875** fields of the Hash structure.
101876**
101877** "pNew" is a pointer to the hash table that is to be initialized.
101878** keyClass is one of the constants
101879** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
101880** determines what kind of key the hash table will use.  "copyKey" is
101881** true if the hash table should make its own private copy of keys and
101882** false if it should just use the supplied pointer.
101883*/
101884SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
101885  assert( pNew!=0 );
101886  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
101887  pNew->keyClass = keyClass;
101888  pNew->copyKey = copyKey;
101889  pNew->first = 0;
101890  pNew->count = 0;
101891  pNew->htsize = 0;
101892  pNew->ht = 0;
101893}
101894
101895/* Remove all entries from a hash table.  Reclaim all memory.
101896** Call this routine to delete a hash table or to reset a hash table
101897** to the empty state.
101898*/
101899SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
101900  Fts3HashElem *elem;         /* For looping over all elements of the table */
101901
101902  assert( pH!=0 );
101903  elem = pH->first;
101904  pH->first = 0;
101905  fts3HashFree(pH->ht);
101906  pH->ht = 0;
101907  pH->htsize = 0;
101908  while( elem ){
101909    Fts3HashElem *next_elem = elem->next;
101910    if( pH->copyKey && elem->pKey ){
101911      fts3HashFree(elem->pKey);
101912    }
101913    fts3HashFree(elem);
101914    elem = next_elem;
101915  }
101916  pH->count = 0;
101917}
101918
101919/*
101920** Hash and comparison functions when the mode is FTS3_HASH_STRING
101921*/
101922static int fts3StrHash(const void *pKey, int nKey){
101923  const char *z = (const char *)pKey;
101924  int h = 0;
101925  if( nKey<=0 ) nKey = (int) strlen(z);
101926  while( nKey > 0  ){
101927    h = (h<<3) ^ h ^ *z++;
101928    nKey--;
101929  }
101930  return h & 0x7fffffff;
101931}
101932static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
101933  if( n1!=n2 ) return 1;
101934  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
101935}
101936
101937/*
101938** Hash and comparison functions when the mode is FTS3_HASH_BINARY
101939*/
101940static int fts3BinHash(const void *pKey, int nKey){
101941  int h = 0;
101942  const char *z = (const char *)pKey;
101943  while( nKey-- > 0 ){
101944    h = (h<<3) ^ h ^ *(z++);
101945  }
101946  return h & 0x7fffffff;
101947}
101948static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
101949  if( n1!=n2 ) return 1;
101950  return memcmp(pKey1,pKey2,n1);
101951}
101952
101953/*
101954** Return a pointer to the appropriate hash function given the key class.
101955**
101956** The C syntax in this function definition may be unfamilar to some
101957** programmers, so we provide the following additional explanation:
101958**
101959** The name of the function is "ftsHashFunction".  The function takes a
101960** single parameter "keyClass".  The return value of ftsHashFunction()
101961** is a pointer to another function.  Specifically, the return value
101962** of ftsHashFunction() is a pointer to a function that takes two parameters
101963** with types "const void*" and "int" and returns an "int".
101964*/
101965static int (*ftsHashFunction(int keyClass))(const void*,int){
101966  if( keyClass==FTS3_HASH_STRING ){
101967    return &fts3StrHash;
101968  }else{
101969    assert( keyClass==FTS3_HASH_BINARY );
101970    return &fts3BinHash;
101971  }
101972}
101973
101974/*
101975** Return a pointer to the appropriate hash function given the key class.
101976**
101977** For help in interpreted the obscure C code in the function definition,
101978** see the header comment on the previous function.
101979*/
101980static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
101981  if( keyClass==FTS3_HASH_STRING ){
101982    return &fts3StrCompare;
101983  }else{
101984    assert( keyClass==FTS3_HASH_BINARY );
101985    return &fts3BinCompare;
101986  }
101987}
101988
101989/* Link an element into the hash table
101990*/
101991static void fts3HashInsertElement(
101992  Fts3Hash *pH,            /* The complete hash table */
101993  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
101994  Fts3HashElem *pNew       /* The element to be inserted */
101995){
101996  Fts3HashElem *pHead;     /* First element already in pEntry */
101997  pHead = pEntry->chain;
101998  if( pHead ){
101999    pNew->next = pHead;
102000    pNew->prev = pHead->prev;
102001    if( pHead->prev ){ pHead->prev->next = pNew; }
102002    else             { pH->first = pNew; }
102003    pHead->prev = pNew;
102004  }else{
102005    pNew->next = pH->first;
102006    if( pH->first ){ pH->first->prev = pNew; }
102007    pNew->prev = 0;
102008    pH->first = pNew;
102009  }
102010  pEntry->count++;
102011  pEntry->chain = pNew;
102012}
102013
102014
102015/* Resize the hash table so that it cantains "new_size" buckets.
102016** "new_size" must be a power of 2.  The hash table might fail
102017** to resize if sqliteMalloc() fails.
102018**
102019** Return non-zero if a memory allocation error occurs.
102020*/
102021static int fts3Rehash(Fts3Hash *pH, int new_size){
102022  struct _fts3ht *new_ht;          /* The new hash table */
102023  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
102024  int (*xHash)(const void*,int);   /* The hash function */
102025
102026  assert( (new_size & (new_size-1))==0 );
102027  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
102028  if( new_ht==0 ) return 1;
102029  fts3HashFree(pH->ht);
102030  pH->ht = new_ht;
102031  pH->htsize = new_size;
102032  xHash = ftsHashFunction(pH->keyClass);
102033  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
102034    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
102035    next_elem = elem->next;
102036    fts3HashInsertElement(pH, &new_ht[h], elem);
102037  }
102038  return 0;
102039}
102040
102041/* This function (for internal use only) locates an element in an
102042** hash table that matches the given key.  The hash for this key has
102043** already been computed and is passed as the 4th parameter.
102044*/
102045static Fts3HashElem *fts3FindElementByHash(
102046  const Fts3Hash *pH, /* The pH to be searched */
102047  const void *pKey,   /* The key we are searching for */
102048  int nKey,
102049  int h               /* The hash for this key. */
102050){
102051  Fts3HashElem *elem;            /* Used to loop thru the element list */
102052  int count;                     /* Number of elements left to test */
102053  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
102054
102055  if( pH->ht ){
102056    struct _fts3ht *pEntry = &pH->ht[h];
102057    elem = pEntry->chain;
102058    count = pEntry->count;
102059    xCompare = ftsCompareFunction(pH->keyClass);
102060    while( count-- && elem ){
102061      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
102062        return elem;
102063      }
102064      elem = elem->next;
102065    }
102066  }
102067  return 0;
102068}
102069
102070/* Remove a single entry from the hash table given a pointer to that
102071** element and a hash on the element's key.
102072*/
102073static void fts3RemoveElementByHash(
102074  Fts3Hash *pH,         /* The pH containing "elem" */
102075  Fts3HashElem* elem,   /* The element to be removed from the pH */
102076  int h                 /* Hash value for the element */
102077){
102078  struct _fts3ht *pEntry;
102079  if( elem->prev ){
102080    elem->prev->next = elem->next;
102081  }else{
102082    pH->first = elem->next;
102083  }
102084  if( elem->next ){
102085    elem->next->prev = elem->prev;
102086  }
102087  pEntry = &pH->ht[h];
102088  if( pEntry->chain==elem ){
102089    pEntry->chain = elem->next;
102090  }
102091  pEntry->count--;
102092  if( pEntry->count<=0 ){
102093    pEntry->chain = 0;
102094  }
102095  if( pH->copyKey && elem->pKey ){
102096    fts3HashFree(elem->pKey);
102097  }
102098  fts3HashFree( elem );
102099  pH->count--;
102100  if( pH->count<=0 ){
102101    assert( pH->first==0 );
102102    assert( pH->count==0 );
102103    fts3HashClear(pH);
102104  }
102105}
102106
102107SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
102108  const Fts3Hash *pH,
102109  const void *pKey,
102110  int nKey
102111){
102112  int h;                          /* A hash on key */
102113  int (*xHash)(const void*,int);  /* The hash function */
102114
102115  if( pH==0 || pH->ht==0 ) return 0;
102116  xHash = ftsHashFunction(pH->keyClass);
102117  assert( xHash!=0 );
102118  h = (*xHash)(pKey,nKey);
102119  assert( (pH->htsize & (pH->htsize-1))==0 );
102120  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
102121}
102122
102123/*
102124** Attempt to locate an element of the hash table pH with a key
102125** that matches pKey,nKey.  Return the data for this element if it is
102126** found, or NULL if there is no match.
102127*/
102128SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
102129  Fts3HashElem *pElem;            /* The element that matches key (if any) */
102130
102131  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
102132  return pElem ? pElem->data : 0;
102133}
102134
102135/* Insert an element into the hash table pH.  The key is pKey,nKey
102136** and the data is "data".
102137**
102138** If no element exists with a matching key, then a new
102139** element is created.  A copy of the key is made if the copyKey
102140** flag is set.  NULL is returned.
102141**
102142** If another element already exists with the same key, then the
102143** new data replaces the old data and the old data is returned.
102144** The key is not copied in this instance.  If a malloc fails, then
102145** the new data is returned and the hash table is unchanged.
102146**
102147** If the "data" parameter to this function is NULL, then the
102148** element corresponding to "key" is removed from the hash table.
102149*/
102150SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
102151  Fts3Hash *pH,        /* The hash table to insert into */
102152  const void *pKey,    /* The key */
102153  int nKey,            /* Number of bytes in the key */
102154  void *data           /* The data */
102155){
102156  int hraw;                 /* Raw hash value of the key */
102157  int h;                    /* the hash of the key modulo hash table size */
102158  Fts3HashElem *elem;       /* Used to loop thru the element list */
102159  Fts3HashElem *new_elem;   /* New element added to the pH */
102160  int (*xHash)(const void*,int);  /* The hash function */
102161
102162  assert( pH!=0 );
102163  xHash = ftsHashFunction(pH->keyClass);
102164  assert( xHash!=0 );
102165  hraw = (*xHash)(pKey, nKey);
102166  assert( (pH->htsize & (pH->htsize-1))==0 );
102167  h = hraw & (pH->htsize-1);
102168  elem = fts3FindElementByHash(pH,pKey,nKey,h);
102169  if( elem ){
102170    void *old_data = elem->data;
102171    if( data==0 ){
102172      fts3RemoveElementByHash(pH,elem,h);
102173    }else{
102174      elem->data = data;
102175    }
102176    return old_data;
102177  }
102178  if( data==0 ) return 0;
102179  if( (pH->htsize==0 && fts3Rehash(pH,8))
102180   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
102181  ){
102182    pH->count = 0;
102183    return data;
102184  }
102185  assert( pH->htsize>0 );
102186  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
102187  if( new_elem==0 ) return data;
102188  if( pH->copyKey && pKey!=0 ){
102189    new_elem->pKey = fts3HashMalloc( nKey );
102190    if( new_elem->pKey==0 ){
102191      fts3HashFree(new_elem);
102192      return data;
102193    }
102194    memcpy((void*)new_elem->pKey, pKey, nKey);
102195  }else{
102196    new_elem->pKey = (void*)pKey;
102197  }
102198  new_elem->nKey = nKey;
102199  pH->count++;
102200  assert( pH->htsize>0 );
102201  assert( (pH->htsize & (pH->htsize-1))==0 );
102202  h = hraw & (pH->htsize-1);
102203  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
102204  new_elem->data = data;
102205  return 0;
102206}
102207
102208#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
102209
102210/************** End of fts3_hash.c *******************************************/
102211/************** Begin file fts3_porter.c *************************************/
102212/*
102213** 2006 September 30
102214**
102215** The author disclaims copyright to this source code.  In place of
102216** a legal notice, here is a blessing:
102217**
102218**    May you do good and not evil.
102219**    May you find forgiveness for yourself and forgive others.
102220**    May you share freely, never taking more than you give.
102221**
102222*************************************************************************
102223** Implementation of the full-text-search tokenizer that implements
102224** a Porter stemmer.
102225*/
102226
102227/*
102228** The code in this file is only compiled if:
102229**
102230**     * The FTS3 module is being built as an extension
102231**       (in which case SQLITE_CORE is not defined), or
102232**
102233**     * The FTS3 module is being built into the core of
102234**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
102235*/
102236#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
102237
102238
102239
102240
102241/*
102242** Class derived from sqlite3_tokenizer
102243*/
102244typedef struct porter_tokenizer {
102245  sqlite3_tokenizer base;      /* Base class */
102246} porter_tokenizer;
102247
102248/*
102249** Class derived from sqlit3_tokenizer_cursor
102250*/
102251typedef struct porter_tokenizer_cursor {
102252  sqlite3_tokenizer_cursor base;
102253  const char *zInput;          /* input we are tokenizing */
102254  int nInput;                  /* size of the input */
102255  int iOffset;                 /* current position in zInput */
102256  int iToken;                  /* index of next token to be returned */
102257  char *zToken;                /* storage for current token */
102258  int nAllocated;              /* space allocated to zToken buffer */
102259} porter_tokenizer_cursor;
102260
102261
102262/*
102263** Create a new tokenizer instance.
102264*/
102265static int porterCreate(
102266  int argc, const char * const *argv,
102267  sqlite3_tokenizer **ppTokenizer
102268){
102269  porter_tokenizer *t;
102270
102271  UNUSED_PARAMETER(argc);
102272  UNUSED_PARAMETER(argv);
102273
102274  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
102275  if( t==NULL ) return SQLITE_NOMEM;
102276  memset(t, 0, sizeof(*t));
102277  *ppTokenizer = &t->base;
102278  return SQLITE_OK;
102279}
102280
102281/*
102282** Destroy a tokenizer
102283*/
102284static int porterDestroy(sqlite3_tokenizer *pTokenizer){
102285  sqlite3_free(pTokenizer);
102286  return SQLITE_OK;
102287}
102288
102289/*
102290** Prepare to begin tokenizing a particular string.  The input
102291** string to be tokenized is zInput[0..nInput-1].  A cursor
102292** used to incrementally tokenize this string is returned in
102293** *ppCursor.
102294*/
102295static int porterOpen(
102296  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
102297  const char *zInput, int nInput,        /* String to be tokenized */
102298  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
102299){
102300  porter_tokenizer_cursor *c;
102301
102302  UNUSED_PARAMETER(pTokenizer);
102303
102304  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
102305  if( c==NULL ) return SQLITE_NOMEM;
102306
102307  c->zInput = zInput;
102308  if( zInput==0 ){
102309    c->nInput = 0;
102310  }else if( nInput<0 ){
102311    c->nInput = (int)strlen(zInput);
102312  }else{
102313    c->nInput = nInput;
102314  }
102315  c->iOffset = 0;                 /* start tokenizing at the beginning */
102316  c->iToken = 0;
102317  c->zToken = NULL;               /* no space allocated, yet. */
102318  c->nAllocated = 0;
102319
102320  *ppCursor = &c->base;
102321  return SQLITE_OK;
102322}
102323
102324/*
102325** Close a tokenization cursor previously opened by a call to
102326** porterOpen() above.
102327*/
102328static int porterClose(sqlite3_tokenizer_cursor *pCursor){
102329  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
102330  sqlite3_free(c->zToken);
102331  sqlite3_free(c);
102332  return SQLITE_OK;
102333}
102334/*
102335** Vowel or consonant
102336*/
102337static const char cType[] = {
102338   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
102339   1, 1, 1, 2, 1
102340};
102341
102342/*
102343** isConsonant() and isVowel() determine if their first character in
102344** the string they point to is a consonant or a vowel, according
102345** to Porter ruls.
102346**
102347** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
102348** 'Y' is a consonant unless it follows another consonant,
102349** in which case it is a vowel.
102350**
102351** In these routine, the letters are in reverse order.  So the 'y' rule
102352** is that 'y' is a consonant unless it is followed by another
102353** consonent.
102354*/
102355static int isVowel(const char*);
102356static int isConsonant(const char *z){
102357  int j;
102358  char x = *z;
102359  if( x==0 ) return 0;
102360  assert( x>='a' && x<='z' );
102361  j = cType[x-'a'];
102362  if( j<2 ) return j;
102363  return z[1]==0 || isVowel(z + 1);
102364}
102365static int isVowel(const char *z){
102366  int j;
102367  char x = *z;
102368  if( x==0 ) return 0;
102369  assert( x>='a' && x<='z' );
102370  j = cType[x-'a'];
102371  if( j<2 ) return 1-j;
102372  return isConsonant(z + 1);
102373}
102374
102375/*
102376** Let any sequence of one or more vowels be represented by V and let
102377** C be sequence of one or more consonants.  Then every word can be
102378** represented as:
102379**
102380**           [C] (VC){m} [V]
102381**
102382** In prose:  A word is an optional consonant followed by zero or
102383** vowel-consonant pairs followed by an optional vowel.  "m" is the
102384** number of vowel consonant pairs.  This routine computes the value
102385** of m for the first i bytes of a word.
102386**
102387** Return true if the m-value for z is 1 or more.  In other words,
102388** return true if z contains at least one vowel that is followed
102389** by a consonant.
102390**
102391** In this routine z[] is in reverse order.  So we are really looking
102392** for an instance of of a consonant followed by a vowel.
102393*/
102394static int m_gt_0(const char *z){
102395  while( isVowel(z) ){ z++; }
102396  if( *z==0 ) return 0;
102397  while( isConsonant(z) ){ z++; }
102398  return *z!=0;
102399}
102400
102401/* Like mgt0 above except we are looking for a value of m which is
102402** exactly 1
102403*/
102404static int m_eq_1(const char *z){
102405  while( isVowel(z) ){ z++; }
102406  if( *z==0 ) return 0;
102407  while( isConsonant(z) ){ z++; }
102408  if( *z==0 ) return 0;
102409  while( isVowel(z) ){ z++; }
102410  if( *z==0 ) return 1;
102411  while( isConsonant(z) ){ z++; }
102412  return *z==0;
102413}
102414
102415/* Like mgt0 above except we are looking for a value of m>1 instead
102416** or m>0
102417*/
102418static int m_gt_1(const char *z){
102419  while( isVowel(z) ){ z++; }
102420  if( *z==0 ) return 0;
102421  while( isConsonant(z) ){ z++; }
102422  if( *z==0 ) return 0;
102423  while( isVowel(z) ){ z++; }
102424  if( *z==0 ) return 0;
102425  while( isConsonant(z) ){ z++; }
102426  return *z!=0;
102427}
102428
102429/*
102430** Return TRUE if there is a vowel anywhere within z[0..n-1]
102431*/
102432static int hasVowel(const char *z){
102433  while( isConsonant(z) ){ z++; }
102434  return *z!=0;
102435}
102436
102437/*
102438** Return TRUE if the word ends in a double consonant.
102439**
102440** The text is reversed here. So we are really looking at
102441** the first two characters of z[].
102442*/
102443static int doubleConsonant(const char *z){
102444  return isConsonant(z) && z[0]==z[1];
102445}
102446
102447/*
102448** Return TRUE if the word ends with three letters which
102449** are consonant-vowel-consonent and where the final consonant
102450** is not 'w', 'x', or 'y'.
102451**
102452** The word is reversed here.  So we are really checking the
102453** first three letters and the first one cannot be in [wxy].
102454*/
102455static int star_oh(const char *z){
102456  return
102457    isConsonant(z) &&
102458    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
102459    isVowel(z+1) &&
102460    isConsonant(z+2);
102461}
102462
102463/*
102464** If the word ends with zFrom and xCond() is true for the stem
102465** of the word that preceeds the zFrom ending, then change the
102466** ending to zTo.
102467**
102468** The input word *pz and zFrom are both in reverse order.  zTo
102469** is in normal order.
102470**
102471** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
102472** match.  Not that TRUE is returned even if xCond() fails and
102473** no substitution occurs.
102474*/
102475static int stem(
102476  char **pz,             /* The word being stemmed (Reversed) */
102477  const char *zFrom,     /* If the ending matches this... (Reversed) */
102478  const char *zTo,       /* ... change the ending to this (not reversed) */
102479  int (*xCond)(const char*)   /* Condition that must be true */
102480){
102481  char *z = *pz;
102482  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
102483  if( *zFrom!=0 ) return 0;
102484  if( xCond && !xCond(z) ) return 1;
102485  while( *zTo ){
102486    *(--z) = *(zTo++);
102487  }
102488  *pz = z;
102489  return 1;
102490}
102491
102492/*
102493** This is the fallback stemmer used when the porter stemmer is
102494** inappropriate.  The input word is copied into the output with
102495** US-ASCII case folding.  If the input word is too long (more
102496** than 20 bytes if it contains no digits or more than 6 bytes if
102497** it contains digits) then word is truncated to 20 or 6 bytes
102498** by taking 10 or 3 bytes from the beginning and end.
102499*/
102500static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
102501  int i, mx, j;
102502  int hasDigit = 0;
102503  for(i=0; i<nIn; i++){
102504    char c = zIn[i];
102505    if( c>='A' && c<='Z' ){
102506      zOut[i] = c - 'A' + 'a';
102507    }else{
102508      if( c>='0' && c<='9' ) hasDigit = 1;
102509      zOut[i] = c;
102510    }
102511  }
102512  mx = hasDigit ? 3 : 10;
102513  if( nIn>mx*2 ){
102514    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
102515      zOut[j] = zOut[i];
102516    }
102517    i = j;
102518  }
102519  zOut[i] = 0;
102520  *pnOut = i;
102521}
102522
102523
102524/*
102525** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
102526** zOut is at least big enough to hold nIn bytes.  Write the actual
102527** size of the output word (exclusive of the '\0' terminator) into *pnOut.
102528**
102529** Any upper-case characters in the US-ASCII character set ([A-Z])
102530** are converted to lower case.  Upper-case UTF characters are
102531** unchanged.
102532**
102533** Words that are longer than about 20 bytes are stemmed by retaining
102534** a few bytes from the beginning and the end of the word.  If the
102535** word contains digits, 3 bytes are taken from the beginning and
102536** 3 bytes from the end.  For long words without digits, 10 bytes
102537** are taken from each end.  US-ASCII case folding still applies.
102538**
102539** If the input word contains not digits but does characters not
102540** in [a-zA-Z] then no stemming is attempted and this routine just
102541** copies the input into the input into the output with US-ASCII
102542** case folding.
102543**
102544** Stemming never increases the length of the word.  So there is
102545** no chance of overflowing the zOut buffer.
102546*/
102547static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
102548  int i, j;
102549  char zReverse[28];
102550  char *z, *z2;
102551  if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
102552    /* The word is too big or too small for the porter stemmer.
102553    ** Fallback to the copy stemmer */
102554    copy_stemmer(zIn, nIn, zOut, pnOut);
102555    return;
102556  }
102557  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
102558    char c = zIn[i];
102559    if( c>='A' && c<='Z' ){
102560      zReverse[j] = c + 'a' - 'A';
102561    }else if( c>='a' && c<='z' ){
102562      zReverse[j] = c;
102563    }else{
102564      /* The use of a character not in [a-zA-Z] means that we fallback
102565      ** to the copy stemmer */
102566      copy_stemmer(zIn, nIn, zOut, pnOut);
102567      return;
102568    }
102569  }
102570  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
102571  z = &zReverse[j+1];
102572
102573
102574  /* Step 1a */
102575  if( z[0]=='s' ){
102576    if(
102577     !stem(&z, "sess", "ss", 0) &&
102578     !stem(&z, "sei", "i", 0)  &&
102579     !stem(&z, "ss", "ss", 0)
102580    ){
102581      z++;
102582    }
102583  }
102584
102585  /* Step 1b */
102586  z2 = z;
102587  if( stem(&z, "dee", "ee", m_gt_0) ){
102588    /* Do nothing.  The work was all in the test */
102589  }else if(
102590     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
102591      && z!=z2
102592  ){
102593     if( stem(&z, "ta", "ate", 0) ||
102594         stem(&z, "lb", "ble", 0) ||
102595         stem(&z, "zi", "ize", 0) ){
102596       /* Do nothing.  The work was all in the test */
102597     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
102598       z++;
102599     }else if( m_eq_1(z) && star_oh(z) ){
102600       *(--z) = 'e';
102601     }
102602  }
102603
102604  /* Step 1c */
102605  if( z[0]=='y' && hasVowel(z+1) ){
102606    z[0] = 'i';
102607  }
102608
102609  /* Step 2 */
102610  switch( z[1] ){
102611   case 'a':
102612     stem(&z, "lanoita", "ate", m_gt_0) ||
102613     stem(&z, "lanoit", "tion", m_gt_0);
102614     break;
102615   case 'c':
102616     stem(&z, "icne", "ence", m_gt_0) ||
102617     stem(&z, "icna", "ance", m_gt_0);
102618     break;
102619   case 'e':
102620     stem(&z, "rezi", "ize", m_gt_0);
102621     break;
102622   case 'g':
102623     stem(&z, "igol", "log", m_gt_0);
102624     break;
102625   case 'l':
102626     stem(&z, "ilb", "ble", m_gt_0) ||
102627     stem(&z, "illa", "al", m_gt_0) ||
102628     stem(&z, "iltne", "ent", m_gt_0) ||
102629     stem(&z, "ile", "e", m_gt_0) ||
102630     stem(&z, "ilsuo", "ous", m_gt_0);
102631     break;
102632   case 'o':
102633     stem(&z, "noitazi", "ize", m_gt_0) ||
102634     stem(&z, "noita", "ate", m_gt_0) ||
102635     stem(&z, "rota", "ate", m_gt_0);
102636     break;
102637   case 's':
102638     stem(&z, "msila", "al", m_gt_0) ||
102639     stem(&z, "ssenevi", "ive", m_gt_0) ||
102640     stem(&z, "ssenluf", "ful", m_gt_0) ||
102641     stem(&z, "ssensuo", "ous", m_gt_0);
102642     break;
102643   case 't':
102644     stem(&z, "itila", "al", m_gt_0) ||
102645     stem(&z, "itivi", "ive", m_gt_0) ||
102646     stem(&z, "itilib", "ble", m_gt_0);
102647     break;
102648  }
102649
102650  /* Step 3 */
102651  switch( z[0] ){
102652   case 'e':
102653     stem(&z, "etaci", "ic", m_gt_0) ||
102654     stem(&z, "evita", "", m_gt_0)   ||
102655     stem(&z, "ezila", "al", m_gt_0);
102656     break;
102657   case 'i':
102658     stem(&z, "itici", "ic", m_gt_0);
102659     break;
102660   case 'l':
102661     stem(&z, "laci", "ic", m_gt_0) ||
102662     stem(&z, "luf", "", m_gt_0);
102663     break;
102664   case 's':
102665     stem(&z, "ssen", "", m_gt_0);
102666     break;
102667  }
102668
102669  /* Step 4 */
102670  switch( z[1] ){
102671   case 'a':
102672     if( z[0]=='l' && m_gt_1(z+2) ){
102673       z += 2;
102674     }
102675     break;
102676   case 'c':
102677     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
102678       z += 4;
102679     }
102680     break;
102681   case 'e':
102682     if( z[0]=='r' && m_gt_1(z+2) ){
102683       z += 2;
102684     }
102685     break;
102686   case 'i':
102687     if( z[0]=='c' && m_gt_1(z+2) ){
102688       z += 2;
102689     }
102690     break;
102691   case 'l':
102692     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
102693       z += 4;
102694     }
102695     break;
102696   case 'n':
102697     if( z[0]=='t' ){
102698       if( z[2]=='a' ){
102699         if( m_gt_1(z+3) ){
102700           z += 3;
102701         }
102702       }else if( z[2]=='e' ){
102703         stem(&z, "tneme", "", m_gt_1) ||
102704         stem(&z, "tnem", "", m_gt_1) ||
102705         stem(&z, "tne", "", m_gt_1);
102706       }
102707     }
102708     break;
102709   case 'o':
102710     if( z[0]=='u' ){
102711       if( m_gt_1(z+2) ){
102712         z += 2;
102713       }
102714     }else if( z[3]=='s' || z[3]=='t' ){
102715       stem(&z, "noi", "", m_gt_1);
102716     }
102717     break;
102718   case 's':
102719     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
102720       z += 3;
102721     }
102722     break;
102723   case 't':
102724     stem(&z, "eta", "", m_gt_1) ||
102725     stem(&z, "iti", "", m_gt_1);
102726     break;
102727   case 'u':
102728     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
102729       z += 3;
102730     }
102731     break;
102732   case 'v':
102733   case 'z':
102734     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
102735       z += 3;
102736     }
102737     break;
102738  }
102739
102740  /* Step 5a */
102741  if( z[0]=='e' ){
102742    if( m_gt_1(z+1) ){
102743      z++;
102744    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
102745      z++;
102746    }
102747  }
102748
102749  /* Step 5b */
102750  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
102751    z++;
102752  }
102753
102754  /* z[] is now the stemmed word in reverse order.  Flip it back
102755  ** around into forward order and return.
102756  */
102757  *pnOut = i = (int)strlen(z);
102758  zOut[i] = 0;
102759  while( *z ){
102760    zOut[--i] = *(z++);
102761  }
102762}
102763
102764/*
102765** Characters that can be part of a token.  We assume any character
102766** whose value is greater than 0x80 (any UTF character) can be
102767** part of a token.  In other words, delimiters all must have
102768** values of 0x7f or lower.
102769*/
102770static const char porterIdChar[] = {
102771/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
102772    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
102773    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
102774    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
102775    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
102776    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
102777};
102778#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
102779
102780/*
102781** Extract the next token from a tokenization cursor.  The cursor must
102782** have been opened by a prior call to porterOpen().
102783*/
102784static int porterNext(
102785  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
102786  const char **pzToken,               /* OUT: *pzToken is the token text */
102787  int *pnBytes,                       /* OUT: Number of bytes in token */
102788  int *piStartOffset,                 /* OUT: Starting offset of token */
102789  int *piEndOffset,                   /* OUT: Ending offset of token */
102790  int *piPosition                     /* OUT: Position integer of token */
102791){
102792  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
102793  const char *z = c->zInput;
102794
102795  while( c->iOffset<c->nInput ){
102796    int iStartOffset, ch;
102797
102798    /* Scan past delimiter characters */
102799    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
102800      c->iOffset++;
102801    }
102802
102803    /* Count non-delimiter characters. */
102804    iStartOffset = c->iOffset;
102805    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
102806      c->iOffset++;
102807    }
102808
102809    if( c->iOffset>iStartOffset ){
102810      int n = c->iOffset-iStartOffset;
102811      if( n>c->nAllocated ){
102812        c->nAllocated = n+20;
102813        c->zToken = sqlite3_realloc(c->zToken, c->nAllocated);
102814        if( c->zToken==NULL ) return SQLITE_NOMEM;
102815      }
102816      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
102817      *pzToken = c->zToken;
102818      *piStartOffset = iStartOffset;
102819      *piEndOffset = c->iOffset;
102820      *piPosition = c->iToken++;
102821      return SQLITE_OK;
102822    }
102823  }
102824  return SQLITE_DONE;
102825}
102826
102827/*
102828** The set of routines that implement the porter-stemmer tokenizer
102829*/
102830static const sqlite3_tokenizer_module porterTokenizerModule = {
102831  0,
102832  porterCreate,
102833  porterDestroy,
102834  porterOpen,
102835  porterClose,
102836  porterNext,
102837};
102838
102839/*
102840** Allocate a new porter tokenizer.  Return a pointer to the new
102841** tokenizer in *ppModule
102842*/
102843SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
102844  sqlite3_tokenizer_module const**ppModule
102845){
102846  *ppModule = &porterTokenizerModule;
102847}
102848
102849#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
102850
102851/************** End of fts3_porter.c *****************************************/
102852/************** Begin file fts3_tokenizer.c **********************************/
102853/*
102854** 2007 June 22
102855**
102856** The author disclaims copyright to this source code.  In place of
102857** a legal notice, here is a blessing:
102858**
102859**    May you do good and not evil.
102860**    May you find forgiveness for yourself and forgive others.
102861**    May you share freely, never taking more than you give.
102862**
102863******************************************************************************
102864**
102865** This is part of an SQLite module implementing full-text search.
102866** This particular file implements the generic tokenizer interface.
102867*/
102868
102869/*
102870** The code in this file is only compiled if:
102871**
102872**     * The FTS3 module is being built as an extension
102873**       (in which case SQLITE_CORE is not defined), or
102874**
102875**     * The FTS3 module is being built into the core of
102876**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
102877*/
102878#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
102879
102880#ifndef SQLITE_CORE
102881  SQLITE_EXTENSION_INIT1
102882#endif
102883
102884
102885/*
102886** Implementation of the SQL scalar function for accessing the underlying
102887** hash table. This function may be called as follows:
102888**
102889**   SELECT <function-name>(<key-name>);
102890**   SELECT <function-name>(<key-name>, <pointer>);
102891**
102892** where <function-name> is the name passed as the second argument
102893** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
102894**
102895** If the <pointer> argument is specified, it must be a blob value
102896** containing a pointer to be stored as the hash data corresponding
102897** to the string <key-name>. If <pointer> is not specified, then
102898** the string <key-name> must already exist in the has table. Otherwise,
102899** an error is returned.
102900**
102901** Whether or not the <pointer> argument is specified, the value returned
102902** is a blob containing the pointer stored as the hash data corresponding
102903** to string <key-name> (after the hash-table is updated, if applicable).
102904*/
102905static void scalarFunc(
102906  sqlite3_context *context,
102907  int argc,
102908  sqlite3_value **argv
102909){
102910  Fts3Hash *pHash;
102911  void *pPtr = 0;
102912  const unsigned char *zName;
102913  int nName;
102914
102915  assert( argc==1 || argc==2 );
102916
102917  pHash = (Fts3Hash *)sqlite3_user_data(context);
102918
102919  zName = sqlite3_value_text(argv[0]);
102920  nName = sqlite3_value_bytes(argv[0])+1;
102921
102922  if( argc==2 ){
102923    void *pOld;
102924    int n = sqlite3_value_bytes(argv[1]);
102925    if( n!=sizeof(pPtr) ){
102926      sqlite3_result_error(context, "argument type mismatch", -1);
102927      return;
102928    }
102929    pPtr = *(void **)sqlite3_value_blob(argv[1]);
102930    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
102931    if( pOld==pPtr ){
102932      sqlite3_result_error(context, "out of memory", -1);
102933      return;
102934    }
102935  }else{
102936    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
102937    if( !pPtr ){
102938      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
102939      sqlite3_result_error(context, zErr, -1);
102940      sqlite3_free(zErr);
102941      return;
102942    }
102943  }
102944
102945  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
102946}
102947
102948static int fts3IsIdChar(char c){
102949  static const char isFtsIdChar[] = {
102950      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
102951      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
102952      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
102953      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
102954      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
102955      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
102956      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
102957      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
102958  };
102959  return (c&0x80 || isFtsIdChar[(int)(c)]);
102960}
102961
102962SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
102963  const char *z1;
102964  const char *z2 = 0;
102965
102966  /* Find the start of the next token. */
102967  z1 = zStr;
102968  while( z2==0 ){
102969    char c = *z1;
102970    switch( c ){
102971      case '\0': return 0;        /* No more tokens here */
102972      case '\'':
102973      case '"':
102974      case '`': {
102975        z2 = z1;
102976        while( *++z2 && (*z2!=c || *++z2==c) );
102977        break;
102978      }
102979      case '[':
102980        z2 = &z1[1];
102981        while( *z2 && z2[0]!=']' ) z2++;
102982        if( *z2 ) z2++;
102983        break;
102984
102985      default:
102986        if( fts3IsIdChar(*z1) ){
102987          z2 = &z1[1];
102988          while( fts3IsIdChar(*z2) ) z2++;
102989        }else{
102990          z1++;
102991        }
102992    }
102993  }
102994
102995  *pn = (int)(z2-z1);
102996  return z1;
102997}
102998
102999SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
103000  Fts3Hash *pHash,                /* Tokenizer hash table */
103001  const char *zArg,               /* Possible tokenizer specification */
103002  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
103003  const char **pzTokenizer,       /* OUT: Set to zArg if is tokenizer */
103004  char **pzErr                    /* OUT: Set to malloced error message */
103005){
103006  int rc;
103007  char *z = (char *)zArg;
103008  int n;
103009  char *zCopy;
103010  char *zEnd;                     /* Pointer to nul-term of zCopy */
103011  sqlite3_tokenizer_module *m;
103012
103013  if( !z ){
103014    zCopy = sqlite3_mprintf("simple");
103015  }else{
103016    if( sqlite3_strnicmp(z, "tokenize", 8) || fts3IsIdChar(z[8])){
103017      return SQLITE_OK;
103018    }
103019    zCopy = sqlite3_mprintf("%s", &z[8]);
103020    *pzTokenizer = zArg;
103021  }
103022  if( !zCopy ){
103023    return SQLITE_NOMEM;
103024  }
103025
103026  zEnd = &zCopy[strlen(zCopy)];
103027
103028  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
103029  z[n] = '\0';
103030  sqlite3Fts3Dequote(z);
103031
103032  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, z, (int)strlen(z)+1);
103033  if( !m ){
103034    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
103035    rc = SQLITE_ERROR;
103036  }else{
103037    char const **aArg = 0;
103038    int iArg = 0;
103039    z = &z[n+1];
103040    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
103041      int nNew = sizeof(char *)*(iArg+1);
103042      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
103043      if( !aNew ){
103044        sqlite3_free(zCopy);
103045        sqlite3_free((void *)aArg);
103046        return SQLITE_NOMEM;
103047      }
103048      aArg = aNew;
103049      aArg[iArg++] = z;
103050      z[n] = '\0';
103051      sqlite3Fts3Dequote(z);
103052      z = &z[n+1];
103053    }
103054    rc = m->xCreate(iArg, aArg, ppTok);
103055    assert( rc!=SQLITE_OK || *ppTok );
103056    if( rc!=SQLITE_OK ){
103057      *pzErr = sqlite3_mprintf("unknown tokenizer");
103058    }else{
103059      (*ppTok)->pModule = m;
103060    }
103061    sqlite3_free((void *)aArg);
103062  }
103063
103064  sqlite3_free(zCopy);
103065  return rc;
103066}
103067
103068
103069#ifdef SQLITE_TEST
103070
103071
103072/*
103073** Implementation of a special SQL scalar function for testing tokenizers
103074** designed to be used in concert with the Tcl testing framework. This
103075** function must be called with two arguments:
103076**
103077**   SELECT <function-name>(<key-name>, <input-string>);
103078**   SELECT <function-name>(<key-name>, <pointer>);
103079**
103080** where <function-name> is the name passed as the second argument
103081** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
103082** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
103083**
103084** The return value is a string that may be interpreted as a Tcl
103085** list. For each token in the <input-string>, three elements are
103086** added to the returned list. The first is the token position, the
103087** second is the token text (folded, stemmed, etc.) and the third is the
103088** substring of <input-string> associated with the token. For example,
103089** using the built-in "simple" tokenizer:
103090**
103091**   SELECT fts_tokenizer_test('simple', 'I don't see how');
103092**
103093** will return the string:
103094**
103095**   "{0 i I 1 dont don't 2 see see 3 how how}"
103096**
103097*/
103098static void testFunc(
103099  sqlite3_context *context,
103100  int argc,
103101  sqlite3_value **argv
103102){
103103  Fts3Hash *pHash;
103104  sqlite3_tokenizer_module *p;
103105  sqlite3_tokenizer *pTokenizer = 0;
103106  sqlite3_tokenizer_cursor *pCsr = 0;
103107
103108  const char *zErr = 0;
103109
103110  const char *zName;
103111  int nName;
103112  const char *zInput;
103113  int nInput;
103114
103115  const char *zArg = 0;
103116
103117  const char *zToken;
103118  int nToken;
103119  int iStart;
103120  int iEnd;
103121  int iPos;
103122
103123  Tcl_Obj *pRet;
103124
103125  assert( argc==2 || argc==3 );
103126
103127  nName = sqlite3_value_bytes(argv[0]);
103128  zName = (const char *)sqlite3_value_text(argv[0]);
103129  nInput = sqlite3_value_bytes(argv[argc-1]);
103130  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
103131
103132  if( argc==3 ){
103133    zArg = (const char *)sqlite3_value_text(argv[1]);
103134  }
103135
103136  pHash = (Fts3Hash *)sqlite3_user_data(context);
103137  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
103138
103139  if( !p ){
103140    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
103141    sqlite3_result_error(context, zErr, -1);
103142    sqlite3_free(zErr);
103143    return;
103144  }
103145
103146  pRet = Tcl_NewObj();
103147  Tcl_IncrRefCount(pRet);
103148
103149  if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
103150    zErr = "error in xCreate()";
103151    goto finish;
103152  }
103153  pTokenizer->pModule = p;
103154  if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
103155    zErr = "error in xOpen()";
103156    goto finish;
103157  }
103158  pCsr->pTokenizer = pTokenizer;
103159
103160  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
103161    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
103162    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
103163    zToken = &zInput[iStart];
103164    nToken = iEnd-iStart;
103165    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
103166  }
103167
103168  if( SQLITE_OK!=p->xClose(pCsr) ){
103169    zErr = "error in xClose()";
103170    goto finish;
103171  }
103172  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
103173    zErr = "error in xDestroy()";
103174    goto finish;
103175  }
103176
103177finish:
103178  if( zErr ){
103179    sqlite3_result_error(context, zErr, -1);
103180  }else{
103181    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
103182  }
103183  Tcl_DecrRefCount(pRet);
103184}
103185
103186static
103187int registerTokenizer(
103188  sqlite3 *db,
103189  char *zName,
103190  const sqlite3_tokenizer_module *p
103191){
103192  int rc;
103193  sqlite3_stmt *pStmt;
103194  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
103195
103196  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
103197  if( rc!=SQLITE_OK ){
103198    return rc;
103199  }
103200
103201  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
103202  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
103203  sqlite3_step(pStmt);
103204
103205  return sqlite3_finalize(pStmt);
103206}
103207
103208static
103209int queryTokenizer(
103210  sqlite3 *db,
103211  char *zName,
103212  const sqlite3_tokenizer_module **pp
103213){
103214  int rc;
103215  sqlite3_stmt *pStmt;
103216  const char zSql[] = "SELECT fts3_tokenizer(?)";
103217
103218  *pp = 0;
103219  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
103220  if( rc!=SQLITE_OK ){
103221    return rc;
103222  }
103223
103224  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
103225  if( SQLITE_ROW==sqlite3_step(pStmt) ){
103226    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
103227      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
103228    }
103229  }
103230
103231  return sqlite3_finalize(pStmt);
103232}
103233
103234SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
103235
103236/*
103237** Implementation of the scalar function fts3_tokenizer_internal_test().
103238** This function is used for testing only, it is not included in the
103239** build unless SQLITE_TEST is defined.
103240**
103241** The purpose of this is to test that the fts3_tokenizer() function
103242** can be used as designed by the C-code in the queryTokenizer and
103243** registerTokenizer() functions above. These two functions are repeated
103244** in the README.tokenizer file as an example, so it is important to
103245** test them.
103246**
103247** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
103248** function with no arguments. An assert() will fail if a problem is
103249** detected. i.e.:
103250**
103251**     SELECT fts3_tokenizer_internal_test();
103252**
103253*/
103254static void intTestFunc(
103255  sqlite3_context *context,
103256  int argc,
103257  sqlite3_value **argv
103258){
103259  int rc;
103260  const sqlite3_tokenizer_module *p1;
103261  const sqlite3_tokenizer_module *p2;
103262  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
103263
103264  UNUSED_PARAMETER(argc);
103265  UNUSED_PARAMETER(argv);
103266
103267  /* Test the query function */
103268  sqlite3Fts3SimpleTokenizerModule(&p1);
103269  rc = queryTokenizer(db, "simple", &p2);
103270  assert( rc==SQLITE_OK );
103271  assert( p1==p2 );
103272  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
103273  assert( rc==SQLITE_ERROR );
103274  assert( p2==0 );
103275  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
103276
103277  /* Test the storage function */
103278  rc = registerTokenizer(db, "nosuchtokenizer", p1);
103279  assert( rc==SQLITE_OK );
103280  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
103281  assert( rc==SQLITE_OK );
103282  assert( p2==p1 );
103283
103284  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
103285}
103286
103287#endif
103288
103289/*
103290** Set up SQL objects in database db used to access the contents of
103291** the hash table pointed to by argument pHash. The hash table must
103292** been initialised to use string keys, and to take a private copy
103293** of the key when a value is inserted. i.e. by a call similar to:
103294**
103295**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
103296**
103297** This function adds a scalar function (see header comment above
103298** scalarFunc() in this file for details) and, if ENABLE_TABLE is
103299** defined at compilation time, a temporary virtual table (see header
103300** comment above struct HashTableVtab) to the database schema. Both
103301** provide read/write access to the contents of *pHash.
103302**
103303** The third argument to this function, zName, is used as the name
103304** of both the scalar and, if created, the virtual table.
103305*/
103306SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
103307  sqlite3 *db,
103308  Fts3Hash *pHash,
103309  const char *zName
103310){
103311  int rc = SQLITE_OK;
103312  void *p = (void *)pHash;
103313  const int any = SQLITE_ANY;
103314
103315#ifdef SQLITE_TEST
103316  char *zTest = 0;
103317  char *zTest2 = 0;
103318  void *pdb = (void *)db;
103319  zTest = sqlite3_mprintf("%s_test", zName);
103320  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
103321  if( !zTest || !zTest2 ){
103322    rc = SQLITE_NOMEM;
103323  }
103324#endif
103325
103326  if( SQLITE_OK!=rc
103327   || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
103328   || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
103329#ifdef SQLITE_TEST
103330   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
103331   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
103332   || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
103333#endif
103334   );
103335
103336#ifdef SQLITE_TEST
103337  sqlite3_free(zTest);
103338  sqlite3_free(zTest2);
103339#endif
103340
103341  return rc;
103342}
103343
103344#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103345
103346/************** End of fts3_tokenizer.c **************************************/
103347/************** Begin file fts3_tokenizer1.c *********************************/
103348/*
103349** 2006 Oct 10
103350**
103351** The author disclaims copyright to this source code.  In place of
103352** a legal notice, here is a blessing:
103353**
103354**    May you do good and not evil.
103355**    May you find forgiveness for yourself and forgive others.
103356**    May you share freely, never taking more than you give.
103357**
103358******************************************************************************
103359**
103360** Implementation of the "simple" full-text-search tokenizer.
103361*/
103362
103363/*
103364** The code in this file is only compiled if:
103365**
103366**     * The FTS3 module is being built as an extension
103367**       (in which case SQLITE_CORE is not defined), or
103368**
103369**     * The FTS3 module is being built into the core of
103370**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
103371*/
103372#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103373
103374
103375
103376
103377typedef struct simple_tokenizer {
103378  sqlite3_tokenizer base;
103379  char delim[128];             /* flag ASCII delimiters */
103380} simple_tokenizer;
103381
103382typedef struct simple_tokenizer_cursor {
103383  sqlite3_tokenizer_cursor base;
103384  const char *pInput;          /* input we are tokenizing */
103385  int nBytes;                  /* size of the input */
103386  int iOffset;                 /* current position in pInput */
103387  int iToken;                  /* index of next token to be returned */
103388  char *pToken;                /* storage for current token */
103389  int nTokenAllocated;         /* space allocated to zToken buffer */
103390} simple_tokenizer_cursor;
103391
103392
103393static int simpleDelim(simple_tokenizer *t, unsigned char c){
103394  return c<0x80 && t->delim[c];
103395}
103396
103397/*
103398** Create a new tokenizer instance.
103399*/
103400static int simpleCreate(
103401  int argc, const char * const *argv,
103402  sqlite3_tokenizer **ppTokenizer
103403){
103404  simple_tokenizer *t;
103405
103406  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
103407  if( t==NULL ) return SQLITE_NOMEM;
103408  memset(t, 0, sizeof(*t));
103409
103410  /* TODO(shess) Delimiters need to remain the same from run to run,
103411  ** else we need to reindex.  One solution would be a meta-table to
103412  ** track such information in the database, then we'd only want this
103413  ** information on the initial create.
103414  */
103415  if( argc>1 ){
103416    int i, n = (int)strlen(argv[1]);
103417    for(i=0; i<n; i++){
103418      unsigned char ch = argv[1][i];
103419      /* We explicitly don't support UTF-8 delimiters for now. */
103420      if( ch>=0x80 ){
103421        sqlite3_free(t);
103422        return SQLITE_ERROR;
103423      }
103424      t->delim[ch] = 1;
103425    }
103426  } else {
103427    /* Mark non-alphanumeric ASCII characters as delimiters */
103428    int i;
103429    for(i=1; i<0x80; i++){
103430      t->delim[i] = !isalnum(i) ? -1 : 0;
103431    }
103432  }
103433
103434  *ppTokenizer = &t->base;
103435  return SQLITE_OK;
103436}
103437
103438/*
103439** Destroy a tokenizer
103440*/
103441static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
103442  sqlite3_free(pTokenizer);
103443  return SQLITE_OK;
103444}
103445
103446/*
103447** Prepare to begin tokenizing a particular string.  The input
103448** string to be tokenized is pInput[0..nBytes-1].  A cursor
103449** used to incrementally tokenize this string is returned in
103450** *ppCursor.
103451*/
103452static int simpleOpen(
103453  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
103454  const char *pInput, int nBytes,        /* String to be tokenized */
103455  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
103456){
103457  simple_tokenizer_cursor *c;
103458
103459  UNUSED_PARAMETER(pTokenizer);
103460
103461  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
103462  if( c==NULL ) return SQLITE_NOMEM;
103463
103464  c->pInput = pInput;
103465  if( pInput==0 ){
103466    c->nBytes = 0;
103467  }else if( nBytes<0 ){
103468    c->nBytes = (int)strlen(pInput);
103469  }else{
103470    c->nBytes = nBytes;
103471  }
103472  c->iOffset = 0;                 /* start tokenizing at the beginning */
103473  c->iToken = 0;
103474  c->pToken = NULL;               /* no space allocated, yet. */
103475  c->nTokenAllocated = 0;
103476
103477  *ppCursor = &c->base;
103478  return SQLITE_OK;
103479}
103480
103481/*
103482** Close a tokenization cursor previously opened by a call to
103483** simpleOpen() above.
103484*/
103485static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
103486  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
103487  sqlite3_free(c->pToken);
103488  sqlite3_free(c);
103489  return SQLITE_OK;
103490}
103491
103492/*
103493** Extract the next token from a tokenization cursor.  The cursor must
103494** have been opened by a prior call to simpleOpen().
103495*/
103496static int simpleNext(
103497  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
103498  const char **ppToken,               /* OUT: *ppToken is the token text */
103499  int *pnBytes,                       /* OUT: Number of bytes in token */
103500  int *piStartOffset,                 /* OUT: Starting offset of token */
103501  int *piEndOffset,                   /* OUT: Ending offset of token */
103502  int *piPosition                     /* OUT: Position integer of token */
103503){
103504  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
103505  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
103506  unsigned char *p = (unsigned char *)c->pInput;
103507
103508  while( c->iOffset<c->nBytes ){
103509    int iStartOffset;
103510
103511    /* Scan past delimiter characters */
103512    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
103513      c->iOffset++;
103514    }
103515
103516    /* Count non-delimiter characters. */
103517    iStartOffset = c->iOffset;
103518    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
103519      c->iOffset++;
103520    }
103521
103522    if( c->iOffset>iStartOffset ){
103523      int i, n = c->iOffset-iStartOffset;
103524      if( n>c->nTokenAllocated ){
103525        c->nTokenAllocated = n+20;
103526        c->pToken = sqlite3_realloc(c->pToken, c->nTokenAllocated);
103527        if( c->pToken==NULL ) return SQLITE_NOMEM;
103528      }
103529      for(i=0; i<n; i++){
103530        /* TODO(shess) This needs expansion to handle UTF-8
103531        ** case-insensitivity.
103532        */
103533        unsigned char ch = p[iStartOffset+i];
103534        c->pToken[i] = (char)(ch<0x80 ? tolower(ch) : ch);
103535      }
103536      *ppToken = c->pToken;
103537      *pnBytes = n;
103538      *piStartOffset = iStartOffset;
103539      *piEndOffset = c->iOffset;
103540      *piPosition = c->iToken++;
103541
103542      return SQLITE_OK;
103543    }
103544  }
103545  return SQLITE_DONE;
103546}
103547
103548/*
103549** The set of routines that implement the simple tokenizer
103550*/
103551static const sqlite3_tokenizer_module simpleTokenizerModule = {
103552  0,
103553  simpleCreate,
103554  simpleDestroy,
103555  simpleOpen,
103556  simpleClose,
103557  simpleNext,
103558};
103559
103560/*
103561** Allocate a new simple tokenizer.  Return a pointer to the new
103562** tokenizer in *ppModule
103563*/
103564SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
103565  sqlite3_tokenizer_module const**ppModule
103566){
103567  *ppModule = &simpleTokenizerModule;
103568}
103569
103570#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103571
103572/************** End of fts3_tokenizer1.c *************************************/
103573/************** Begin file fts3_write.c **************************************/
103574/*
103575** 2009 Oct 23
103576**
103577** The author disclaims copyright to this source code.  In place of
103578** a legal notice, here is a blessing:
103579**
103580**    May you do good and not evil.
103581**    May you find forgiveness for yourself and forgive others.
103582**    May you share freely, never taking more than you give.
103583**
103584******************************************************************************
103585**
103586** This file is part of the SQLite FTS3 extension module. Specifically,
103587** this file contains code to insert, update and delete rows from FTS3
103588** tables. It also contains code to merge FTS3 b-tree segments. Some
103589** of the sub-routines used to merge segments are also used by the query
103590** code in fts3.c.
103591*/
103592
103593#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103594
103595
103596typedef struct PendingList PendingList;
103597typedef struct SegmentNode SegmentNode;
103598typedef struct SegmentWriter SegmentWriter;
103599
103600/*
103601** Data structure used while accumulating terms in the pending-terms hash
103602** table. The hash table entry maps from term (a string) to a malloc'd
103603** instance of this structure.
103604*/
103605struct PendingList {
103606  int nData;
103607  char *aData;
103608  int nSpace;
103609  sqlite3_int64 iLastDocid;
103610  sqlite3_int64 iLastCol;
103611  sqlite3_int64 iLastPos;
103612};
103613
103614/*
103615** An instance of this structure is used to iterate through the terms on
103616** a contiguous set of segment b-tree leaf nodes. Although the details of
103617** this structure are only manipulated by code in this file, opaque handles
103618** of type Fts3SegReader* are also used by code in fts3.c to iterate through
103619** terms when querying the full-text index. See functions:
103620**
103621**   sqlite3Fts3SegReaderNew()
103622**   sqlite3Fts3SegReaderFree()
103623**   sqlite3Fts3SegReaderIterate()
103624**
103625** Methods used to manipulate Fts3SegReader structures:
103626**
103627**   fts3SegReaderNext()
103628**   fts3SegReaderFirstDocid()
103629**   fts3SegReaderNextDocid()
103630*/
103631struct Fts3SegReader {
103632  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
103633  sqlite3_int64 iStartBlock;
103634  sqlite3_int64 iEndBlock;
103635  sqlite3_stmt *pStmt;            /* SQL Statement to access leaf nodes */
103636  char *aNode;                    /* Pointer to node data (or NULL) */
103637  int nNode;                      /* Size of buffer at aNode (or 0) */
103638  int nTermAlloc;                 /* Allocated size of zTerm buffer */
103639  Fts3HashElem **ppNextElem;
103640
103641  /* Variables set by fts3SegReaderNext(). These may be read directly
103642  ** by the caller. They are valid from the time SegmentReaderNew() returns
103643  ** until SegmentReaderNext() returns something other than SQLITE_OK
103644  ** (i.e. SQLITE_DONE).
103645  */
103646  int nTerm;                      /* Number of bytes in current term */
103647  char *zTerm;                    /* Pointer to current term */
103648  char *aDoclist;                 /* Pointer to doclist of current entry */
103649  int nDoclist;                   /* Size of doclist in current entry */
103650
103651  /* The following variables are used to iterate through the current doclist */
103652  char *pOffsetList;
103653  sqlite3_int64 iDocid;
103654};
103655
103656#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
103657
103658/*
103659** An instance of this structure is used to create a segment b-tree in the
103660** database. The internal details of this type are only accessed by the
103661** following functions:
103662**
103663**   fts3SegWriterAdd()
103664**   fts3SegWriterFlush()
103665**   fts3SegWriterFree()
103666*/
103667struct SegmentWriter {
103668  SegmentNode *pTree;             /* Pointer to interior tree structure */
103669  sqlite3_int64 iFirst;           /* First slot in %_segments written */
103670  sqlite3_int64 iFree;            /* Next free slot in %_segments */
103671  char *zTerm;                    /* Pointer to previous term buffer */
103672  int nTerm;                      /* Number of bytes in zTerm */
103673  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
103674  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
103675  int nSize;                      /* Size of allocation at aData */
103676  int nData;                      /* Bytes of data in aData */
103677  char *aData;                    /* Pointer to block from malloc() */
103678};
103679
103680/*
103681** Type SegmentNode is used by the following three functions to create
103682** the interior part of the segment b+-tree structures (everything except
103683** the leaf nodes). These functions and type are only ever used by code
103684** within the fts3SegWriterXXX() family of functions described above.
103685**
103686**   fts3NodeAddTerm()
103687**   fts3NodeWrite()
103688**   fts3NodeFree()
103689*/
103690struct SegmentNode {
103691  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
103692  SegmentNode *pRight;            /* Pointer to right-sibling */
103693  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
103694  int nEntry;                     /* Number of terms written to node so far */
103695  char *zTerm;                    /* Pointer to previous term buffer */
103696  int nTerm;                      /* Number of bytes in zTerm */
103697  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
103698  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
103699  int nData;                      /* Bytes of valid data so far */
103700  char *aData;                    /* Node data */
103701};
103702
103703/*
103704** Valid values for the second argument to fts3SqlStmt().
103705*/
103706#define SQL_DELETE_CONTENT             0
103707#define SQL_IS_EMPTY                   1
103708#define SQL_DELETE_ALL_CONTENT         2
103709#define SQL_DELETE_ALL_SEGMENTS        3
103710#define SQL_DELETE_ALL_SEGDIR          4
103711#define SQL_SELECT_CONTENT_BY_ROWID    5
103712#define SQL_NEXT_SEGMENT_INDEX         6
103713#define SQL_INSERT_SEGMENTS            7
103714#define SQL_NEXT_SEGMENTS_ID           8
103715#define SQL_INSERT_SEGDIR              9
103716#define SQL_SELECT_LEVEL              10
103717#define SQL_SELECT_ALL_LEVEL          11
103718#define SQL_SELECT_LEVEL_COUNT        12
103719#define SQL_SELECT_SEGDIR_COUNT_MAX   13
103720#define SQL_DELETE_SEGDIR_BY_LEVEL    14
103721#define SQL_DELETE_SEGMENTS_RANGE     15
103722#define SQL_CONTENT_INSERT            16
103723#define SQL_GET_BLOCK                 17
103724
103725/*
103726** This function is used to obtain an SQLite prepared statement handle
103727** for the statement identified by the second argument. If successful,
103728** *pp is set to the requested statement handle and SQLITE_OK returned.
103729** Otherwise, an SQLite error code is returned and *pp is set to 0.
103730**
103731** If argument apVal is not NULL, then it must point to an array with
103732** at least as many entries as the requested statement has bound
103733** parameters. The values are bound to the statements parameters before
103734** returning.
103735*/
103736static int fts3SqlStmt(
103737  Fts3Table *p,                   /* Virtual table handle */
103738  int eStmt,                      /* One of the SQL_XXX constants above */
103739  sqlite3_stmt **pp,              /* OUT: Statement handle */
103740  sqlite3_value **apVal           /* Values to bind to statement */
103741){
103742  const char *azSql[] = {
103743/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
103744/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
103745/* 2  */  "DELETE FROM %Q.'%q_content'",
103746/* 3  */  "DELETE FROM %Q.'%q_segments'",
103747/* 4  */  "DELETE FROM %Q.'%q_segdir'",
103748/* 5  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
103749/* 6  */  "SELECT coalesce(max(idx)+1, 0) FROM %Q.'%q_segdir' WHERE level=?",
103750/* 7  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
103751/* 8  */  "SELECT coalesce(max(blockid)+1, 1) FROM %Q.'%q_segments'",
103752/* 9  */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
103753
103754          /* Return segments in order from oldest to newest.*/
103755/* 10 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
103756            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
103757/* 11 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
103758            "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
103759
103760/* 12 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
103761/* 13 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
103762
103763/* 14 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
103764/* 15 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
103765/* 16 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
103766/* 17 */  "SELECT block FROM %Q.'%q_segments' WHERE blockid = ?",
103767  };
103768  int rc = SQLITE_OK;
103769  sqlite3_stmt *pStmt;
103770
103771  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
103772  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
103773
103774  pStmt = p->aStmt[eStmt];
103775  if( !pStmt ){
103776    char *zSql;
103777    if( eStmt==SQL_CONTENT_INSERT ){
103778      int i;                      /* Iterator variable */
103779      char *zVarlist;             /* The "?, ?, ..." string */
103780      zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
103781      if( !zVarlist ){
103782        *pp = 0;
103783        return SQLITE_NOMEM;
103784      }
103785      zVarlist[0] = '?';
103786      zVarlist[p->nColumn*2+1] = '\0';
103787      for(i=1; i<=p->nColumn; i++){
103788        zVarlist[i*2-1] = ',';
103789        zVarlist[i*2] = '?';
103790      }
103791      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
103792    }else{
103793      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
103794    }
103795    if( !zSql ){
103796      rc = SQLITE_NOMEM;
103797    }else{
103798      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
103799      sqlite3_free(zSql);
103800      assert( rc==SQLITE_OK || pStmt==0 );
103801      p->aStmt[eStmt] = pStmt;
103802    }
103803  }
103804  if( apVal ){
103805    int i;
103806    int nParam = sqlite3_bind_parameter_count(pStmt);
103807    for(i=0; rc==SQLITE_OK && i<nParam; i++){
103808      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
103809    }
103810  }
103811  *pp = pStmt;
103812  return rc;
103813}
103814
103815/*
103816** Similar to fts3SqlStmt(). Except, after binding the parameters in
103817** array apVal[] to the SQL statement identified by eStmt, the statement
103818** is executed.
103819**
103820** Returns SQLITE_OK if the statement is successfully executed, or an
103821** SQLite error code otherwise.
103822*/
103823static int fts3SqlExec(Fts3Table *p, int eStmt, sqlite3_value **apVal){
103824  sqlite3_stmt *pStmt;
103825  int rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
103826  if( rc==SQLITE_OK ){
103827    sqlite3_step(pStmt);
103828    rc = sqlite3_reset(pStmt);
103829  }
103830  return rc;
103831}
103832
103833
103834/*
103835** Read a single block from the %_segments table. If the specified block
103836** does not exist, return SQLITE_CORRUPT. If some other error (malloc, IO
103837** etc.) occurs, return the appropriate SQLite error code.
103838**
103839** Otherwise, if successful, set *pzBlock to point to a buffer containing
103840** the block read from the database, and *pnBlock to the size of the read
103841** block in bytes.
103842**
103843** WARNING: The returned buffer is only valid until the next call to
103844** sqlite3Fts3ReadBlock().
103845*/
103846SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
103847  Fts3Table *p,
103848  sqlite3_int64 iBlock,
103849  char const **pzBlock,
103850  int *pnBlock
103851){
103852  sqlite3_stmt *pStmt;
103853  int rc = fts3SqlStmt(p, SQL_GET_BLOCK, &pStmt, 0);
103854  if( rc!=SQLITE_OK ) return rc;
103855  sqlite3_reset(pStmt);
103856
103857  if( pzBlock ){
103858    sqlite3_bind_int64(pStmt, 1, iBlock);
103859    rc = sqlite3_step(pStmt);
103860    if( rc!=SQLITE_ROW ){
103861      return (rc==SQLITE_DONE ? SQLITE_CORRUPT : rc);
103862    }
103863
103864    *pnBlock = sqlite3_column_bytes(pStmt, 0);
103865    *pzBlock = (char *)sqlite3_column_blob(pStmt, 0);
103866    if( sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
103867      return SQLITE_CORRUPT;
103868    }
103869  }
103870  return SQLITE_OK;
103871}
103872
103873/*
103874** Set *ppStmt to a statement handle that may be used to iterate through
103875** all rows in the %_segdir table, from oldest to newest. If successful,
103876** return SQLITE_OK. If an error occurs while preparing the statement,
103877** return an SQLite error code.
103878**
103879** There is only ever one instance of this SQL statement compiled for
103880** each FTS3 table.
103881**
103882** The statement returns the following columns from the %_segdir table:
103883**
103884**   0: idx
103885**   1: start_block
103886**   2: leaves_end_block
103887**   3: end_block
103888**   4: root
103889*/
103890SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
103891  return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
103892}
103893
103894
103895/*
103896** Append a single varint to a PendingList buffer. SQLITE_OK is returned
103897** if successful, or an SQLite error code otherwise.
103898**
103899** This function also serves to allocate the PendingList structure itself.
103900** For example, to create a new PendingList structure containing two
103901** varints:
103902**
103903**   PendingList *p = 0;
103904**   fts3PendingListAppendVarint(&p, 1);
103905**   fts3PendingListAppendVarint(&p, 2);
103906*/
103907static int fts3PendingListAppendVarint(
103908  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
103909  sqlite3_int64 i                 /* Value to append to data */
103910){
103911  PendingList *p = *pp;
103912
103913  /* Allocate or grow the PendingList as required. */
103914  if( !p ){
103915    p = sqlite3_malloc(sizeof(*p) + 100);
103916    if( !p ){
103917      return SQLITE_NOMEM;
103918    }
103919    p->nSpace = 100;
103920    p->aData = (char *)&p[1];
103921    p->nData = 0;
103922  }
103923  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
103924    int nNew = p->nSpace * 2;
103925    p = sqlite3_realloc(p, sizeof(*p) + nNew);
103926    if( !p ){
103927      sqlite3_free(*pp);
103928      *pp = 0;
103929      return SQLITE_NOMEM;
103930    }
103931    p->nSpace = nNew;
103932    p->aData = (char *)&p[1];
103933  }
103934
103935  /* Append the new serialized varint to the end of the list. */
103936  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
103937  p->aData[p->nData] = '\0';
103938  *pp = p;
103939  return SQLITE_OK;
103940}
103941
103942/*
103943** Add a docid/column/position entry to a PendingList structure. Non-zero
103944** is returned if the structure is sqlite3_realloced as part of adding
103945** the entry. Otherwise, zero.
103946**
103947** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
103948** Zero is always returned in this case. Otherwise, if no OOM error occurs,
103949** it is set to SQLITE_OK.
103950*/
103951static int fts3PendingListAppend(
103952  PendingList **pp,               /* IN/OUT: PendingList structure */
103953  sqlite3_int64 iDocid,           /* Docid for entry to add */
103954  sqlite3_int64 iCol,             /* Column for entry to add */
103955  sqlite3_int64 iPos,             /* Position of term for entry to add */
103956  int *pRc                        /* OUT: Return code */
103957){
103958  PendingList *p = *pp;
103959  int rc = SQLITE_OK;
103960
103961  assert( !p || p->iLastDocid<=iDocid );
103962
103963  if( !p || p->iLastDocid!=iDocid ){
103964    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
103965    if( p ){
103966      assert( p->nData<p->nSpace );
103967      assert( p->aData[p->nData]==0 );
103968      p->nData++;
103969    }
103970    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
103971      goto pendinglistappend_out;
103972    }
103973    p->iLastCol = -1;
103974    p->iLastPos = 0;
103975    p->iLastDocid = iDocid;
103976  }
103977  if( iCol>0 && p->iLastCol!=iCol ){
103978    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
103979     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
103980    ){
103981      goto pendinglistappend_out;
103982    }
103983    p->iLastCol = iCol;
103984    p->iLastPos = 0;
103985  }
103986  if( iCol>=0 ){
103987    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
103988    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
103989    if( rc==SQLITE_OK ){
103990      p->iLastPos = iPos;
103991    }
103992  }
103993
103994 pendinglistappend_out:
103995  *pRc = rc;
103996  if( p!=*pp ){
103997    *pp = p;
103998    return 1;
103999  }
104000  return 0;
104001}
104002
104003/*
104004** Tokenize the nul-terminated string zText and add all tokens to the
104005** pending-terms hash-table. The docid used is that currently stored in
104006** p->iPrevDocid, and the column is specified by argument iCol.
104007**
104008** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
104009*/
104010static int fts3PendingTermsAdd(Fts3Table *p, const char *zText, int iCol){
104011  int rc;
104012  int iStart;
104013  int iEnd;
104014  int iPos;
104015
104016  char const *zToken;
104017  int nToken;
104018
104019  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
104020  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
104021  sqlite3_tokenizer_cursor *pCsr;
104022  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
104023      const char**,int*,int*,int*,int*);
104024
104025  assert( pTokenizer && pModule );
104026
104027  rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
104028  if( rc!=SQLITE_OK ){
104029    return rc;
104030  }
104031  pCsr->pTokenizer = pTokenizer;
104032
104033  xNext = pModule->xNext;
104034  while( SQLITE_OK==rc
104035      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
104036  ){
104037    PendingList *pList;
104038
104039    /* Positions cannot be negative; we use -1 as a terminator internally.
104040    ** Tokens must have a non-zero length.
104041    */
104042    if( iPos<0 || !zToken || nToken<=0 ){
104043      rc = SQLITE_ERROR;
104044      break;
104045    }
104046
104047    pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
104048    if( pList ){
104049      p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
104050    }
104051    if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
104052      if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
104053        /* Malloc failed while inserting the new entry. This can only
104054        ** happen if there was no previous entry for this token.
104055        */
104056        assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
104057        sqlite3_free(pList);
104058        rc = SQLITE_NOMEM;
104059      }
104060    }
104061    if( rc==SQLITE_OK ){
104062      p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
104063    }
104064  }
104065
104066  pModule->xClose(pCsr);
104067  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
104068}
104069
104070/*
104071** Calling this function indicates that subsequent calls to
104072** fts3PendingTermsAdd() are to add term/position-list pairs for the
104073** contents of the document with docid iDocid.
104074*/
104075static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
104076  /* TODO(shess) Explore whether partially flushing the buffer on
104077  ** forced-flush would provide better performance.  I suspect that if
104078  ** we ordered the doclists by size and flushed the largest until the
104079  ** buffer was half empty, that would let the less frequent terms
104080  ** generate longer doclists.
104081  */
104082  if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
104083    int rc = sqlite3Fts3PendingTermsFlush(p);
104084    if( rc!=SQLITE_OK ) return rc;
104085  }
104086  p->iPrevDocid = iDocid;
104087  return SQLITE_OK;
104088}
104089
104090SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
104091  Fts3HashElem *pElem;
104092  for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
104093    sqlite3_free(fts3HashData(pElem));
104094  }
104095  fts3HashClear(&p->pendingTerms);
104096  p->nPendingData = 0;
104097}
104098
104099/*
104100** This function is called by the xUpdate() method as part of an INSERT
104101** operation. It adds entries for each term in the new record to the
104102** pendingTerms hash table.
104103**
104104** Argument apVal is the same as the similarly named argument passed to
104105** fts3InsertData(). Parameter iDocid is the docid of the new row.
104106*/
104107static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal){
104108  int i;                          /* Iterator variable */
104109  for(i=2; i<p->nColumn+2; i++){
104110    const char *zText = (const char *)sqlite3_value_text(apVal[i]);
104111    if( zText ){
104112      int rc = fts3PendingTermsAdd(p, zText, i-2);
104113      if( rc!=SQLITE_OK ){
104114        return rc;
104115      }
104116    }
104117  }
104118  return SQLITE_OK;
104119}
104120
104121/*
104122** This function is called by the xUpdate() method for an INSERT operation.
104123** The apVal parameter is passed a copy of the apVal argument passed by
104124** SQLite to the xUpdate() method. i.e:
104125**
104126**   apVal[0]                Not used for INSERT.
104127**   apVal[1]                rowid
104128**   apVal[2]                Left-most user-defined column
104129**   ...
104130**   apVal[p->nColumn+1]     Right-most user-defined column
104131**   apVal[p->nColumn+2]     Hidden column with same name as table
104132**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
104133*/
104134static int fts3InsertData(
104135  Fts3Table *p,                   /* Full-text table */
104136  sqlite3_value **apVal,          /* Array of values to insert */
104137  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
104138){
104139  int rc;                         /* Return code */
104140  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
104141
104142  /* Locate the statement handle used to insert data into the %_content
104143  ** table. The SQL for this statement is:
104144  **
104145  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
104146  **
104147  ** The statement features N '?' variables, where N is the number of user
104148  ** defined columns in the FTS3 table, plus one for the docid field.
104149  */
104150  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
104151  if( rc!=SQLITE_OK ){
104152    return rc;
104153  }
104154
104155  /* There is a quirk here. The users INSERT statement may have specified
104156  ** a value for the "rowid" field, for the "docid" field, or for both.
104157  ** Which is a problem, since "rowid" and "docid" are aliases for the
104158  ** same value. For example:
104159  **
104160  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
104161  **
104162  ** In FTS3, this is an error. It is an error to specify non-NULL values
104163  ** for both docid and some other rowid alias.
104164  */
104165  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
104166    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
104167     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
104168    ){
104169      /* A rowid/docid conflict. */
104170      return SQLITE_ERROR;
104171    }
104172    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
104173    if( rc!=SQLITE_OK ) return rc;
104174  }
104175
104176  /* Execute the statement to insert the record. Set *piDocid to the
104177  ** new docid value.
104178  */
104179  sqlite3_step(pContentInsert);
104180  rc = sqlite3_reset(pContentInsert);
104181
104182  *piDocid = sqlite3_last_insert_rowid(p->db);
104183  return rc;
104184}
104185
104186
104187
104188/*
104189** Remove all data from the FTS3 table. Clear the hash table containing
104190** pending terms.
104191*/
104192static int fts3DeleteAll(Fts3Table *p){
104193  int rc;                         /* Return code */
104194
104195  /* Discard the contents of the pending-terms hash table. */
104196  sqlite3Fts3PendingTermsClear(p);
104197
104198  /* Delete everything from the %_content, %_segments and %_segdir tables. */
104199  rc = fts3SqlExec(p, SQL_DELETE_ALL_CONTENT, 0);
104200  if( rc==SQLITE_OK ){
104201    rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGMENTS, 0);
104202  }
104203  if( rc==SQLITE_OK ){
104204    rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGDIR, 0);
104205  }
104206  return rc;
104207}
104208
104209/*
104210** The first element in the apVal[] array is assumed to contain the docid
104211** (an integer) of a row about to be deleted. Remove all terms from the
104212** full-text index.
104213*/
104214static int fts3DeleteTerms(Fts3Table *p, sqlite3_value **apVal){
104215  int rc;
104216  sqlite3_stmt *pSelect;
104217
104218  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
104219  if( rc==SQLITE_OK ){
104220    if( SQLITE_ROW==sqlite3_step(pSelect) ){
104221      int i;
104222      for(i=1; i<=p->nColumn; i++){
104223        const char *zText = (const char *)sqlite3_column_text(pSelect, i);
104224        rc = fts3PendingTermsAdd(p, zText, -1);
104225        if( rc!=SQLITE_OK ){
104226          sqlite3_reset(pSelect);
104227          return rc;
104228        }
104229      }
104230    }
104231    rc = sqlite3_reset(pSelect);
104232  }else{
104233    sqlite3_reset(pSelect);
104234  }
104235  return rc;
104236}
104237
104238/*
104239** Forward declaration to account for the circular dependency between
104240** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
104241*/
104242static int fts3SegmentMerge(Fts3Table *, int);
104243
104244/*
104245** This function allocates a new level iLevel index in the segdir table.
104246** Usually, indexes are allocated within a level sequentially starting
104247** with 0, so the allocated index is one greater than the value returned
104248** by:
104249**
104250**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
104251**
104252** However, if there are already FTS3_MERGE_COUNT indexes at the requested
104253** level, they are merged into a single level (iLevel+1) segment and the
104254** allocated index is 0.
104255**
104256** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
104257** returned. Otherwise, an SQLite error code is returned.
104258*/
104259static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
104260  int rc;                         /* Return Code */
104261  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
104262  int iNext = 0;                  /* Result of query pNextIdx */
104263
104264  /* Set variable iNext to the next available segdir index at level iLevel. */
104265  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
104266  if( rc==SQLITE_OK ){
104267    sqlite3_bind_int(pNextIdx, 1, iLevel);
104268    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
104269      iNext = sqlite3_column_int(pNextIdx, 0);
104270    }
104271    rc = sqlite3_reset(pNextIdx);
104272  }
104273
104274  if( rc==SQLITE_OK ){
104275    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
104276    ** full, merge all segments in level iLevel into a single iLevel+1
104277    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
104278    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
104279    */
104280    if( iNext>=FTS3_MERGE_COUNT ){
104281      rc = fts3SegmentMerge(p, iLevel);
104282      *piIdx = 0;
104283    }else{
104284      *piIdx = iNext;
104285    }
104286  }
104287
104288  return rc;
104289}
104290
104291/*
104292** Move the iterator passed as the first argument to the next term in the
104293** segment. If successful, SQLITE_OK is returned. If there is no next term,
104294** SQLITE_DONE. Otherwise, an SQLite error code.
104295*/
104296static int fts3SegReaderNext(Fts3SegReader *pReader){
104297  char *pNext;                    /* Cursor variable */
104298  int nPrefix;                    /* Number of bytes in term prefix */
104299  int nSuffix;                    /* Number of bytes in term suffix */
104300
104301  if( !pReader->aDoclist ){
104302    pNext = pReader->aNode;
104303  }else{
104304    pNext = &pReader->aDoclist[pReader->nDoclist];
104305  }
104306
104307  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
104308    int rc;
104309    if( fts3SegReaderIsPending(pReader) ){
104310      Fts3HashElem *pElem = *(pReader->ppNextElem);
104311      if( pElem==0 ){
104312        pReader->aNode = 0;
104313      }else{
104314        PendingList *pList = (PendingList *)fts3HashData(pElem);
104315        pReader->zTerm = (char *)fts3HashKey(pElem);
104316        pReader->nTerm = fts3HashKeysize(pElem);
104317        pReader->nNode = pReader->nDoclist = pList->nData + 1;
104318        pReader->aNode = pReader->aDoclist = pList->aData;
104319        pReader->ppNextElem++;
104320        assert( pReader->aNode );
104321      }
104322      return SQLITE_OK;
104323    }
104324    if( !pReader->pStmt ){
104325      pReader->aNode = 0;
104326      return SQLITE_OK;
104327    }
104328    rc = sqlite3_step(pReader->pStmt);
104329    if( rc!=SQLITE_ROW ){
104330      pReader->aNode = 0;
104331      return (rc==SQLITE_DONE ? SQLITE_OK : rc);
104332    }
104333    pReader->nNode = sqlite3_column_bytes(pReader->pStmt, 0);
104334    pReader->aNode = (char *)sqlite3_column_blob(pReader->pStmt, 0);
104335    pNext = pReader->aNode;
104336  }
104337
104338  pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
104339  pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
104340
104341  if( nPrefix+nSuffix>pReader->nTermAlloc ){
104342    int nNew = (nPrefix+nSuffix)*2;
104343    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
104344    if( !zNew ){
104345      return SQLITE_NOMEM;
104346    }
104347    pReader->zTerm = zNew;
104348    pReader->nTermAlloc = nNew;
104349  }
104350  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
104351  pReader->nTerm = nPrefix+nSuffix;
104352  pNext += nSuffix;
104353  pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
104354  assert( pNext<&pReader->aNode[pReader->nNode] );
104355  pReader->aDoclist = pNext;
104356  pReader->pOffsetList = 0;
104357  return SQLITE_OK;
104358}
104359
104360/*
104361** Set the SegReader to point to the first docid in the doclist associated
104362** with the current term.
104363*/
104364static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
104365  int n;
104366  assert( pReader->aDoclist );
104367  assert( !pReader->pOffsetList );
104368  n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
104369  pReader->pOffsetList = &pReader->aDoclist[n];
104370}
104371
104372/*
104373** Advance the SegReader to point to the next docid in the doclist
104374** associated with the current term.
104375**
104376** If arguments ppOffsetList and pnOffsetList are not NULL, then
104377** *ppOffsetList is set to point to the first column-offset list
104378** in the doclist entry (i.e. immediately past the docid varint).
104379** *pnOffsetList is set to the length of the set of column-offset
104380** lists, not including the nul-terminator byte. For example:
104381*/
104382static void fts3SegReaderNextDocid(
104383  Fts3SegReader *pReader,
104384  char **ppOffsetList,
104385  int *pnOffsetList
104386){
104387  char *p = pReader->pOffsetList;
104388  char c = 0;
104389
104390  /* Pointer p currently points at the first byte of an offset list. The
104391  ** following two lines advance it to point one byte past the end of
104392  ** the same offset list.
104393  */
104394  while( *p | c ) c = *p++ & 0x80;
104395  p++;
104396
104397  /* If required, populate the output variables with a pointer to and the
104398  ** size of the previous offset-list.
104399  */
104400  if( ppOffsetList ){
104401    *ppOffsetList = pReader->pOffsetList;
104402    *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
104403  }
104404
104405  /* If there are no more entries in the doclist, set pOffsetList to
104406  ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
104407  ** Fts3SegReader.pOffsetList to point to the next offset list before
104408  ** returning.
104409  */
104410  if( p>=&pReader->aDoclist[pReader->nDoclist] ){
104411    pReader->pOffsetList = 0;
104412  }else{
104413    sqlite3_int64 iDelta;
104414    pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
104415    pReader->iDocid += iDelta;
104416  }
104417}
104418
104419/*
104420** Free all allocations associated with the iterator passed as the
104421** second argument.
104422*/
104423SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *p, Fts3SegReader *pReader){
104424  if( pReader ){
104425    if( pReader->pStmt ){
104426      /* Move the leaf-range SELECT statement to the aLeavesStmt[] array,
104427      ** so that it can be reused when required by another query.
104428      */
104429      assert( p->nLeavesStmt<p->nLeavesTotal );
104430      sqlite3_reset(pReader->pStmt);
104431      p->aLeavesStmt[p->nLeavesStmt++] = pReader->pStmt;
104432    }
104433    if( !fts3SegReaderIsPending(pReader) ){
104434      sqlite3_free(pReader->zTerm);
104435    }
104436    sqlite3_free(pReader);
104437  }
104438}
104439
104440/*
104441** Allocate a new SegReader object.
104442*/
104443SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
104444  Fts3Table *p,                   /* Virtual table handle */
104445  int iAge,                       /* Segment "age". */
104446  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
104447  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
104448  sqlite3_int64 iEndBlock,        /* Final block of segment */
104449  const char *zRoot,              /* Buffer containing root node */
104450  int nRoot,                      /* Size of buffer containing root node */
104451  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
104452){
104453  int rc = SQLITE_OK;             /* Return code */
104454  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
104455  int nExtra = 0;                 /* Bytes to allocate segment root node */
104456
104457  if( iStartLeaf==0 ){
104458    nExtra = nRoot;
104459  }
104460
104461  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
104462  if( !pReader ){
104463    return SQLITE_NOMEM;
104464  }
104465  memset(pReader, 0, sizeof(Fts3SegReader));
104466  pReader->iStartBlock = iStartLeaf;
104467  pReader->iIdx = iAge;
104468  pReader->iEndBlock = iEndBlock;
104469
104470  if( nExtra ){
104471    /* The entire segment is stored in the root node. */
104472    pReader->aNode = (char *)&pReader[1];
104473    pReader->nNode = nRoot;
104474    memcpy(pReader->aNode, zRoot, nRoot);
104475  }else{
104476    /* If the text of the SQL statement to iterate through a contiguous
104477    ** set of entries in the %_segments table has not yet been composed,
104478    ** compose it now.
104479    */
104480    if( !p->zSelectLeaves ){
104481      p->zSelectLeaves = sqlite3_mprintf(
104482          "SELECT block FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ? "
104483          "ORDER BY blockid", p->zDb, p->zName
104484      );
104485      if( !p->zSelectLeaves ){
104486        rc = SQLITE_NOMEM;
104487        goto finished;
104488      }
104489    }
104490
104491    /* If there are no free statements in the aLeavesStmt[] array, prepare
104492    ** a new statement now. Otherwise, reuse a prepared statement from
104493    ** aLeavesStmt[].
104494    */
104495    if( p->nLeavesStmt==0 ){
104496      if( p->nLeavesTotal==p->nLeavesAlloc ){
104497        int nNew = p->nLeavesAlloc + 16;
104498        sqlite3_stmt **aNew = (sqlite3_stmt **)sqlite3_realloc(
104499            p->aLeavesStmt, nNew*sizeof(sqlite3_stmt *)
104500        );
104501        if( !aNew ){
104502          rc = SQLITE_NOMEM;
104503          goto finished;
104504        }
104505        p->nLeavesAlloc = nNew;
104506        p->aLeavesStmt = aNew;
104507      }
104508      rc = sqlite3_prepare_v2(p->db, p->zSelectLeaves, -1, &pReader->pStmt, 0);
104509      if( rc!=SQLITE_OK ){
104510        goto finished;
104511      }
104512      p->nLeavesTotal++;
104513    }else{
104514      pReader->pStmt = p->aLeavesStmt[--p->nLeavesStmt];
104515    }
104516
104517    /* Bind the start and end leaf blockids to the prepared SQL statement. */
104518    sqlite3_bind_int64(pReader->pStmt, 1, iStartLeaf);
104519    sqlite3_bind_int64(pReader->pStmt, 2, iEndLeaf);
104520  }
104521  rc = fts3SegReaderNext(pReader);
104522
104523 finished:
104524  if( rc==SQLITE_OK ){
104525    *ppReader = pReader;
104526  }else{
104527    sqlite3Fts3SegReaderFree(p, pReader);
104528  }
104529  return rc;
104530}
104531
104532/*
104533** This is a comparison function used as a qsort() callback when sorting
104534** an array of pending terms by term. This occurs as part of flushing
104535** the contents of the pending-terms hash table to the database.
104536*/
104537static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
104538  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
104539  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
104540  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
104541  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
104542
104543  int n = (n1<n2 ? n1 : n2);
104544  int c = memcmp(z1, z2, n);
104545  if( c==0 ){
104546    c = n1 - n2;
104547  }
104548  return c;
104549}
104550
104551/*
104552** This function is used to allocate an Fts3SegReader that iterates through
104553** a subset of the terms stored in the Fts3Table.pendingTerms array.
104554*/
104555SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
104556  Fts3Table *p,                   /* Virtual table handle */
104557  const char *zTerm,              /* Term to search for */
104558  int nTerm,                      /* Size of buffer zTerm */
104559  int isPrefix,                   /* True for a term-prefix query */
104560  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
104561){
104562  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
104563  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
104564  int nElem = 0;                  /* Size of array at aElem */
104565  int rc = SQLITE_OK;             /* Return Code */
104566
104567  if( isPrefix ){
104568    int nAlloc = 0;               /* Size of allocated array at aElem */
104569    Fts3HashElem *pE = 0;         /* Iterator variable */
104570
104571    for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
104572      char *zKey = (char *)fts3HashKey(pE);
104573      int nKey = fts3HashKeysize(pE);
104574      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
104575        if( nElem==nAlloc ){
104576          Fts3HashElem **aElem2;
104577          nAlloc += 16;
104578          aElem2 = (Fts3HashElem **)sqlite3_realloc(
104579              aElem, nAlloc*sizeof(Fts3HashElem *)
104580          );
104581          if( !aElem2 ){
104582            rc = SQLITE_NOMEM;
104583            nElem = 0;
104584            break;
104585          }
104586          aElem = aElem2;
104587        }
104588        aElem[nElem++] = pE;
104589      }
104590    }
104591
104592    /* If more than one term matches the prefix, sort the Fts3HashElem
104593    ** objects in term order using qsort(). This uses the same comparison
104594    ** callback as is used when flushing terms to disk.
104595    */
104596    if( nElem>1 ){
104597      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
104598    }
104599
104600  }else{
104601    Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
104602    if( pE ){
104603      aElem = &pE;
104604      nElem = 1;
104605    }
104606  }
104607
104608  if( nElem>0 ){
104609    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
104610    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
104611    if( !pReader ){
104612      rc = SQLITE_NOMEM;
104613    }else{
104614      memset(pReader, 0, nByte);
104615      pReader->iIdx = 0x7FFFFFFF;
104616      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
104617      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
104618      fts3SegReaderNext(pReader);
104619    }
104620  }
104621
104622  if( isPrefix ){
104623    sqlite3_free(aElem);
104624  }
104625  *ppReader = pReader;
104626  return rc;
104627}
104628
104629
104630/*
104631** The second argument to this function is expected to be a statement of
104632** the form:
104633**
104634**   SELECT
104635**     idx,                  -- col 0
104636**     start_block,          -- col 1
104637**     leaves_end_block,     -- col 2
104638**     end_block,            -- col 3
104639**     root                  -- col 4
104640**   FROM %_segdir ...
104641**
104642** This function allocates and initializes a Fts3SegReader structure to
104643** iterate through the terms stored in the segment identified by the
104644** current row that pStmt is pointing to.
104645**
104646** If successful, the Fts3SegReader is left pointing to the first term
104647** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
104648** code is returned.
104649*/
104650static int fts3SegReaderNew(
104651  Fts3Table *p,                   /* Virtual table handle */
104652  sqlite3_stmt *pStmt,            /* See above */
104653  int iAge,                       /* Segment "age". */
104654  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
104655){
104656  return sqlite3Fts3SegReaderNew(p, iAge,
104657      sqlite3_column_int64(pStmt, 1),
104658      sqlite3_column_int64(pStmt, 2),
104659      sqlite3_column_int64(pStmt, 3),
104660      sqlite3_column_blob(pStmt, 4),
104661      sqlite3_column_bytes(pStmt, 4),
104662      ppReader
104663  );
104664}
104665
104666/*
104667** Compare the entries pointed to by two Fts3SegReader structures.
104668** Comparison is as follows:
104669**
104670**   1) EOF is greater than not EOF.
104671**
104672**   2) The current terms (if any) are compared using memcmp(). If one
104673**      term is a prefix of another, the longer term is considered the
104674**      larger.
104675**
104676**   3) By segment age. An older segment is considered larger.
104677*/
104678static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
104679  int rc;
104680  if( pLhs->aNode && pRhs->aNode ){
104681    int rc2 = pLhs->nTerm - pRhs->nTerm;
104682    if( rc2<0 ){
104683      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
104684    }else{
104685      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
104686    }
104687    if( rc==0 ){
104688      rc = rc2;
104689    }
104690  }else{
104691    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
104692  }
104693  if( rc==0 ){
104694    rc = pRhs->iIdx - pLhs->iIdx;
104695  }
104696  assert( rc!=0 );
104697  return rc;
104698}
104699
104700/*
104701** A different comparison function for SegReader structures. In this
104702** version, it is assumed that each SegReader points to an entry in
104703** a doclist for identical terms. Comparison is made as follows:
104704**
104705**   1) EOF (end of doclist in this case) is greater than not EOF.
104706**
104707**   2) By current docid.
104708**
104709**   3) By segment age. An older segment is considered larger.
104710*/
104711static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
104712  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
104713  if( rc==0 ){
104714    if( pLhs->iDocid==pRhs->iDocid ){
104715      rc = pRhs->iIdx - pLhs->iIdx;
104716    }else{
104717      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
104718    }
104719  }
104720  assert( pLhs->aNode && pRhs->aNode );
104721  return rc;
104722}
104723
104724/*
104725** Compare the term that the Fts3SegReader object passed as the first argument
104726** points to with the term specified by arguments zTerm and nTerm.
104727**
104728** If the pSeg iterator is already at EOF, return 0. Otherwise, return
104729** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
104730** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
104731*/
104732static int fts3SegReaderTermCmp(
104733  Fts3SegReader *pSeg,            /* Segment reader object */
104734  const char *zTerm,              /* Term to compare to */
104735  int nTerm                       /* Size of term zTerm in bytes */
104736){
104737  int res = 0;
104738  if( pSeg->aNode ){
104739    if( pSeg->nTerm>nTerm ){
104740      res = memcmp(pSeg->zTerm, zTerm, nTerm);
104741    }else{
104742      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
104743    }
104744    if( res==0 ){
104745      res = pSeg->nTerm-nTerm;
104746    }
104747  }
104748  return res;
104749}
104750
104751/*
104752** Argument apSegment is an array of nSegment elements. It is known that
104753** the final (nSegment-nSuspect) members are already in sorted order
104754** (according to the comparison function provided). This function shuffles
104755** the array around until all entries are in sorted order.
104756*/
104757static void fts3SegReaderSort(
104758  Fts3SegReader **apSegment,                     /* Array to sort entries of */
104759  int nSegment,                                  /* Size of apSegment array */
104760  int nSuspect,                                  /* Unsorted entry count */
104761  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
104762){
104763  int i;                          /* Iterator variable */
104764
104765  assert( nSuspect<=nSegment );
104766
104767  if( nSuspect==nSegment ) nSuspect--;
104768  for(i=nSuspect-1; i>=0; i--){
104769    int j;
104770    for(j=i; j<(nSegment-1); j++){
104771      Fts3SegReader *pTmp;
104772      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
104773      pTmp = apSegment[j+1];
104774      apSegment[j+1] = apSegment[j];
104775      apSegment[j] = pTmp;
104776    }
104777  }
104778
104779#ifndef NDEBUG
104780  /* Check that the list really is sorted now. */
104781  for(i=0; i<(nSuspect-1); i++){
104782    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
104783  }
104784#endif
104785}
104786
104787/*
104788** Insert a record into the %_segments table.
104789*/
104790static int fts3WriteSegment(
104791  Fts3Table *p,                   /* Virtual table handle */
104792  sqlite3_int64 iBlock,           /* Block id for new block */
104793  char *z,                        /* Pointer to buffer containing block data */
104794  int n                           /* Size of buffer z in bytes */
104795){
104796  sqlite3_stmt *pStmt;
104797  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
104798  if( rc==SQLITE_OK ){
104799    sqlite3_bind_int64(pStmt, 1, iBlock);
104800    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
104801    sqlite3_step(pStmt);
104802    rc = sqlite3_reset(pStmt);
104803  }
104804  return rc;
104805}
104806
104807/*
104808** Insert a record into the %_segdir table.
104809*/
104810static int fts3WriteSegdir(
104811  Fts3Table *p,                   /* Virtual table handle */
104812  int iLevel,                     /* Value for "level" field */
104813  int iIdx,                       /* Value for "idx" field */
104814  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
104815  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
104816  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
104817  char *zRoot,                    /* Blob value for "root" field */
104818  int nRoot                       /* Number of bytes in buffer zRoot */
104819){
104820  sqlite3_stmt *pStmt;
104821  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
104822  if( rc==SQLITE_OK ){
104823    sqlite3_bind_int(pStmt, 1, iLevel);
104824    sqlite3_bind_int(pStmt, 2, iIdx);
104825    sqlite3_bind_int64(pStmt, 3, iStartBlock);
104826    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
104827    sqlite3_bind_int64(pStmt, 5, iEndBlock);
104828    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
104829    sqlite3_step(pStmt);
104830    rc = sqlite3_reset(pStmt);
104831  }
104832  return rc;
104833}
104834
104835/*
104836** Return the size of the common prefix (if any) shared by zPrev and
104837** zNext, in bytes. For example,
104838**
104839**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
104840**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
104841**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
104842*/
104843static int fts3PrefixCompress(
104844  const char *zPrev,              /* Buffer containing previous term */
104845  int nPrev,                      /* Size of buffer zPrev in bytes */
104846  const char *zNext,              /* Buffer containing next term */
104847  int nNext                       /* Size of buffer zNext in bytes */
104848){
104849  int n;
104850  UNUSED_PARAMETER(nNext);
104851  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
104852  return n;
104853}
104854
104855/*
104856** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
104857** (according to memcmp) than the previous term.
104858*/
104859static int fts3NodeAddTerm(
104860  Fts3Table *p,               /* Virtual table handle */
104861  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
104862  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
104863  const char *zTerm,              /* Pointer to buffer containing term */
104864  int nTerm                       /* Size of term in bytes */
104865){
104866  SegmentNode *pTree = *ppTree;
104867  int rc;
104868  SegmentNode *pNew;
104869
104870  /* First try to append the term to the current node. Return early if
104871  ** this is possible.
104872  */
104873  if( pTree ){
104874    int nData = pTree->nData;     /* Current size of node in bytes */
104875    int nReq = nData;             /* Required space after adding zTerm */
104876    int nPrefix;                  /* Number of bytes of prefix compression */
104877    int nSuffix;                  /* Suffix length */
104878
104879    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
104880    nSuffix = nTerm-nPrefix;
104881
104882    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
104883    if( nReq<=p->nNodeSize || !pTree->zTerm ){
104884
104885      if( nReq>p->nNodeSize ){
104886        /* An unusual case: this is the first term to be added to the node
104887        ** and the static node buffer (p->nNodeSize bytes) is not large
104888        ** enough. Use a separately malloced buffer instead This wastes
104889        ** p->nNodeSize bytes, but since this scenario only comes about when
104890        ** the database contain two terms that share a prefix of almost 2KB,
104891        ** this is not expected to be a serious problem.
104892        */
104893        assert( pTree->aData==(char *)&pTree[1] );
104894        pTree->aData = (char *)sqlite3_malloc(nReq);
104895        if( !pTree->aData ){
104896          return SQLITE_NOMEM;
104897        }
104898      }
104899
104900      if( pTree->zTerm ){
104901        /* There is no prefix-length field for first term in a node */
104902        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
104903      }
104904
104905      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
104906      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
104907      pTree->nData = nData + nSuffix;
104908      pTree->nEntry++;
104909
104910      if( isCopyTerm ){
104911        if( pTree->nMalloc<nTerm ){
104912          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
104913          if( !zNew ){
104914            return SQLITE_NOMEM;
104915          }
104916          pTree->nMalloc = nTerm*2;
104917          pTree->zMalloc = zNew;
104918        }
104919        pTree->zTerm = pTree->zMalloc;
104920        memcpy(pTree->zTerm, zTerm, nTerm);
104921        pTree->nTerm = nTerm;
104922      }else{
104923        pTree->zTerm = (char *)zTerm;
104924        pTree->nTerm = nTerm;
104925      }
104926      return SQLITE_OK;
104927    }
104928  }
104929
104930  /* If control flows to here, it was not possible to append zTerm to the
104931  ** current node. Create a new node (a right-sibling of the current node).
104932  ** If this is the first node in the tree, the term is added to it.
104933  **
104934  ** Otherwise, the term is not added to the new node, it is left empty for
104935  ** now. Instead, the term is inserted into the parent of pTree. If pTree
104936  ** has no parent, one is created here.
104937  */
104938  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
104939  if( !pNew ){
104940    return SQLITE_NOMEM;
104941  }
104942  memset(pNew, 0, sizeof(SegmentNode));
104943  pNew->nData = 1 + FTS3_VARINT_MAX;
104944  pNew->aData = (char *)&pNew[1];
104945
104946  if( pTree ){
104947    SegmentNode *pParent = pTree->pParent;
104948    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
104949    if( pTree->pParent==0 ){
104950      pTree->pParent = pParent;
104951    }
104952    pTree->pRight = pNew;
104953    pNew->pLeftmost = pTree->pLeftmost;
104954    pNew->pParent = pParent;
104955    pNew->zMalloc = pTree->zMalloc;
104956    pNew->nMalloc = pTree->nMalloc;
104957    pTree->zMalloc = 0;
104958  }else{
104959    pNew->pLeftmost = pNew;
104960    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
104961  }
104962
104963  *ppTree = pNew;
104964  return rc;
104965}
104966
104967/*
104968** Helper function for fts3NodeWrite().
104969*/
104970static int fts3TreeFinishNode(
104971  SegmentNode *pTree,
104972  int iHeight,
104973  sqlite3_int64 iLeftChild
104974){
104975  int nStart;
104976  assert( iHeight>=1 && iHeight<128 );
104977  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
104978  pTree->aData[nStart] = (char)iHeight;
104979  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
104980  return nStart;
104981}
104982
104983/*
104984** Write the buffer for the segment node pTree and all of its peers to the
104985** database. Then call this function recursively to write the parent of
104986** pTree and its peers to the database.
104987**
104988** Except, if pTree is a root node, do not write it to the database. Instead,
104989** set output variables *paRoot and *pnRoot to contain the root node.
104990**
104991** If successful, SQLITE_OK is returned and output variable *piLast is
104992** set to the largest blockid written to the database (or zero if no
104993** blocks were written to the db). Otherwise, an SQLite error code is
104994** returned.
104995*/
104996static int fts3NodeWrite(
104997  Fts3Table *p,                   /* Virtual table handle */
104998  SegmentNode *pTree,             /* SegmentNode handle */
104999  int iHeight,                    /* Height of this node in tree */
105000  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
105001  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
105002  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
105003  char **paRoot,                  /* OUT: Data for root node */
105004  int *pnRoot                     /* OUT: Size of root node in bytes */
105005){
105006  int rc = SQLITE_OK;
105007
105008  if( !pTree->pParent ){
105009    /* Root node of the tree. */
105010    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
105011    *piLast = iFree-1;
105012    *pnRoot = pTree->nData - nStart;
105013    *paRoot = &pTree->aData[nStart];
105014  }else{
105015    SegmentNode *pIter;
105016    sqlite3_int64 iNextFree = iFree;
105017    sqlite3_int64 iNextLeaf = iLeaf;
105018    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
105019      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
105020      int nWrite = pIter->nData - nStart;
105021
105022      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
105023      iNextFree++;
105024      iNextLeaf += (pIter->nEntry+1);
105025    }
105026    if( rc==SQLITE_OK ){
105027      assert( iNextLeaf==iFree );
105028      rc = fts3NodeWrite(
105029          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
105030      );
105031    }
105032  }
105033
105034  return rc;
105035}
105036
105037/*
105038** Free all memory allocations associated with the tree pTree.
105039*/
105040static void fts3NodeFree(SegmentNode *pTree){
105041  if( pTree ){
105042    SegmentNode *p = pTree->pLeftmost;
105043    fts3NodeFree(p->pParent);
105044    while( p ){
105045      SegmentNode *pRight = p->pRight;
105046      if( p->aData!=(char *)&p[1] ){
105047        sqlite3_free(p->aData);
105048      }
105049      assert( pRight==0 || p->zMalloc==0 );
105050      sqlite3_free(p->zMalloc);
105051      sqlite3_free(p);
105052      p = pRight;
105053    }
105054  }
105055}
105056
105057/*
105058** Add a term to the segment being constructed by the SegmentWriter object
105059** *ppWriter. When adding the first term to a segment, *ppWriter should
105060** be passed NULL. This function will allocate a new SegmentWriter object
105061** and return it via the input/output variable *ppWriter in this case.
105062**
105063** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
105064*/
105065static int fts3SegWriterAdd(
105066  Fts3Table *p,                   /* Virtual table handle */
105067  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
105068  int isCopyTerm,                 /* True if buffer zTerm must be copied */
105069  const char *zTerm,              /* Pointer to buffer containing term */
105070  int nTerm,                      /* Size of term in bytes */
105071  const char *aDoclist,           /* Pointer to buffer containing doclist */
105072  int nDoclist                    /* Size of doclist in bytes */
105073){
105074  int nPrefix;                    /* Size of term prefix in bytes */
105075  int nSuffix;                    /* Size of term suffix in bytes */
105076  int nReq;                       /* Number of bytes required on leaf page */
105077  int nData;
105078  SegmentWriter *pWriter = *ppWriter;
105079
105080  if( !pWriter ){
105081    int rc;
105082    sqlite3_stmt *pStmt;
105083
105084    /* Allocate the SegmentWriter structure */
105085    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
105086    if( !pWriter ) return SQLITE_NOMEM;
105087    memset(pWriter, 0, sizeof(SegmentWriter));
105088    *ppWriter = pWriter;
105089
105090    /* Allocate a buffer in which to accumulate data */
105091    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
105092    if( !pWriter->aData ) return SQLITE_NOMEM;
105093    pWriter->nSize = p->nNodeSize;
105094
105095    /* Find the next free blockid in the %_segments table */
105096    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
105097    if( rc!=SQLITE_OK ) return rc;
105098    if( SQLITE_ROW==sqlite3_step(pStmt) ){
105099      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
105100      pWriter->iFirst = pWriter->iFree;
105101    }
105102    rc = sqlite3_reset(pStmt);
105103    if( rc!=SQLITE_OK ) return rc;
105104  }
105105  nData = pWriter->nData;
105106
105107  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
105108  nSuffix = nTerm-nPrefix;
105109
105110  /* Figure out how many bytes are required by this new entry */
105111  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
105112    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
105113    nSuffix +                               /* Term suffix */
105114    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
105115    nDoclist;                               /* Doclist data */
105116
105117  if( nData>0 && nData+nReq>p->nNodeSize ){
105118    int rc;
105119
105120    /* The current leaf node is full. Write it out to the database. */
105121    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
105122    if( rc!=SQLITE_OK ) return rc;
105123
105124    /* Add the current term to the interior node tree. The term added to
105125    ** the interior tree must:
105126    **
105127    **   a) be greater than the largest term on the leaf node just written
105128    **      to the database (still available in pWriter->zTerm), and
105129    **
105130    **   b) be less than or equal to the term about to be added to the new
105131    **      leaf node (zTerm/nTerm).
105132    **
105133    ** In other words, it must be the prefix of zTerm 1 byte longer than
105134    ** the common prefix (if any) of zTerm and pWriter->zTerm.
105135    */
105136    assert( nPrefix<nTerm );
105137    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
105138    if( rc!=SQLITE_OK ) return rc;
105139
105140    nData = 0;
105141    pWriter->nTerm = 0;
105142
105143    nPrefix = 0;
105144    nSuffix = nTerm;
105145    nReq = 1 +                              /* varint containing prefix size */
105146      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
105147      nTerm +                               /* Term suffix */
105148      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
105149      nDoclist;                             /* Doclist data */
105150  }
105151
105152  /* If the buffer currently allocated is too small for this entry, realloc
105153  ** the buffer to make it large enough.
105154  */
105155  if( nReq>pWriter->nSize ){
105156    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
105157    if( !aNew ) return SQLITE_NOMEM;
105158    pWriter->aData = aNew;
105159    pWriter->nSize = nReq;
105160  }
105161  assert( nData+nReq<=pWriter->nSize );
105162
105163  /* Append the prefix-compressed term and doclist to the buffer. */
105164  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
105165  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
105166  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
105167  nData += nSuffix;
105168  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
105169  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
105170  pWriter->nData = nData + nDoclist;
105171
105172  /* Save the current term so that it can be used to prefix-compress the next.
105173  ** If the isCopyTerm parameter is true, then the buffer pointed to by
105174  ** zTerm is transient, so take a copy of the term data. Otherwise, just
105175  ** store a copy of the pointer.
105176  */
105177  if( isCopyTerm ){
105178    if( nTerm>pWriter->nMalloc ){
105179      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
105180      if( !zNew ){
105181        return SQLITE_NOMEM;
105182      }
105183      pWriter->nMalloc = nTerm*2;
105184      pWriter->zMalloc = zNew;
105185      pWriter->zTerm = zNew;
105186    }
105187    assert( pWriter->zTerm==pWriter->zMalloc );
105188    memcpy(pWriter->zTerm, zTerm, nTerm);
105189  }else{
105190    pWriter->zTerm = (char *)zTerm;
105191  }
105192  pWriter->nTerm = nTerm;
105193
105194  return SQLITE_OK;
105195}
105196
105197/*
105198** Flush all data associated with the SegmentWriter object pWriter to the
105199** database. This function must be called after all terms have been added
105200** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
105201** returned. Otherwise, an SQLite error code.
105202*/
105203static int fts3SegWriterFlush(
105204  Fts3Table *p,                   /* Virtual table handle */
105205  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
105206  int iLevel,                     /* Value for 'level' column of %_segdir */
105207  int iIdx                        /* Value for 'idx' column of %_segdir */
105208){
105209  int rc;                         /* Return code */
105210  if( pWriter->pTree ){
105211    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
105212    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
105213    char *zRoot = NULL;           /* Pointer to buffer containing root node */
105214    int nRoot = 0;                /* Size of buffer zRoot */
105215
105216    iLastLeaf = pWriter->iFree;
105217    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
105218    if( rc==SQLITE_OK ){
105219      rc = fts3NodeWrite(p, pWriter->pTree, 1,
105220          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
105221    }
105222    if( rc==SQLITE_OK ){
105223      rc = fts3WriteSegdir(
105224          p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
105225    }
105226  }else{
105227    /* The entire tree fits on the root node. Write it to the segdir table. */
105228    rc = fts3WriteSegdir(
105229        p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
105230  }
105231  return rc;
105232}
105233
105234/*
105235** Release all memory held by the SegmentWriter object passed as the
105236** first argument.
105237*/
105238static void fts3SegWriterFree(SegmentWriter *pWriter){
105239  if( pWriter ){
105240    sqlite3_free(pWriter->aData);
105241    sqlite3_free(pWriter->zMalloc);
105242    fts3NodeFree(pWriter->pTree);
105243    sqlite3_free(pWriter);
105244  }
105245}
105246
105247/*
105248** The first value in the apVal[] array is assumed to contain an integer.
105249** This function tests if there exist any documents with docid values that
105250** are different from that integer. i.e. if deleting the document with docid
105251** apVal[0] would mean the FTS3 table were empty.
105252**
105253** If successful, *pisEmpty is set to true if the table is empty except for
105254** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
105255** error occurs, an SQLite error code is returned.
105256*/
105257static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
105258  sqlite3_stmt *pStmt;
105259  int rc;
105260  rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
105261  if( rc==SQLITE_OK ){
105262    if( SQLITE_ROW==sqlite3_step(pStmt) ){
105263      *pisEmpty = sqlite3_column_int(pStmt, 0);
105264    }
105265    rc = sqlite3_reset(pStmt);
105266  }
105267  return rc;
105268}
105269
105270/*
105271** Set *pnSegment to the number of segments of level iLevel in the database.
105272**
105273** Return SQLITE_OK if successful, or an SQLite error code if not.
105274*/
105275static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
105276  sqlite3_stmt *pStmt;
105277  int rc;
105278
105279  assert( iLevel>=0 );
105280  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
105281  if( rc!=SQLITE_OK ) return rc;
105282  sqlite3_bind_int(pStmt, 1, iLevel);
105283  if( SQLITE_ROW==sqlite3_step(pStmt) ){
105284    *pnSegment = sqlite3_column_int(pStmt, 0);
105285  }
105286  return sqlite3_reset(pStmt);
105287}
105288
105289/*
105290** Set *pnSegment to the total number of segments in the database. Set
105291** *pnMax to the largest segment level in the database (segment levels
105292** are stored in the 'level' column of the %_segdir table).
105293**
105294** Return SQLITE_OK if successful, or an SQLite error code if not.
105295*/
105296static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
105297  sqlite3_stmt *pStmt;
105298  int rc;
105299
105300  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
105301  if( rc!=SQLITE_OK ) return rc;
105302  if( SQLITE_ROW==sqlite3_step(pStmt) ){
105303    *pnSegment = sqlite3_column_int(pStmt, 0);
105304    *pnMax = sqlite3_column_int(pStmt, 1);
105305  }
105306  return sqlite3_reset(pStmt);
105307}
105308
105309/*
105310** This function is used after merging multiple segments into a single large
105311** segment to delete the old, now redundant, segment b-trees. Specifically,
105312** it:
105313**
105314**   1) Deletes all %_segments entries for the segments associated with
105315**      each of the SegReader objects in the array passed as the third
105316**      argument, and
105317**
105318**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
105319**      entries regardless of level if (iLevel<0).
105320**
105321** SQLITE_OK is returned if successful, otherwise an SQLite error code.
105322*/
105323static int fts3DeleteSegdir(
105324  Fts3Table *p,                   /* Virtual table handle */
105325  int iLevel,                     /* Level of %_segdir entries to delete */
105326  Fts3SegReader **apSegment,      /* Array of SegReader objects */
105327  int nReader                     /* Size of array apSegment */
105328){
105329  int rc;                         /* Return Code */
105330  int i;                          /* Iterator variable */
105331  sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
105332
105333  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
105334  for(i=0; rc==SQLITE_OK && i<nReader; i++){
105335    Fts3SegReader *pSegment = apSegment[i];
105336    if( pSegment->iStartBlock ){
105337      sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
105338      sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
105339      sqlite3_step(pDelete);
105340      rc = sqlite3_reset(pDelete);
105341    }
105342  }
105343  if( rc!=SQLITE_OK ){
105344    return rc;
105345  }
105346
105347  if( iLevel>=0 ){
105348    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
105349    if( rc==SQLITE_OK ){
105350      sqlite3_bind_int(pDelete, 1, iLevel);
105351      sqlite3_step(pDelete);
105352      rc = sqlite3_reset(pDelete);
105353    }
105354  }else{
105355    rc = fts3SqlExec(p, SQL_DELETE_ALL_SEGDIR, 0);
105356  }
105357
105358  return rc;
105359}
105360
105361/*
105362** When this function is called, buffer *ppList (size *pnList bytes) contains
105363** a position list that may (or may not) feature multiple columns. This
105364** function adjusts the pointer *ppList and the length *pnList so that they
105365** identify the subset of the position list that corresponds to column iCol.
105366**
105367** If there are no entries in the input position list for column iCol, then
105368** *pnList is set to zero before returning.
105369*/
105370static void fts3ColumnFilter(
105371  int iCol,                       /* Column to filter on */
105372  char **ppList,                  /* IN/OUT: Pointer to position list */
105373  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
105374){
105375  char *pList = *ppList;
105376  int nList = *pnList;
105377  char *pEnd = &pList[nList];
105378  int iCurrent = 0;
105379  char *p = pList;
105380
105381  assert( iCol>=0 );
105382  while( 1 ){
105383    char c = 0;
105384    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
105385
105386    if( iCol==iCurrent ){
105387      nList = (int)(p - pList);
105388      break;
105389    }
105390
105391    nList -= (int)(p - pList);
105392    pList = p;
105393    if( nList==0 ){
105394      break;
105395    }
105396    p = &pList[1];
105397    p += sqlite3Fts3GetVarint32(p, &iCurrent);
105398  }
105399
105400  *ppList = pList;
105401  *pnList = nList;
105402}
105403
105404/*
105405** sqlite3Fts3SegReaderIterate() callback used when merging multiple
105406** segments to create a single, larger segment.
105407*/
105408static int fts3MergeCallback(
105409  Fts3Table *p,                   /* FTS3 Virtual table handle */
105410  void *pContext,                 /* Pointer to SegmentWriter* to write with */
105411  char *zTerm,                    /* Term to write to the db */
105412  int nTerm,                      /* Number of bytes in zTerm */
105413  char *aDoclist,                 /* Doclist associated with zTerm */
105414  int nDoclist                    /* Number of bytes in doclist */
105415){
105416  SegmentWriter **ppW = (SegmentWriter **)pContext;
105417  return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
105418}
105419
105420/*
105421** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
105422** of the pending-terms hash table to the database.
105423*/
105424static int fts3FlushCallback(
105425  Fts3Table *p,                   /* FTS3 Virtual table handle */
105426  void *pContext,                 /* Pointer to SegmentWriter* to write with */
105427  char *zTerm,                    /* Term to write to the db */
105428  int nTerm,                      /* Number of bytes in zTerm */
105429  char *aDoclist,                 /* Doclist associated with zTerm */
105430  int nDoclist                    /* Number of bytes in doclist */
105431){
105432  SegmentWriter **ppW = (SegmentWriter **)pContext;
105433  return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
105434}
105435
105436/*
105437** This function is used to iterate through a contiguous set of terms
105438** stored in the full-text index. It merges data contained in one or
105439** more segments to support this.
105440**
105441** The second argument is passed an array of pointers to SegReader objects
105442** allocated with sqlite3Fts3SegReaderNew(). This function merges the range
105443** of terms selected by each SegReader. If a single term is present in
105444** more than one segment, the associated doclists are merged. For each
105445** term and (possibly merged) doclist in the merged range, the callback
105446** function xFunc is invoked with its arguments set as follows.
105447**
105448**   arg 0: Copy of 'p' parameter passed to this function
105449**   arg 1: Copy of 'pContext' parameter passed to this function
105450**   arg 2: Pointer to buffer containing term
105451**   arg 3: Size of arg 2 buffer in bytes
105452**   arg 4: Pointer to buffer containing doclist
105453**   arg 5: Size of arg 2 buffer in bytes
105454**
105455** The 4th argument to this function is a pointer to a structure of type
105456** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
105457** further restrict the range of terms that callbacks are made for and
105458** modify the behaviour of this function. See comments above structure
105459** definition for details.
105460*/
105461SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
105462  Fts3Table *p,                   /* Virtual table handle */
105463  Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
105464  int nSegment,                   /* Size of apSegment array */
105465  Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
105466  int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
105467  void *pContext                  /* Callback context (2nd argument) */
105468){
105469  int i;                          /* Iterator variable */
105470  char *aBuffer = 0;              /* Buffer to merge doclists in */
105471  int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
105472  int rc = SQLITE_OK;             /* Return code */
105473
105474  int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
105475  int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
105476  int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
105477  int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
105478
105479  /* If there are zero segments, this function is a no-op. This scenario
105480  ** comes about only when reading from an empty database.
105481  */
105482  if( nSegment==0 ) goto finished;
105483
105484  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
105485  ** for, then advance each segment iterator until it points to a term of
105486  ** equal or greater value than the specified term. This prevents many
105487  ** unnecessary merge/sort operations for the case where single segment
105488  ** b-tree leaf nodes contain more than one term.
105489  */
105490  if( pFilter->zTerm ){
105491    int nTerm = pFilter->nTerm;
105492    const char *zTerm = pFilter->zTerm;
105493    for(i=0; i<nSegment; i++){
105494      Fts3SegReader *pSeg = apSegment[i];
105495      while( fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 ){
105496        rc = fts3SegReaderNext(pSeg);
105497        if( rc!=SQLITE_OK ) goto finished; }
105498    }
105499  }
105500
105501  fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
105502  while( apSegment[0]->aNode ){
105503    int nTerm = apSegment[0]->nTerm;
105504    char *zTerm = apSegment[0]->zTerm;
105505    int nMerge = 1;
105506
105507    /* If this is a prefix-search, and if the term that apSegment[0] points
105508    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
105509    ** required callbacks have been made. In this case exit early.
105510    **
105511    ** Similarly, if this is a search for an exact match, and the first term
105512    ** of segment apSegment[0] is not a match, exit early.
105513    */
105514    if( pFilter->zTerm ){
105515      if( nTerm<pFilter->nTerm
105516       || (!isPrefix && nTerm>pFilter->nTerm)
105517       || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm)
105518    ){
105519        goto finished;
105520      }
105521    }
105522
105523    while( nMerge<nSegment
105524        && apSegment[nMerge]->aNode
105525        && apSegment[nMerge]->nTerm==nTerm
105526        && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
105527    ){
105528      nMerge++;
105529    }
105530
105531    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
105532    if( nMerge==1 && !isIgnoreEmpty ){
105533      Fts3SegReader *p0 = apSegment[0];
105534      rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
105535      if( rc!=SQLITE_OK ) goto finished;
105536    }else{
105537      int nDoclist = 0;           /* Size of doclist */
105538      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
105539
105540      /* The current term of the first nMerge entries in the array
105541      ** of Fts3SegReader objects is the same. The doclists must be merged
105542      ** and a single term added to the new segment.
105543      */
105544      for(i=0; i<nMerge; i++){
105545        fts3SegReaderFirstDocid(apSegment[i]);
105546      }
105547      fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
105548      while( apSegment[0]->pOffsetList ){
105549        int j;                    /* Number of segments that share a docid */
105550        char *pList;
105551        int nList;
105552        int nByte;
105553        sqlite3_int64 iDocid = apSegment[0]->iDocid;
105554        fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
105555        j = 1;
105556        while( j<nMerge
105557            && apSegment[j]->pOffsetList
105558            && apSegment[j]->iDocid==iDocid
105559        ){
105560          fts3SegReaderNextDocid(apSegment[j], 0, 0);
105561          j++;
105562        }
105563
105564        if( isColFilter ){
105565          fts3ColumnFilter(pFilter->iCol, &pList, &nList);
105566        }
105567
105568        if( !isIgnoreEmpty || nList>0 ){
105569          nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
105570          if( nDoclist+nByte>nAlloc ){
105571            char *aNew;
105572            nAlloc = nDoclist+nByte*2;
105573            aNew = sqlite3_realloc(aBuffer, nAlloc);
105574            if( !aNew ){
105575              rc = SQLITE_NOMEM;
105576              goto finished;
105577            }
105578            aBuffer = aNew;
105579          }
105580          nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
105581          iPrev = iDocid;
105582          if( isRequirePos ){
105583            memcpy(&aBuffer[nDoclist], pList, nList);
105584            nDoclist += nList;
105585            aBuffer[nDoclist++] = '\0';
105586          }
105587        }
105588
105589        fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
105590      }
105591
105592      if( nDoclist>0 ){
105593        rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
105594        if( rc!=SQLITE_OK ) goto finished;
105595      }
105596    }
105597
105598    /* If there is a term specified to filter on, and this is not a prefix
105599    ** search, return now. The callback that corresponds to the required
105600    ** term (if such a term exists in the index) has already been made.
105601    */
105602    if( pFilter->zTerm && !isPrefix ){
105603      goto finished;
105604    }
105605
105606    for(i=0; i<nMerge; i++){
105607      rc = fts3SegReaderNext(apSegment[i]);
105608      if( rc!=SQLITE_OK ) goto finished;
105609    }
105610    fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
105611  }
105612
105613 finished:
105614  sqlite3_free(aBuffer);
105615  return rc;
105616}
105617
105618/*
105619** Merge all level iLevel segments in the database into a single
105620** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
105621** single segment with a level equal to the numerically largest level
105622** currently present in the database.
105623**
105624** If this function is called with iLevel<0, but there is only one
105625** segment in the database, SQLITE_DONE is returned immediately.
105626** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
105627** an SQLite error code is returned.
105628*/
105629static int fts3SegmentMerge(Fts3Table *p, int iLevel){
105630  int i;                          /* Iterator variable */
105631  int rc;                         /* Return code */
105632  int iIdx;                       /* Index of new segment */
105633  int iNewLevel;                  /* Level to create new segment at */
105634  sqlite3_stmt *pStmt = 0;
105635  SegmentWriter *pWriter = 0;
105636  int nSegment = 0;               /* Number of segments being merged */
105637  Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
105638  Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
105639  Fts3SegFilter filter;           /* Segment term filter condition */
105640
105641  if( iLevel<0 ){
105642    /* This call is to merge all segments in the database to a single
105643    ** segment. The level of the new segment is equal to the the numerically
105644    ** greatest segment level currently present in the database. The index
105645    ** of the new segment is always 0.
105646    */
105647    iIdx = 0;
105648    rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
105649    if( rc!=SQLITE_OK ) goto finished;
105650    rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
105651    if( rc!=SQLITE_OK ) goto finished;
105652    nSegment += (pPending!=0);
105653    if( nSegment<=1 ){
105654      return SQLITE_DONE;
105655    }
105656  }else{
105657    /* This call is to merge all segments at level iLevel. Find the next
105658    ** available segment index at level iLevel+1. The call to
105659    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
105660    ** a single iLevel+2 segment if necessary.
105661    */
105662    iNewLevel = iLevel+1;
105663    rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
105664    if( rc!=SQLITE_OK ) goto finished;
105665    rc = fts3SegmentCount(p, iLevel, &nSegment);
105666    if( rc!=SQLITE_OK ) goto finished;
105667  }
105668  assert( nSegment>0 );
105669  assert( iNewLevel>=0 );
105670
105671  /* Allocate space for an array of pointers to segment iterators. */
105672  apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
105673  if( !apSegment ){
105674    rc = SQLITE_NOMEM;
105675    goto finished;
105676  }
105677  memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
105678
105679  /* Allocate a Fts3SegReader structure for each segment being merged. A
105680  ** Fts3SegReader stores the state data required to iterate through all
105681  ** entries on all leaves of a single segment.
105682  */
105683  assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
105684  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
105685  if( rc!=SQLITE_OK ) goto finished;
105686  sqlite3_bind_int(pStmt, 1, iLevel);
105687  for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
105688    rc = fts3SegReaderNew(p, pStmt, i, &apSegment[i]);
105689    if( rc!=SQLITE_OK ){
105690      goto finished;
105691    }
105692  }
105693  rc = sqlite3_reset(pStmt);
105694  if( pPending ){
105695    apSegment[i] = pPending;
105696    pPending = 0;
105697  }
105698  pStmt = 0;
105699  if( rc!=SQLITE_OK ) goto finished;
105700
105701  memset(&filter, 0, sizeof(Fts3SegFilter));
105702  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
105703  filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
105704  rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
105705      &filter, fts3MergeCallback, (void *)&pWriter
105706  );
105707  if( rc!=SQLITE_OK ) goto finished;
105708
105709  rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
105710  if( rc==SQLITE_OK ){
105711    rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
105712  }
105713
105714 finished:
105715  fts3SegWriterFree(pWriter);
105716  if( apSegment ){
105717    for(i=0; i<nSegment; i++){
105718      sqlite3Fts3SegReaderFree(p, apSegment[i]);
105719    }
105720    sqlite3_free(apSegment);
105721  }
105722  sqlite3Fts3SegReaderFree(p, pPending);
105723  sqlite3_reset(pStmt);
105724  return rc;
105725}
105726
105727
105728/*
105729** Flush the contents of pendingTerms to a level 0 segment.
105730*/
105731SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
105732  int rc;                         /* Return Code */
105733  int idx;                        /* Index of new segment created */
105734  SegmentWriter *pWriter = 0;     /* Used to write the segment */
105735  Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
105736
105737  /* Allocate a SegReader object to iterate through the contents of the
105738  ** pending-terms table. If an error occurs, or if there are no terms
105739  ** in the pending-terms table, return immediately.
105740  */
105741  rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
105742  if( rc!=SQLITE_OK || pReader==0 ){
105743    return rc;
105744  }
105745
105746  /* Determine the next index at level 0. If level 0 is already full, this
105747  ** call may merge all existing level 0 segments into a single level 1
105748  ** segment.
105749  */
105750  rc = fts3AllocateSegdirIdx(p, 0, &idx);
105751
105752  /* If no errors have occured, iterate through the contents of the
105753  ** pending-terms hash table using the Fts3SegReader iterator. The callback
105754  ** writes each term (along with its doclist) to the database via the
105755  ** SegmentWriter handle pWriter.
105756  */
105757  if( rc==SQLITE_OK ){
105758    void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
105759    Fts3SegFilter f;              /* SegReaderIterate() parameters */
105760
105761    memset(&f, 0, sizeof(Fts3SegFilter));
105762    f.flags = FTS3_SEGMENT_REQUIRE_POS;
105763    rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
105764  }
105765  assert( pWriter || rc!=SQLITE_OK );
105766
105767  /* If no errors have occured, flush the SegmentWriter object to the
105768  ** database. Then delete the SegmentWriter and Fts3SegReader objects
105769  ** allocated by this function.
105770  */
105771  if( rc==SQLITE_OK ){
105772    rc = fts3SegWriterFlush(p, pWriter, 0, idx);
105773  }
105774  fts3SegWriterFree(pWriter);
105775  sqlite3Fts3SegReaderFree(p, pReader);
105776
105777  if( rc==SQLITE_OK ){
105778    sqlite3Fts3PendingTermsClear(p);
105779  }
105780  return rc;
105781}
105782
105783/*
105784** Handle a 'special' INSERT of the form:
105785**
105786**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
105787**
105788** Argument pVal contains the result of <expr>. Currently the only
105789** meaningful value to insert is the text 'optimize'.
105790*/
105791static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
105792  int rc;                         /* Return Code */
105793  const char *zVal = (const char *)sqlite3_value_text(pVal);
105794  int nVal = sqlite3_value_bytes(pVal);
105795
105796  if( !zVal ){
105797    return SQLITE_NOMEM;
105798  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
105799    rc = fts3SegmentMerge(p, -1);
105800    if( rc==SQLITE_DONE ){
105801      rc = SQLITE_OK;
105802    }else{
105803      sqlite3Fts3PendingTermsClear(p);
105804    }
105805#ifdef SQLITE_TEST
105806  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
105807    p->nNodeSize = atoi(&zVal[9]);
105808    rc = SQLITE_OK;
105809  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
105810    p->nMaxPendingData = atoi(&zVal[11]);
105811    rc = SQLITE_OK;
105812#endif
105813  }else{
105814    rc = SQLITE_ERROR;
105815  }
105816
105817  return rc;
105818}
105819
105820/*
105821** This function does the work for the xUpdate method of FTS3 virtual
105822** tables.
105823*/
105824SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
105825  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
105826  int nArg,                       /* Size of argument array */
105827  sqlite3_value **apVal,          /* Array of arguments */
105828  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
105829){
105830  Fts3Table *p = (Fts3Table *)pVtab;
105831  int rc = SQLITE_OK;             /* Return Code */
105832  int isRemove = 0;               /* True for an UPDATE or DELETE */
105833  sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
105834
105835
105836  /* If this is a DELETE or UPDATE operation, remove the old record. */
105837  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
105838    int isEmpty;
105839    rc = fts3IsEmpty(p, apVal, &isEmpty);
105840    if( rc==SQLITE_OK ){
105841      if( isEmpty ){
105842        /* Deleting this row means the whole table is empty. In this case
105843        ** delete the contents of all three tables and throw away any
105844        ** data in the pendingTerms hash table.
105845        */
105846        rc = fts3DeleteAll(p);
105847      }else{
105848        isRemove = 1;
105849        iRemove = sqlite3_value_int64(apVal[0]);
105850        rc = fts3PendingTermsDocid(p, iRemove);
105851        if( rc==SQLITE_OK ){
105852          rc = fts3DeleteTerms(p, apVal);
105853          if( rc==SQLITE_OK ){
105854            rc = fts3SqlExec(p, SQL_DELETE_CONTENT, apVal);
105855          }
105856        }
105857      }
105858    }
105859  }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
105860    return fts3SpecialInsert(p, apVal[p->nColumn+2]);
105861  }
105862
105863  /* If this is an INSERT or UPDATE operation, insert the new record. */
105864  if( nArg>1 && rc==SQLITE_OK ){
105865    rc = fts3InsertData(p, apVal, pRowid);
105866    if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
105867      rc = fts3PendingTermsDocid(p, *pRowid);
105868    }
105869    if( rc==SQLITE_OK ){
105870      rc = fts3InsertTerms(p, apVal);
105871    }
105872  }
105873
105874  return rc;
105875}
105876
105877/*
105878** Flush any data in the pending-terms hash table to disk. If successful,
105879** merge all segments in the database (including the new segment, if
105880** there was any data to flush) into a single segment.
105881*/
105882SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
105883  int rc;
105884  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
105885  if( rc==SQLITE_OK ){
105886    rc = fts3SegmentMerge(p, -1);
105887    if( rc==SQLITE_OK ){
105888      rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
105889      if( rc==SQLITE_OK ){
105890        sqlite3Fts3PendingTermsClear(p);
105891      }
105892    }else{
105893      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
105894      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
105895    }
105896  }
105897  return rc;
105898}
105899
105900#endif
105901
105902/************** End of fts3_write.c ******************************************/
105903/************** Begin file fts3_snippet.c ************************************/
105904/*
105905** 2009 Oct 23
105906**
105907** The author disclaims copyright to this source code.  In place of
105908** a legal notice, here is a blessing:
105909**
105910**    May you do good and not evil.
105911**    May you find forgiveness for yourself and forgive others.
105912**    May you share freely, never taking more than you give.
105913**
105914******************************************************************************
105915*/
105916
105917#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
105918
105919
105920typedef struct Snippet Snippet;
105921
105922/*
105923** An instance of the following structure keeps track of generated
105924** matching-word offset information and snippets.
105925*/
105926struct Snippet {
105927  int nMatch;                     /* Total number of matches */
105928  int nAlloc;                     /* Space allocated for aMatch[] */
105929  struct snippetMatch {  /* One entry for each matching term */
105930    char snStatus;       /* Status flag for use while constructing snippets */
105931    short int nByte;     /* Number of bytes in the term */
105932    short int iCol;      /* The column that contains the match */
105933    short int iTerm;     /* The index in Query.pTerms[] of the matching term */
105934    int iToken;          /* The index of the matching document token */
105935    int iStart;          /* The offset to the first character of the term */
105936  } *aMatch;                      /* Points to space obtained from malloc */
105937  char *zOffset;                  /* Text rendering of aMatch[] */
105938  int nOffset;                    /* strlen(zOffset) */
105939  char *zSnippet;                 /* Snippet text */
105940  int nSnippet;                   /* strlen(zSnippet) */
105941};
105942
105943
105944/* It is not safe to call isspace(), tolower(), or isalnum() on
105945** hi-bit-set characters.  This is the same solution used in the
105946** tokenizer.
105947*/
105948static int fts3snippetIsspace(char c){
105949  return (c&0x80)==0 ? isspace(c) : 0;
105950}
105951
105952
105953/*
105954** A StringBuffer object holds a zero-terminated string that grows
105955** arbitrarily by appending.  Space to hold the string is obtained
105956** from sqlite3_malloc().  After any memory allocation failure,
105957** StringBuffer.z is set to NULL and no further allocation is attempted.
105958*/
105959typedef struct StringBuffer {
105960  char *z;         /* Text of the string.  Space from malloc. */
105961  int nUsed;       /* Number bytes of z[] used, not counting \000 terminator */
105962  int nAlloc;      /* Bytes allocated for z[] */
105963} StringBuffer;
105964
105965
105966/*
105967** Initialize a new StringBuffer.
105968*/
105969static void fts3SnippetSbInit(StringBuffer *p){
105970  p->nAlloc = 100;
105971  p->nUsed = 0;
105972  p->z = sqlite3_malloc( p->nAlloc );
105973}
105974
105975/*
105976** Append text to the string buffer.
105977*/
105978static void fts3SnippetAppend(StringBuffer *p, const char *zNew, int nNew){
105979  if( p->z==0 ) return;
105980  if( nNew<0 ) nNew = (int)strlen(zNew);
105981  if( p->nUsed + nNew >= p->nAlloc ){
105982    int nAlloc;
105983    char *zNew;
105984
105985    nAlloc = p->nUsed + nNew + p->nAlloc;
105986    zNew = sqlite3_realloc(p->z, nAlloc);
105987    if( zNew==0 ){
105988      sqlite3_free(p->z);
105989      p->z = 0;
105990      return;
105991    }
105992    p->z = zNew;
105993    p->nAlloc = nAlloc;
105994  }
105995  memcpy(&p->z[p->nUsed], zNew, nNew);
105996  p->nUsed += nNew;
105997  p->z[p->nUsed] = 0;
105998}
105999
106000/* If the StringBuffer ends in something other than white space, add a
106001** single space character to the end.
106002*/
106003static void fts3SnippetAppendWhiteSpace(StringBuffer *p){
106004  if( p->z && p->nUsed && !fts3snippetIsspace(p->z[p->nUsed-1]) ){
106005    fts3SnippetAppend(p, " ", 1);
106006  }
106007}
106008
106009/* Remove white space from the end of the StringBuffer */
106010static void fts3SnippetTrimWhiteSpace(StringBuffer *p){
106011  if( p->z ){
106012    while( p->nUsed && fts3snippetIsspace(p->z[p->nUsed-1]) ){
106013      p->nUsed--;
106014    }
106015    p->z[p->nUsed] = 0;
106016  }
106017}
106018
106019/*
106020** Release all memory associated with the Snippet structure passed as
106021** an argument.
106022*/
106023static void fts3SnippetFree(Snippet *p){
106024  if( p ){
106025    sqlite3_free(p->aMatch);
106026    sqlite3_free(p->zOffset);
106027    sqlite3_free(p->zSnippet);
106028    sqlite3_free(p);
106029  }
106030}
106031
106032/*
106033** Append a single entry to the p->aMatch[] log.
106034*/
106035static int snippetAppendMatch(
106036  Snippet *p,               /* Append the entry to this snippet */
106037  int iCol, int iTerm,      /* The column and query term */
106038  int iToken,               /* Matching token in document */
106039  int iStart, int nByte     /* Offset and size of the match */
106040){
106041  int i;
106042  struct snippetMatch *pMatch;
106043  if( p->nMatch+1>=p->nAlloc ){
106044    struct snippetMatch *pNew;
106045    p->nAlloc = p->nAlloc*2 + 10;
106046    pNew = sqlite3_realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) );
106047    if( pNew==0 ){
106048      p->aMatch = 0;
106049      p->nMatch = 0;
106050      p->nAlloc = 0;
106051      return SQLITE_NOMEM;
106052    }
106053    p->aMatch = pNew;
106054  }
106055  i = p->nMatch++;
106056  pMatch = &p->aMatch[i];
106057  pMatch->iCol = (short)iCol;
106058  pMatch->iTerm = (short)iTerm;
106059  pMatch->iToken = iToken;
106060  pMatch->iStart = iStart;
106061  pMatch->nByte = (short)nByte;
106062  return SQLITE_OK;
106063}
106064
106065/*
106066** Sizing information for the circular buffer used in snippetOffsetsOfColumn()
106067*/
106068#define FTS3_ROTOR_SZ   (32)
106069#define FTS3_ROTOR_MASK (FTS3_ROTOR_SZ-1)
106070
106071/*
106072** Function to iterate through the tokens of a compiled expression.
106073**
106074** Except, skip all tokens on the right-hand side of a NOT operator.
106075** This function is used to find tokens as part of snippet and offset
106076** generation and we do nt want snippets and offsets to report matches
106077** for tokens on the RHS of a NOT.
106078*/
106079static int fts3NextExprToken(Fts3Expr **ppExpr, int *piToken){
106080  Fts3Expr *p = *ppExpr;
106081  int iToken = *piToken;
106082  if( iToken<0 ){
106083    /* In this case the expression p is the root of an expression tree.
106084    ** Move to the first token in the expression tree.
106085    */
106086    while( p->pLeft ){
106087      p = p->pLeft;
106088    }
106089    iToken = 0;
106090  }else{
106091    assert(p && p->eType==FTSQUERY_PHRASE );
106092    if( iToken<(p->pPhrase->nToken-1) ){
106093      iToken++;
106094    }else{
106095      iToken = 0;
106096      while( p->pParent && p->pParent->pLeft!=p ){
106097        assert( p->pParent->pRight==p );
106098        p = p->pParent;
106099      }
106100      p = p->pParent;
106101      if( p ){
106102        assert( p->pRight!=0 );
106103        p = p->pRight;
106104        while( p->pLeft ){
106105          p = p->pLeft;
106106        }
106107      }
106108    }
106109  }
106110
106111  *ppExpr = p;
106112  *piToken = iToken;
106113  return p?1:0;
106114}
106115
106116/*
106117** Return TRUE if the expression node pExpr is located beneath the
106118** RHS of a NOT operator.
106119*/
106120static int fts3ExprBeneathNot(Fts3Expr *p){
106121  Fts3Expr *pParent;
106122  while( p ){
106123    pParent = p->pParent;
106124    if( pParent && pParent->eType==FTSQUERY_NOT && pParent->pRight==p ){
106125      return 1;
106126    }
106127    p = pParent;
106128  }
106129  return 0;
106130}
106131
106132/*
106133** Add entries to pSnippet->aMatch[] for every match that occurs against
106134** document zDoc[0..nDoc-1] which is stored in column iColumn.
106135*/
106136static int snippetOffsetsOfColumn(
106137  Fts3Cursor *pCur,         /* The fulltest search cursor */
106138  Snippet *pSnippet,             /* The Snippet object to be filled in */
106139  int iColumn,                   /* Index of fulltext table column */
106140  const char *zDoc,              /* Text of the fulltext table column */
106141  int nDoc                       /* Length of zDoc in bytes */
106142){
106143  const sqlite3_tokenizer_module *pTModule;  /* The tokenizer module */
106144  sqlite3_tokenizer *pTokenizer;             /* The specific tokenizer */
106145  sqlite3_tokenizer_cursor *pTCursor;        /* Tokenizer cursor */
106146  Fts3Table *pVtab;                /* The full text index */
106147  int nColumn;                         /* Number of columns in the index */
106148  int i, j;                            /* Loop counters */
106149  int rc;                              /* Return code */
106150  unsigned int match, prevMatch;       /* Phrase search bitmasks */
106151  const char *zToken;                  /* Next token from the tokenizer */
106152  int nToken;                          /* Size of zToken */
106153  int iBegin, iEnd, iPos;              /* Offsets of beginning and end */
106154
106155  /* The following variables keep a circular buffer of the last
106156  ** few tokens */
106157  unsigned int iRotor = 0;             /* Index of current token */
106158  int iRotorBegin[FTS3_ROTOR_SZ];      /* Beginning offset of token */
106159  int iRotorLen[FTS3_ROTOR_SZ];        /* Length of token */
106160
106161  pVtab =  (Fts3Table *)pCur->base.pVtab;
106162  nColumn = pVtab->nColumn;
106163  pTokenizer = pVtab->pTokenizer;
106164  pTModule = pTokenizer->pModule;
106165  rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor);
106166  if( rc ) return rc;
106167  pTCursor->pTokenizer = pTokenizer;
106168
106169  prevMatch = 0;
106170  while( (rc = pTModule->xNext(pTCursor, &zToken, &nToken,
106171                               &iBegin, &iEnd, &iPos))==SQLITE_OK ){
106172    Fts3Expr *pIter = pCur->pExpr;
106173    int iIter = -1;
106174    iRotorBegin[iRotor&FTS3_ROTOR_MASK] = iBegin;
106175    iRotorLen[iRotor&FTS3_ROTOR_MASK] = iEnd-iBegin;
106176    match = 0;
106177    for(i=0; i<(FTS3_ROTOR_SZ-1) && fts3NextExprToken(&pIter, &iIter); i++){
106178      int nPhrase;                    /* Number of tokens in current phrase */
106179      struct PhraseToken *pToken;     /* Current token */
106180      int iCol;                       /* Column index */
106181
106182      if( fts3ExprBeneathNot(pIter) ) continue;
106183      nPhrase = pIter->pPhrase->nToken;
106184      pToken = &pIter->pPhrase->aToken[iIter];
106185      iCol = pIter->pPhrase->iColumn;
106186      if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue;
106187      if( pToken->n>nToken ) continue;
106188      if( !pToken->isPrefix && pToken->n<nToken ) continue;
106189      assert( pToken->n<=nToken );
106190      if( memcmp(pToken->z, zToken, pToken->n) ) continue;
106191      if( iIter>0 && (prevMatch & (1<<i))==0 ) continue;
106192      match |= 1<<i;
106193      if( i==(FTS3_ROTOR_SZ-2) || nPhrase==iIter+1 ){
106194        for(j=nPhrase-1; j>=0; j--){
106195          int k = (iRotor-j) & FTS3_ROTOR_MASK;
106196          rc = snippetAppendMatch(pSnippet, iColumn, i-j, iPos-j,
106197                                  iRotorBegin[k], iRotorLen[k]);
106198          if( rc ) goto end_offsets_of_column;
106199        }
106200      }
106201    }
106202    prevMatch = match<<1;
106203    iRotor++;
106204  }
106205end_offsets_of_column:
106206  pTModule->xClose(pTCursor);
106207  return rc==SQLITE_DONE ? SQLITE_OK : rc;
106208}
106209
106210/*
106211** Remove entries from the pSnippet structure to account for the NEAR
106212** operator. When this is called, pSnippet contains the list of token
106213** offsets produced by treating all NEAR operators as AND operators.
106214** This function removes any entries that should not be present after
106215** accounting for the NEAR restriction. For example, if the queried
106216** document is:
106217**
106218**     "A B C D E A"
106219**
106220** and the query is:
106221**
106222**     A NEAR/0 E
106223**
106224** then when this function is called the Snippet contains token offsets
106225** 0, 4 and 5. This function removes the "0" entry (because the first A
106226** is not near enough to an E).
106227**
106228** When this function is called, the value pointed to by parameter piLeft is
106229** the integer id of the left-most token in the expression tree headed by
106230** pExpr. This function increments *piLeft by the total number of tokens
106231** in the expression tree headed by pExpr.
106232**
106233** Return 1 if any trimming occurs.  Return 0 if no trimming is required.
106234*/
106235static int trimSnippetOffsets(
106236  Fts3Expr *pExpr,      /* The search expression */
106237  Snippet *pSnippet,    /* The set of snippet offsets to be trimmed */
106238  int *piLeft           /* Index of left-most token in pExpr */
106239){
106240  if( pExpr ){
106241    if( trimSnippetOffsets(pExpr->pLeft, pSnippet, piLeft) ){
106242      return 1;
106243    }
106244
106245    switch( pExpr->eType ){
106246      case FTSQUERY_PHRASE:
106247        *piLeft += pExpr->pPhrase->nToken;
106248        break;
106249      case FTSQUERY_NEAR: {
106250        /* The right-hand-side of a NEAR operator is always a phrase. The
106251        ** left-hand-side is either a phrase or an expression tree that is
106252        ** itself headed by a NEAR operator. The following initializations
106253        ** set local variable iLeft to the token number of the left-most
106254        ** token in the right-hand phrase, and iRight to the right most
106255        ** token in the same phrase. For example, if we had:
106256        **
106257        **     <col> MATCH '"abc def" NEAR/2 "ghi jkl"'
106258        **
106259        ** then iLeft will be set to 2 (token number of ghi) and nToken will
106260        ** be set to 4.
106261        */
106262        Fts3Expr *pLeft = pExpr->pLeft;
106263        Fts3Expr *pRight = pExpr->pRight;
106264        int iLeft = *piLeft;
106265        int nNear = pExpr->nNear;
106266        int nToken = pRight->pPhrase->nToken;
106267        int jj, ii;
106268        if( pLeft->eType==FTSQUERY_NEAR ){
106269          pLeft = pLeft->pRight;
106270        }
106271        assert( pRight->eType==FTSQUERY_PHRASE );
106272        assert( pLeft->eType==FTSQUERY_PHRASE );
106273        nToken += pLeft->pPhrase->nToken;
106274
106275        for(ii=0; ii<pSnippet->nMatch; ii++){
106276          struct snippetMatch *p = &pSnippet->aMatch[ii];
106277          if( p->iTerm==iLeft ){
106278            int isOk = 0;
106279            /* Snippet ii is an occurence of query term iLeft in the document.
106280            ** It occurs at position (p->iToken) of the document. We now
106281            ** search for an instance of token (iLeft-1) somewhere in the
106282            ** range (p->iToken - nNear)...(p->iToken + nNear + nToken) within
106283            ** the set of snippetMatch structures. If one is found, proceed.
106284            ** If one cannot be found, then remove snippets ii..(ii+N-1)
106285            ** from the matching snippets, where N is the number of tokens
106286            ** in phrase pRight->pPhrase.
106287            */
106288            for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
106289              struct snippetMatch *p2 = &pSnippet->aMatch[jj];
106290              if( p2->iTerm==(iLeft-1) ){
106291                if( p2->iToken>=(p->iToken-nNear-1)
106292                 && p2->iToken<(p->iToken+nNear+nToken)
106293                ){
106294                  isOk = 1;
106295                }
106296              }
106297            }
106298            if( !isOk ){
106299              int kk;
106300              for(kk=0; kk<pRight->pPhrase->nToken; kk++){
106301                pSnippet->aMatch[kk+ii].iTerm = -2;
106302              }
106303              return 1;
106304            }
106305          }
106306          if( p->iTerm==(iLeft-1) ){
106307            int isOk = 0;
106308            for(jj=0; isOk==0 && jj<pSnippet->nMatch; jj++){
106309              struct snippetMatch *p2 = &pSnippet->aMatch[jj];
106310              if( p2->iTerm==iLeft ){
106311                if( p2->iToken<=(p->iToken+nNear+1)
106312                 && p2->iToken>(p->iToken-nNear-nToken)
106313                ){
106314                  isOk = 1;
106315                }
106316              }
106317            }
106318            if( !isOk ){
106319              int kk;
106320              for(kk=0; kk<pLeft->pPhrase->nToken; kk++){
106321                pSnippet->aMatch[ii-kk].iTerm = -2;
106322              }
106323              return 1;
106324            }
106325          }
106326        }
106327        break;
106328      }
106329    }
106330
106331    if( trimSnippetOffsets(pExpr->pRight, pSnippet, piLeft) ){
106332      return 1;
106333    }
106334  }
106335  return 0;
106336}
106337
106338/*
106339** Compute all offsets for the current row of the query.
106340** If the offsets have already been computed, this routine is a no-op.
106341*/
106342static int snippetAllOffsets(Fts3Cursor *pCsr, Snippet **ppSnippet){
106343  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;  /* The FTS3 virtual table */
106344  int nColumn;           /* Number of columns.  Docid does count */
106345  int iColumn;           /* Index of of a column */
106346  int i;                 /* Loop index */
106347  int iFirst;            /* First column to search */
106348  int iLast;             /* Last coumn to search */
106349  int iTerm = 0;
106350  Snippet *pSnippet;
106351  int rc = SQLITE_OK;
106352
106353  if( pCsr->pExpr==0 ){
106354    return SQLITE_OK;
106355  }
106356
106357  pSnippet = (Snippet *)sqlite3_malloc(sizeof(Snippet));
106358  *ppSnippet = pSnippet;
106359  if( !pSnippet ){
106360    return SQLITE_NOMEM;
106361  }
106362  memset(pSnippet, 0, sizeof(Snippet));
106363
106364  nColumn = p->nColumn;
106365  iColumn = (pCsr->eSearch - 2);
106366  if( iColumn<0 || iColumn>=nColumn ){
106367    /* Look for matches over all columns of the full-text index */
106368    iFirst = 0;
106369    iLast = nColumn-1;
106370  }else{
106371    /* Look for matches in the iColumn-th column of the index only */
106372    iFirst = iColumn;
106373    iLast = iColumn;
106374  }
106375  for(i=iFirst; rc==SQLITE_OK && i<=iLast; i++){
106376    const char *zDoc;
106377    int nDoc;
106378    zDoc = (const char*)sqlite3_column_text(pCsr->pStmt, i+1);
106379    nDoc = sqlite3_column_bytes(pCsr->pStmt, i+1);
106380    if( zDoc==0 && sqlite3_column_type(pCsr->pStmt, i+1)!=SQLITE_NULL ){
106381      rc = SQLITE_NOMEM;
106382    }else{
106383      rc = snippetOffsetsOfColumn(pCsr, pSnippet, i, zDoc, nDoc);
106384    }
106385  }
106386
106387  while( trimSnippetOffsets(pCsr->pExpr, pSnippet, &iTerm) ){
106388    iTerm = 0;
106389  }
106390
106391  return rc;
106392}
106393
106394/*
106395** Convert the information in the aMatch[] array of the snippet
106396** into the string zOffset[0..nOffset-1]. This string is used as
106397** the return of the SQL offsets() function.
106398*/
106399static void snippetOffsetText(Snippet *p){
106400  int i;
106401  int cnt = 0;
106402  StringBuffer sb;
106403  char zBuf[200];
106404  if( p->zOffset ) return;
106405  fts3SnippetSbInit(&sb);
106406  for(i=0; i<p->nMatch; i++){
106407    struct snippetMatch *pMatch = &p->aMatch[i];
106408    if( pMatch->iTerm>=0 ){
106409      /* If snippetMatch.iTerm is less than 0, then the match was
106410      ** discarded as part of processing the NEAR operator (see the
106411      ** trimSnippetOffsetsForNear() function for details). Ignore
106412      ** it in this case
106413      */
106414      zBuf[0] = ' ';
106415      sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d",
106416          pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte);
106417      fts3SnippetAppend(&sb, zBuf, -1);
106418      cnt++;
106419    }
106420  }
106421  p->zOffset = sb.z;
106422  p->nOffset = sb.z ? sb.nUsed : 0;
106423}
106424
106425/*
106426** zDoc[0..nDoc-1] is phrase of text.  aMatch[0..nMatch-1] are a set
106427** of matching words some of which might be in zDoc.  zDoc is column
106428** number iCol.
106429**
106430** iBreak is suggested spot in zDoc where we could begin or end an
106431** excerpt.  Return a value similar to iBreak but possibly adjusted
106432** to be a little left or right so that the break point is better.
106433*/
106434static int wordBoundary(
106435  int iBreak,                   /* The suggested break point */
106436  const char *zDoc,             /* Document text */
106437  int nDoc,                     /* Number of bytes in zDoc[] */
106438  struct snippetMatch *aMatch,  /* Matching words */
106439  int nMatch,                   /* Number of entries in aMatch[] */
106440  int iCol                      /* The column number for zDoc[] */
106441){
106442  int i;
106443  if( iBreak<=10 ){
106444    return 0;
106445  }
106446  if( iBreak>=nDoc-10 ){
106447    return nDoc;
106448  }
106449  for(i=0; ALWAYS(i<nMatch) && aMatch[i].iCol<iCol; i++){}
106450  while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; }
106451  if( i<nMatch ){
106452    if( aMatch[i].iStart<iBreak+10 ){
106453      return aMatch[i].iStart;
106454    }
106455    if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){
106456      return aMatch[i-1].iStart;
106457    }
106458  }
106459  for(i=1; i<=10; i++){
106460    if( fts3snippetIsspace(zDoc[iBreak-i]) ){
106461      return iBreak - i + 1;
106462    }
106463    if( fts3snippetIsspace(zDoc[iBreak+i]) ){
106464      return iBreak + i + 1;
106465    }
106466  }
106467  return iBreak;
106468}
106469
106470
106471
106472/*
106473** Allowed values for Snippet.aMatch[].snStatus
106474*/
106475#define SNIPPET_IGNORE  0   /* It is ok to omit this match from the snippet */
106476#define SNIPPET_DESIRED 1   /* We want to include this match in the snippet */
106477
106478/*
106479** Generate the text of a snippet.
106480*/
106481static void snippetText(
106482  Fts3Cursor *pCursor,   /* The cursor we need the snippet for */
106483  Snippet *pSnippet,
106484  const char *zStartMark,     /* Markup to appear before each match */
106485  const char *zEndMark,       /* Markup to appear after each match */
106486  const char *zEllipsis       /* Ellipsis mark */
106487){
106488  int i, j;
106489  struct snippetMatch *aMatch;
106490  int nMatch;
106491  int nDesired;
106492  StringBuffer sb;
106493  int tailCol;
106494  int tailOffset;
106495  int iCol;
106496  int nDoc;
106497  const char *zDoc;
106498  int iStart, iEnd;
106499  int tailEllipsis = 0;
106500  int iMatch;
106501
106502
106503  sqlite3_free(pSnippet->zSnippet);
106504  pSnippet->zSnippet = 0;
106505  aMatch = pSnippet->aMatch;
106506  nMatch = pSnippet->nMatch;
106507  fts3SnippetSbInit(&sb);
106508
106509  for(i=0; i<nMatch; i++){
106510    aMatch[i].snStatus = SNIPPET_IGNORE;
106511  }
106512  nDesired = 0;
106513  for(i=0; i<FTS3_ROTOR_SZ; i++){
106514    for(j=0; j<nMatch; j++){
106515      if( aMatch[j].iTerm==i ){
106516        aMatch[j].snStatus = SNIPPET_DESIRED;
106517        nDesired++;
106518        break;
106519      }
106520    }
106521  }
106522
106523  iMatch = 0;
106524  tailCol = -1;
106525  tailOffset = 0;
106526  for(i=0; i<nMatch && nDesired>0; i++){
106527    if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue;
106528    nDesired--;
106529    iCol = aMatch[i].iCol;
106530    zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1);
106531    nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1);
106532    iStart = aMatch[i].iStart - 40;
106533    iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol);
106534    if( iStart<=10 ){
106535      iStart = 0;
106536    }
106537    if( iCol==tailCol && iStart<=tailOffset+20 ){
106538      iStart = tailOffset;
106539    }
106540    if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){
106541      fts3SnippetTrimWhiteSpace(&sb);
106542      fts3SnippetAppendWhiteSpace(&sb);
106543      fts3SnippetAppend(&sb, zEllipsis, -1);
106544      fts3SnippetAppendWhiteSpace(&sb);
106545    }
106546    iEnd = aMatch[i].iStart + aMatch[i].nByte + 40;
106547    iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol);
106548    if( iEnd>=nDoc-10 ){
106549      iEnd = nDoc;
106550      tailEllipsis = 0;
106551    }else{
106552      tailEllipsis = 1;
106553    }
106554    while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; }
106555    while( iStart<iEnd ){
106556      while( iMatch<nMatch && aMatch[iMatch].iStart<iStart
106557             && aMatch[iMatch].iCol<=iCol ){
106558        iMatch++;
106559      }
106560      if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd
106561             && aMatch[iMatch].iCol==iCol ){
106562        fts3SnippetAppend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart);
106563        iStart = aMatch[iMatch].iStart;
106564        fts3SnippetAppend(&sb, zStartMark, -1);
106565        fts3SnippetAppend(&sb, &zDoc[iStart], aMatch[iMatch].nByte);
106566        fts3SnippetAppend(&sb, zEndMark, -1);
106567        iStart += aMatch[iMatch].nByte;
106568        for(j=iMatch+1; j<nMatch; j++){
106569          if( aMatch[j].iTerm==aMatch[iMatch].iTerm
106570              && aMatch[j].snStatus==SNIPPET_DESIRED ){
106571            nDesired--;
106572            aMatch[j].snStatus = SNIPPET_IGNORE;
106573          }
106574        }
106575      }else{
106576        fts3SnippetAppend(&sb, &zDoc[iStart], iEnd - iStart);
106577        iStart = iEnd;
106578      }
106579    }
106580    tailCol = iCol;
106581    tailOffset = iEnd;
106582  }
106583  fts3SnippetTrimWhiteSpace(&sb);
106584  if( tailEllipsis ){
106585    fts3SnippetAppendWhiteSpace(&sb);
106586    fts3SnippetAppend(&sb, zEllipsis, -1);
106587  }
106588  pSnippet->zSnippet = sb.z;
106589  pSnippet->nSnippet = sb.z ? sb.nUsed : 0;
106590}
106591
106592SQLITE_PRIVATE void sqlite3Fts3Offsets(
106593  sqlite3_context *pCtx,          /* SQLite function call context */
106594  Fts3Cursor *pCsr                /* Cursor object */
106595){
106596  Snippet *p;                     /* Snippet structure */
106597  int rc = snippetAllOffsets(pCsr, &p);
106598  if( rc==SQLITE_OK ){
106599    snippetOffsetText(p);
106600    if( p->zOffset ){
106601      sqlite3_result_text(pCtx, p->zOffset, p->nOffset, SQLITE_TRANSIENT);
106602    }else{
106603      sqlite3_result_error_nomem(pCtx);
106604    }
106605  }else{
106606    sqlite3_result_error_nomem(pCtx);
106607  }
106608  fts3SnippetFree(p);
106609}
106610
106611SQLITE_PRIVATE void sqlite3Fts3Snippet(
106612  sqlite3_context *pCtx,          /* SQLite function call context */
106613  Fts3Cursor *pCsr,               /* Cursor object */
106614  const char *zStart,             /* Snippet start text - "<b>" */
106615  const char *zEnd,               /* Snippet end text - "</b>" */
106616  const char *zEllipsis           /* Snippet ellipsis text - "<b>...</b>" */
106617){
106618  Snippet *p;                     /* Snippet structure */
106619  int rc = snippetAllOffsets(pCsr, &p);
106620  if( rc==SQLITE_OK ){
106621    snippetText(pCsr, p, zStart, zEnd, zEllipsis);
106622    if( p->zSnippet ){
106623      sqlite3_result_text(pCtx, p->zSnippet, p->nSnippet, SQLITE_TRANSIENT);
106624    }else{
106625      sqlite3_result_error_nomem(pCtx);
106626    }
106627  }else{
106628    sqlite3_result_error_nomem(pCtx);
106629  }
106630  fts3SnippetFree(p);
106631}
106632
106633/*************************************************************************
106634** Below this point is the alternative, experimental snippet() implementation.
106635*/
106636
106637#define SNIPPET_BUFFER_CHUNK  64
106638#define SNIPPET_BUFFER_SIZE   SNIPPET_BUFFER_CHUNK*4
106639#define SNIPPET_BUFFER_MASK   (SNIPPET_BUFFER_SIZE-1)
106640
106641static void fts3GetDeltaPosition(char **pp, int *piPos){
106642  int iVal;
106643  *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
106644  *piPos += (iVal-2);
106645}
106646
106647/*
106648** Iterate through all phrase nodes in an FTS3 query, except those that
106649** are part of a sub-tree that is the right-hand-side of a NOT operator.
106650** For each phrase node found, the supplied callback function is invoked.
106651**
106652** If the callback function returns anything other than SQLITE_OK,
106653** the iteration is abandoned and the error code returned immediately.
106654** Otherwise, SQLITE_OK is returned after a callback has been made for
106655** all eligible phrase nodes.
106656*/
106657static int fts3ExprIterate(
106658  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
106659  int (*x)(Fts3Expr *, void *),   /* Callback function to invoke for phrases */
106660  void *pCtx                      /* Second argument to pass to callback */
106661){
106662  int rc;
106663  int eType = pExpr->eType;
106664  if( eType==FTSQUERY_NOT ){
106665    rc = SQLITE_OK;
106666  }else if( eType!=FTSQUERY_PHRASE ){
106667    assert( pExpr->pLeft && pExpr->pRight );
106668    rc = fts3ExprIterate(pExpr->pLeft, x, pCtx);
106669    if( rc==SQLITE_OK ){
106670      rc = fts3ExprIterate(pExpr->pRight, x, pCtx);
106671    }
106672  }else{
106673    rc = x(pExpr, pCtx);
106674  }
106675  return rc;
106676}
106677
106678typedef struct LoadDoclistCtx LoadDoclistCtx;
106679struct LoadDoclistCtx {
106680  Fts3Table *pTab;                /* FTS3 Table */
106681  int nPhrase;                    /* Number of phrases so far */
106682};
106683
106684static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, void *ctx){
106685  int rc = SQLITE_OK;
106686  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
106687  p->nPhrase++;
106688  if( pExpr->isLoaded==0 ){
106689    rc = sqlite3Fts3ExprLoadDoclist(p->pTab, pExpr);
106690    pExpr->isLoaded = 1;
106691    if( rc==SQLITE_OK && pExpr->aDoclist ){
106692      pExpr->pCurrent = pExpr->aDoclist;
106693      pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent,&pExpr->iCurrent);
106694    }
106695  }
106696  return rc;
106697}
106698
106699static int fts3ExprLoadDoclists(Fts3Cursor *pCsr, int *pnPhrase){
106700  int rc;
106701  LoadDoclistCtx sCtx = {0, 0};
106702  sCtx.pTab = (Fts3Table *)pCsr->base.pVtab;
106703  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
106704  *pnPhrase = sCtx.nPhrase;
106705  return rc;
106706}
106707
106708/*
106709** Each call to this function populates a chunk of a snippet-buffer
106710** SNIPPET_BUFFER_CHUNK bytes in size.
106711**
106712** Return true if the end of the data has been reached (and all subsequent
106713** calls to fts3LoadSnippetBuffer() with the same arguments will be no-ops),
106714** or false otherwise.
106715*/
106716static int fts3LoadSnippetBuffer(
106717  int iPos,                       /* Document token offset to load data for */
106718  u8 *aBuffer,                    /* Circular snippet buffer to populate */
106719  int nList,                      /* Number of position lists in appList */
106720  char **apList,                  /* IN/OUT: nList position list pointers */
106721  int *aiPrev                     /* IN/OUT: Previous positions read */
106722){
106723  int i;
106724  int nFin = 0;
106725
106726  assert( (iPos&(SNIPPET_BUFFER_CHUNK-1))==0 );
106727
106728  memset(&aBuffer[iPos&SNIPPET_BUFFER_MASK], 0, SNIPPET_BUFFER_CHUNK);
106729
106730  for(i=0; i<nList; i++){
106731    int iPrev = aiPrev[i];
106732    char *pList = apList[i];
106733
106734    if( !pList ){
106735      nFin++;
106736      continue;
106737    }
106738
106739    while( iPrev<(iPos+SNIPPET_BUFFER_CHUNK) ){
106740      if( iPrev>=iPos ){
106741        aBuffer[iPrev&SNIPPET_BUFFER_MASK] = (u8)(i+1);
106742      }
106743      if( 0==((*pList)&0xFE) ){
106744        nFin++;
106745        break;
106746      }
106747      fts3GetDeltaPosition(&pList, &iPrev);
106748    }
106749
106750    aiPrev[i] = iPrev;
106751    apList[i] = pList;
106752  }
106753
106754  return (nFin==nList);
106755}
106756
106757typedef struct SnippetCtx SnippetCtx;
106758struct SnippetCtx {
106759  Fts3Cursor *pCsr;
106760  int iCol;
106761  int iPhrase;
106762  int *aiPrev;
106763  int *anToken;
106764  char **apList;
106765};
106766
106767static int fts3SnippetFindPositions(Fts3Expr *pExpr, void *ctx){
106768  SnippetCtx *p = (SnippetCtx *)ctx;
106769  int iPhrase = p->iPhrase++;
106770  char *pCsr;
106771
106772  p->anToken[iPhrase] = pExpr->pPhrase->nToken;
106773  pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
106774
106775  if( pCsr ){
106776    int iVal;
106777    pCsr += sqlite3Fts3GetVarint32(pCsr, &iVal);
106778    p->apList[iPhrase] = pCsr;
106779    p->aiPrev[iPhrase] = iVal-2;
106780  }
106781  return SQLITE_OK;
106782}
106783
106784static void fts3SnippetCnt(
106785  int iIdx,
106786  int nSnippet,
106787  int *anCnt,
106788  u8 *aBuffer,
106789  int *anToken,
106790  u64 *pHlmask
106791){
106792  int iSub =  (iIdx-1)&SNIPPET_BUFFER_MASK;
106793  int iAdd =  (iIdx+nSnippet-1)&SNIPPET_BUFFER_MASK;
106794  int iSub2 = (iIdx+(nSnippet/3)-1)&SNIPPET_BUFFER_MASK;
106795  int iAdd2 = (iIdx+(nSnippet*2/3)-1)&SNIPPET_BUFFER_MASK;
106796
106797  u64 h = *pHlmask;
106798
106799  anCnt[ aBuffer[iSub]  ]--;
106800  anCnt[ aBuffer[iSub2] ]--;
106801  anCnt[ aBuffer[iAdd]  ]++;
106802  anCnt[ aBuffer[iAdd2] ]++;
106803
106804  h = h >> 1;
106805  if( aBuffer[iAdd] ){
106806    int j;
106807    for(j=anToken[aBuffer[iAdd]-1]; j>=1; j--){
106808      h |= (u64)1 << (nSnippet-j);
106809    }
106810  }
106811  *pHlmask = h;
106812}
106813
106814static int fts3SnippetScore(int n, int *anCnt){
106815  int j;
106816  int iScore = 0;
106817  for(j=1; j<=n; j++){
106818    int nCnt = anCnt[j];
106819    iScore += nCnt + (nCnt ? 1000 : 0);
106820  }
106821  return iScore;
106822}
106823
106824static int fts3BestSnippet(
106825  int nSnippet,                   /* Desired snippet length */
106826  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
106827  int iCol,                       /* Index of column to create snippet from */
106828  int *piPos,                     /* OUT: Starting token for best snippet */
106829  u64 *pHlmask                    /* OUT: Highlight mask for best snippet */
106830){
106831  int rc;                         /* Return Code */
106832  u8 aBuffer[SNIPPET_BUFFER_SIZE];/* Circular snippet buffer */
106833  int *aiPrev;                    /* Used by fts3LoadSnippetBuffer() */
106834  int *anToken;                   /* Number of tokens in each phrase */
106835  char **apList;                  /* Array of position lists */
106836  int *anCnt;                     /* Running totals of phrase occurences */
106837  int nList;
106838
106839  int i;
106840
106841  u64 hlmask = 0;                 /* Current mask of highlighted terms */
106842  u64 besthlmask = 0;             /* Mask of highlighted terms for iBestPos */
106843  int iBestPos = 0;               /* Starting position of 'best' snippet */
106844  int iBestScore = 0;             /* Score of best snippet higher->better */
106845  SnippetCtx sCtx;
106846
106847  /* Iterate through the phrases in the expression to count them. The same
106848  ** callback makes sure the doclists are loaded for each phrase.
106849  */
106850  rc = fts3ExprLoadDoclists(pCsr, &nList);
106851  if( rc!=SQLITE_OK ){
106852    return rc;
106853  }
106854
106855  /* Now that it is known how many phrases there are, allocate and zero
106856  ** the required arrays using malloc().
106857  */
106858  apList = sqlite3_malloc(
106859      sizeof(u8*)*nList +         /* apList */
106860      sizeof(int)*(nList) +       /* anToken */
106861      sizeof(int)*nList +         /* aiPrev */
106862      sizeof(int)*(nList+1)       /* anCnt */
106863  );
106864  if( !apList ){
106865    return SQLITE_NOMEM;
106866  }
106867  memset(apList, 0, sizeof(u8*)*nList+sizeof(int)*nList+sizeof(int)*nList);
106868  anToken = (int *)&apList[nList];
106869  aiPrev = &anToken[nList];
106870  anCnt = &aiPrev[nList];
106871
106872  /* Initialize the contents of the aiPrev and aiList arrays. */
106873  sCtx.pCsr = pCsr;
106874  sCtx.iCol = iCol;
106875  sCtx.apList = apList;
106876  sCtx.aiPrev = aiPrev;
106877  sCtx.anToken = anToken;
106878  sCtx.iPhrase = 0;
106879  (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sCtx);
106880
106881  /* Load the first two chunks of data into the buffer. */
106882  memset(aBuffer, 0, SNIPPET_BUFFER_SIZE);
106883  fts3LoadSnippetBuffer(0, aBuffer, nList, apList, aiPrev);
106884  fts3LoadSnippetBuffer(SNIPPET_BUFFER_CHUNK, aBuffer, nList, apList, aiPrev);
106885
106886  /* Set the initial contents of the highlight-mask and anCnt[] array. */
106887  for(i=1-nSnippet; i<=0; i++){
106888    fts3SnippetCnt(i, nSnippet, anCnt, aBuffer, anToken, &hlmask);
106889  }
106890  iBestScore = fts3SnippetScore(nList, anCnt);
106891  besthlmask = hlmask;
106892  iBestPos = 0;
106893
106894  for(i=1; 1; i++){
106895    int iScore;
106896
106897    if( 0==(i&(SNIPPET_BUFFER_CHUNK-1)) ){
106898      int iLoad = i + SNIPPET_BUFFER_CHUNK;
106899      if( fts3LoadSnippetBuffer(iLoad, aBuffer, nList, apList, aiPrev) ) break;
106900    }
106901
106902    /* Figure out how highly a snippet starting at token offset i scores
106903    ** according to fts3SnippetScore(). If it is higher than any previously
106904    ** considered position, save the current position, score and hlmask as
106905    ** the best snippet candidate found so far.
106906    */
106907    fts3SnippetCnt(i, nSnippet, anCnt, aBuffer, anToken, &hlmask);
106908    iScore = fts3SnippetScore(nList, anCnt);
106909    if( iScore>iBestScore ){
106910      iBestPos = i;
106911      iBestScore = iScore;
106912      besthlmask = hlmask;
106913    }
106914  }
106915
106916  sqlite3_free(apList);
106917  *piPos = iBestPos;
106918  *pHlmask = besthlmask;
106919  return SQLITE_OK;
106920}
106921
106922typedef struct StrBuffer StrBuffer;
106923struct StrBuffer {
106924  char *z;
106925  int n;
106926  int nAlloc;
106927};
106928
106929static int fts3StringAppend(
106930  StrBuffer *pStr,
106931  const char *zAppend,
106932  int nAppend
106933){
106934  if( nAppend<0 ){
106935    nAppend = (int)strlen(zAppend);
106936  }
106937
106938  if( pStr->n+nAppend+1>=pStr->nAlloc ){
106939    int nAlloc = pStr->nAlloc+nAppend+100;
106940    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
106941    if( !zNew ){
106942      return SQLITE_NOMEM;
106943    }
106944    pStr->z = zNew;
106945    pStr->nAlloc = nAlloc;
106946  }
106947
106948  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
106949  pStr->n += nAppend;
106950  pStr->z[pStr->n] = '\0';
106951
106952  return SQLITE_OK;
106953}
106954
106955static int fts3SnippetText(
106956  Fts3Cursor *pCsr,               /* FTS3 Cursor */
106957  const char *zDoc,               /* Document to extract snippet from */
106958  int nDoc,                       /* Size of zDoc in bytes */
106959  int nSnippet,                   /* Number of tokens in extracted snippet */
106960  int iPos,                       /* Index of first document token in snippet */
106961  u64 hlmask,                     /* Bitmask of terms to highlight in snippet */
106962  const char *zOpen,              /* String inserted before highlighted term */
106963  const char *zClose,             /* String inserted after highlighted term */
106964  const char *zEllipsis,
106965  char **pzSnippet                /* OUT: Snippet text */
106966){
106967  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
106968  int rc;                         /* Return code */
106969  int iCurrent = 0;
106970  int iStart = 0;
106971  int iEnd;
106972
106973  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
106974  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
106975  const char *ZDUMMY;             /* Dummy arguments used with tokenizer */
106976  int DUMMY1, DUMMY2, DUMMY3;     /* Dummy arguments used with tokenizer */
106977
106978  StrBuffer res = {0, 0, 0};   /* Result string */
106979
106980  /* Open a token cursor on the document. Read all tokens up to and
106981  ** including token iPos (the first token of the snippet). Set variable
106982  ** iStart to the byte offset in zDoc of the start of token iPos.
106983  */
106984  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
106985  rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
106986  while( rc==SQLITE_OK && iCurrent<iPos ){
106987    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iStart, &DUMMY2, &iCurrent);
106988  }
106989  iEnd = iStart;
106990
106991  if( rc==SQLITE_OK && iStart>0 ){
106992    rc = fts3StringAppend(&res, zEllipsis, -1);
106993  }
106994
106995  while( rc==SQLITE_OK ){
106996    int iBegin;
106997    int iFin;
106998    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
106999
107000    if( rc==SQLITE_OK ){
107001      if( iCurrent>=(iPos+nSnippet) ){
107002        rc = SQLITE_DONE;
107003      }else{
107004        iEnd = iFin;
107005        if( hlmask & ((u64)1 << (iCurrent-iPos)) ){
107006          if( fts3StringAppend(&res, &zDoc[iStart], iBegin-iStart)
107007           || fts3StringAppend(&res, zOpen, -1)
107008           || fts3StringAppend(&res, &zDoc[iBegin], iEnd-iBegin)
107009           || fts3StringAppend(&res, zClose, -1)
107010          ){
107011            rc = SQLITE_NOMEM;
107012          }
107013          iStart = iEnd;
107014        }
107015      }
107016    }
107017  }
107018  assert( rc!=SQLITE_OK );
107019  if( rc==SQLITE_DONE ){
107020    rc = fts3StringAppend(&res, &zDoc[iStart], iEnd-iStart);
107021    if( rc==SQLITE_OK ){
107022      rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
107023      if( rc==SQLITE_OK ){
107024        rc = fts3StringAppend(&res, zEllipsis, -1);
107025      }else if( rc==SQLITE_DONE ){
107026        rc = fts3StringAppend(&res, &zDoc[iEnd], -1);
107027      }
107028    }
107029  }
107030
107031  pMod->xClose(pC);
107032  if( rc!=SQLITE_OK ){
107033    sqlite3_free(res.z);
107034  }else{
107035    *pzSnippet = res.z;
107036  }
107037  return rc;
107038}
107039
107040
107041/*
107042** An instance of this structure is used to collect the 'global' part of
107043** the matchinfo statistics. The 'global' part consists of the following:
107044**
107045**   1. The number of phrases in the query (nPhrase).
107046**
107047**   2. The number of columns in the FTS3 table (nCol).
107048**
107049**   3. A matrix of (nPhrase*nCol) integers containing the sum of the
107050**      number of hits for each phrase in each column across all rows
107051**      of the table.
107052**
107053** The total size of the global matchinfo array, assuming the number of
107054** columns is N and the number of phrases is P is:
107055**
107056**   2 + P*(N+1)
107057**
107058** The number of hits for the 3rd phrase in the second column is found
107059** using the expression:
107060**
107061**   aGlobal[2 + P*(1+2) + 1]
107062*/
107063typedef struct MatchInfo MatchInfo;
107064struct MatchInfo {
107065  Fts3Table *pTab;                /* FTS3 Table */
107066  Fts3Cursor *pCursor;            /* FTS3 Cursor */
107067  int iPhrase;                    /* Number of phrases so far */
107068  int nCol;                       /* Number of columns in table */
107069  u32 *aGlobal;                   /* Pre-allocated buffer */
107070};
107071
107072/*
107073** This function is used to count the entries in a column-list (delta-encoded
107074** list of term offsets within a single column of a single row).
107075*/
107076static int fts3ColumnlistCount(char **ppCollist){
107077  char *pEnd = *ppCollist;
107078  char c = 0;
107079  int nEntry = 0;
107080
107081  /* A column-list is terminated by either a 0x01 or 0x00. */
107082  while( 0xFE & (*pEnd | c) ){
107083    c = *pEnd++ & 0x80;
107084    if( !c ) nEntry++;
107085  }
107086
107087  *ppCollist = pEnd;
107088  return nEntry;
107089}
107090
107091static void fts3LoadColumnlistCounts(char **pp, u32 *aOut){
107092  char *pCsr = *pp;
107093  while( *pCsr ){
107094    sqlite3_int64 iCol = 0;
107095    if( *pCsr==0x01 ){
107096      pCsr++;
107097      pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
107098    }
107099    aOut[iCol] += fts3ColumnlistCount(&pCsr);
107100  }
107101  pCsr++;
107102  *pp = pCsr;
107103}
107104
107105/*
107106** fts3ExprIterate() callback used to collect the "global" matchinfo stats
107107** for a single query.
107108*/
107109static int fts3ExprGlobalMatchinfoCb(
107110  Fts3Expr *pExpr,                /* Phrase expression node */
107111  void *pCtx                      /* Pointer to MatchInfo structure */
107112){
107113  MatchInfo *p = (MatchInfo *)pCtx;
107114  char *pCsr;
107115  char *pEnd;
107116  const int iStart = 2 + p->nCol*p->iPhrase;
107117
107118  assert( pExpr->isLoaded );
107119
107120  /* Fill in the global hit count matrix row for this phrase. */
107121  pCsr = pExpr->aDoclist;
107122  pEnd = &pExpr->aDoclist[pExpr->nDoclist];
107123  while( pCsr<pEnd ){
107124    while( *pCsr++ & 0x80 );
107125    fts3LoadColumnlistCounts(&pCsr, &p->aGlobal[iStart]);
107126  }
107127
107128  p->iPhrase++;
107129  return SQLITE_OK;
107130}
107131
107132static int fts3ExprLocalMatchinfoCb(
107133  Fts3Expr *pExpr,                /* Phrase expression node */
107134  void *pCtx                      /* Pointer to MatchInfo structure */
107135){
107136  MatchInfo *p = (MatchInfo *)pCtx;
107137  int iPhrase = p->iPhrase++;
107138
107139  if( pExpr->aDoclist ){
107140    char *pCsr;
107141    int iOffset = 2 + p->nCol*(p->aGlobal[0]+iPhrase);
107142
107143    memset(&p->aGlobal[iOffset], 0, p->nCol*sizeof(u32));
107144    pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
107145    if( pCsr ) fts3LoadColumnlistCounts(&pCsr, &p->aGlobal[iOffset]);
107146  }
107147
107148  return SQLITE_OK;
107149}
107150
107151/*
107152** Populate pCsr->aMatchinfo[] with data for the current row. The 'matchinfo'
107153** data is an array of 32-bit unsigned integers (C type u32).
107154*/
107155static int fts3GetMatchinfo(Fts3Cursor *pCsr){
107156  MatchInfo g;
107157  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
107158  if( pCsr->aMatchinfo==0 ){
107159    int rc;
107160    int nPhrase;
107161    int nMatchinfo;
107162
107163    g.pTab = pTab;
107164    g.nCol = pTab->nColumn;
107165    g.iPhrase = 0;
107166    rc = fts3ExprLoadDoclists(pCsr, &nPhrase);
107167    if( rc!=SQLITE_OK ){
107168      return rc;
107169    }
107170
107171    nMatchinfo = 2 + 2*g.nCol*nPhrase;
107172
107173    g.iPhrase = 0;
107174    g.aGlobal = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo);
107175    if( !g.aGlobal ){
107176      return SQLITE_NOMEM;
107177    }
107178    memset(g.aGlobal, 0, sizeof(u32)*nMatchinfo);
107179
107180    g.aGlobal[0] = nPhrase;
107181    g.aGlobal[1] = g.nCol;
107182    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprGlobalMatchinfoCb, (void *)&g);
107183
107184    pCsr->aMatchinfo = g.aGlobal;
107185  }
107186
107187  g.pTab = pTab;
107188  g.pCursor = pCsr;
107189  g.nCol = pTab->nColumn;
107190  g.iPhrase = 0;
107191  g.aGlobal = pCsr->aMatchinfo;
107192
107193  if( pCsr->isMatchinfoOk ){
107194    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLocalMatchinfoCb, (void *)&g);
107195    pCsr->isMatchinfoOk = 0;
107196  }
107197
107198  return SQLITE_OK;
107199}
107200
107201SQLITE_PRIVATE void sqlite3Fts3Snippet2(
107202  sqlite3_context *pCtx,          /* SQLite function call context */
107203  Fts3Cursor *pCsr,               /* Cursor object */
107204  const char *zStart,             /* Snippet start text - "<b>" */
107205  const char *zEnd,               /* Snippet end text - "</b>" */
107206  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
107207  int iCol,                       /* Extract snippet from this column */
107208  int nToken                      /* Approximate number of tokens in snippet */
107209){
107210  int rc;
107211  int iPos = 0;
107212  u64 hlmask = 0;
107213  char *z = 0;
107214  int nDoc;
107215  const char *zDoc;
107216
107217  rc = fts3BestSnippet(nToken, pCsr, iCol, &iPos, &hlmask);
107218
107219  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
107220  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
107221
107222  if( rc==SQLITE_OK ){
107223    rc = fts3SnippetText(
107224        pCsr, zDoc, nDoc, nToken, iPos, hlmask, zStart, zEnd, zEllipsis, &z);
107225  }
107226  if( rc!=SQLITE_OK ){
107227    sqlite3_result_error_code(pCtx, rc);
107228  }else{
107229    sqlite3_result_text(pCtx, z, -1, sqlite3_free);
107230  }
107231}
107232
107233SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *pContext, Fts3Cursor *pCsr){
107234  int rc = fts3GetMatchinfo(pCsr);
107235  if( rc!=SQLITE_OK ){
107236    sqlite3_result_error_code(pContext, rc);
107237  }else{
107238    int n = sizeof(u32)*(2+pCsr->aMatchinfo[0]*pCsr->aMatchinfo[1]*2);
107239    sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
107240  }
107241}
107242
107243#endif
107244
107245/************** End of fts3_snippet.c ****************************************/
107246/************** Begin file rtree.c *******************************************/
107247/*
107248** 2001 September 15
107249**
107250** The author disclaims copyright to this source code.  In place of
107251** a legal notice, here is a blessing:
107252**
107253**    May you do good and not evil.
107254**    May you find forgiveness for yourself and forgive others.
107255**    May you share freely, never taking more than you give.
107256**
107257*************************************************************************
107258** This file contains code for implementations of the r-tree and r*-tree
107259** algorithms packaged as an SQLite virtual table module.
107260*/
107261
107262#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
107263
107264/*
107265** This file contains an implementation of a couple of different variants
107266** of the r-tree algorithm. See the README file for further details. The
107267** same data-structure is used for all, but the algorithms for insert and
107268** delete operations vary. The variants used are selected at compile time
107269** by defining the following symbols:
107270*/
107271
107272/* Either, both or none of the following may be set to activate
107273** r*tree variant algorithms.
107274*/
107275#define VARIANT_RSTARTREE_CHOOSESUBTREE 0
107276#define VARIANT_RSTARTREE_REINSERT      1
107277
107278/*
107279** Exactly one of the following must be set to 1.
107280*/
107281#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
107282#define VARIANT_GUTTMAN_LINEAR_SPLIT    0
107283#define VARIANT_RSTARTREE_SPLIT         1
107284
107285#define VARIANT_GUTTMAN_SPLIT \
107286        (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
107287
107288#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
107289  #define PickNext QuadraticPickNext
107290  #define PickSeeds QuadraticPickSeeds
107291  #define AssignCells splitNodeGuttman
107292#endif
107293#if VARIANT_GUTTMAN_LINEAR_SPLIT
107294  #define PickNext LinearPickNext
107295  #define PickSeeds LinearPickSeeds
107296  #define AssignCells splitNodeGuttman
107297#endif
107298#if VARIANT_RSTARTREE_SPLIT
107299  #define AssignCells splitNodeStartree
107300#endif
107301
107302
107303#ifndef SQLITE_CORE
107304  SQLITE_EXTENSION_INIT1
107305#else
107306#endif
107307
107308
107309#ifndef SQLITE_AMALGAMATION
107310typedef sqlite3_int64 i64;
107311typedef unsigned char u8;
107312typedef unsigned int u32;
107313#endif
107314
107315typedef struct Rtree Rtree;
107316typedef struct RtreeCursor RtreeCursor;
107317typedef struct RtreeNode RtreeNode;
107318typedef struct RtreeCell RtreeCell;
107319typedef struct RtreeConstraint RtreeConstraint;
107320typedef union RtreeCoord RtreeCoord;
107321
107322/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
107323#define RTREE_MAX_DIMENSIONS 5
107324
107325/* Size of hash table Rtree.aHash. This hash table is not expected to
107326** ever contain very many entries, so a fixed number of buckets is
107327** used.
107328*/
107329#define HASHSIZE 128
107330
107331/*
107332** An rtree virtual-table object.
107333*/
107334struct Rtree {
107335  sqlite3_vtab base;
107336  sqlite3 *db;                /* Host database connection */
107337  int iNodeSize;              /* Size in bytes of each node in the node table */
107338  int nDim;                   /* Number of dimensions */
107339  int nBytesPerCell;          /* Bytes consumed per cell */
107340  int iDepth;                 /* Current depth of the r-tree structure */
107341  char *zDb;                  /* Name of database containing r-tree table */
107342  char *zName;                /* Name of r-tree table */
107343  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
107344  int nBusy;                  /* Current number of users of this structure */
107345
107346  /* List of nodes removed during a CondenseTree operation. List is
107347  ** linked together via the pointer normally used for hash chains -
107348  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
107349  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
107350  */
107351  RtreeNode *pDeleted;
107352  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
107353
107354  /* Statements to read/write/delete a record from xxx_node */
107355  sqlite3_stmt *pReadNode;
107356  sqlite3_stmt *pWriteNode;
107357  sqlite3_stmt *pDeleteNode;
107358
107359  /* Statements to read/write/delete a record from xxx_rowid */
107360  sqlite3_stmt *pReadRowid;
107361  sqlite3_stmt *pWriteRowid;
107362  sqlite3_stmt *pDeleteRowid;
107363
107364  /* Statements to read/write/delete a record from xxx_parent */
107365  sqlite3_stmt *pReadParent;
107366  sqlite3_stmt *pWriteParent;
107367  sqlite3_stmt *pDeleteParent;
107368
107369  int eCoordType;
107370};
107371
107372/* Possible values for eCoordType: */
107373#define RTREE_COORD_REAL32 0
107374#define RTREE_COORD_INT32  1
107375
107376/*
107377** The minimum number of cells allowed for a node is a third of the
107378** maximum. In Gutman's notation:
107379**
107380**     m = M/3
107381**
107382** If an R*-tree "Reinsert" operation is required, the same number of
107383** cells are removed from the overfull node and reinserted into the tree.
107384*/
107385#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
107386#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
107387#define RTREE_MAXCELLS 51
107388
107389/*
107390** An rtree cursor object.
107391*/
107392struct RtreeCursor {
107393  sqlite3_vtab_cursor base;
107394  RtreeNode *pNode;                 /* Node cursor is currently pointing at */
107395  int iCell;                        /* Index of current cell in pNode */
107396  int iStrategy;                    /* Copy of idxNum search parameter */
107397  int nConstraint;                  /* Number of entries in aConstraint */
107398  RtreeConstraint *aConstraint;     /* Search constraints. */
107399};
107400
107401union RtreeCoord {
107402  float f;
107403  int i;
107404};
107405
107406/*
107407** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
107408** formatted as a double. This macro assumes that local variable pRtree points
107409** to the Rtree structure associated with the RtreeCoord.
107410*/
107411#define DCOORD(coord) (                           \
107412  (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
107413    ((double)coord.f) :                           \
107414    ((double)coord.i)                             \
107415)
107416
107417/*
107418** A search constraint.
107419*/
107420struct RtreeConstraint {
107421  int iCoord;                       /* Index of constrained coordinate */
107422  int op;                           /* Constraining operation */
107423  double rValue;                    /* Constraint value. */
107424};
107425
107426/* Possible values for RtreeConstraint.op */
107427#define RTREE_EQ 0x41
107428#define RTREE_LE 0x42
107429#define RTREE_LT 0x43
107430#define RTREE_GE 0x44
107431#define RTREE_GT 0x45
107432
107433/*
107434** An rtree structure node.
107435**
107436** Data format (RtreeNode.zData):
107437**
107438**   1. If the node is the root node (node 1), then the first 2 bytes
107439**      of the node contain the tree depth as a big-endian integer.
107440**      For non-root nodes, the first 2 bytes are left unused.
107441**
107442**   2. The next 2 bytes contain the number of entries currently
107443**      stored in the node.
107444**
107445**   3. The remainder of the node contains the node entries. Each entry
107446**      consists of a single 8-byte integer followed by an even number
107447**      of 4-byte coordinates. For leaf nodes the integer is the rowid
107448**      of a record. For internal nodes it is the node number of a
107449**      child page.
107450*/
107451struct RtreeNode {
107452  RtreeNode *pParent;               /* Parent node */
107453  i64 iNode;
107454  int nRef;
107455  int isDirty;
107456  u8 *zData;
107457  RtreeNode *pNext;                 /* Next node in this hash chain */
107458};
107459#define NCELL(pNode) readInt16(&(pNode)->zData[2])
107460
107461/*
107462** Structure to store a deserialized rtree record.
107463*/
107464struct RtreeCell {
107465  i64 iRowid;
107466  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
107467};
107468
107469#ifndef MAX
107470# define MAX(x,y) ((x) < (y) ? (y) : (x))
107471#endif
107472#ifndef MIN
107473# define MIN(x,y) ((x) > (y) ? (y) : (x))
107474#endif
107475
107476/*
107477** Functions to deserialize a 16 bit integer, 32 bit real number and
107478** 64 bit integer. The deserialized value is returned.
107479*/
107480static int readInt16(u8 *p){
107481  return (p[0]<<8) + p[1];
107482}
107483static void readCoord(u8 *p, RtreeCoord *pCoord){
107484  u32 i = (
107485    (((u32)p[0]) << 24) +
107486    (((u32)p[1]) << 16) +
107487    (((u32)p[2]) <<  8) +
107488    (((u32)p[3]) <<  0)
107489  );
107490  *(u32 *)pCoord = i;
107491}
107492static i64 readInt64(u8 *p){
107493  return (
107494    (((i64)p[0]) << 56) +
107495    (((i64)p[1]) << 48) +
107496    (((i64)p[2]) << 40) +
107497    (((i64)p[3]) << 32) +
107498    (((i64)p[4]) << 24) +
107499    (((i64)p[5]) << 16) +
107500    (((i64)p[6]) <<  8) +
107501    (((i64)p[7]) <<  0)
107502  );
107503}
107504
107505/*
107506** Functions to serialize a 16 bit integer, 32 bit real number and
107507** 64 bit integer. The value returned is the number of bytes written
107508** to the argument buffer (always 2, 4 and 8 respectively).
107509*/
107510static int writeInt16(u8 *p, int i){
107511  p[0] = (i>> 8)&0xFF;
107512  p[1] = (i>> 0)&0xFF;
107513  return 2;
107514}
107515static int writeCoord(u8 *p, RtreeCoord *pCoord){
107516  u32 i;
107517  assert( sizeof(RtreeCoord)==4 );
107518  assert( sizeof(u32)==4 );
107519  i = *(u32 *)pCoord;
107520  p[0] = (i>>24)&0xFF;
107521  p[1] = (i>>16)&0xFF;
107522  p[2] = (i>> 8)&0xFF;
107523  p[3] = (i>> 0)&0xFF;
107524  return 4;
107525}
107526static int writeInt64(u8 *p, i64 i){
107527  p[0] = (i>>56)&0xFF;
107528  p[1] = (i>>48)&0xFF;
107529  p[2] = (i>>40)&0xFF;
107530  p[3] = (i>>32)&0xFF;
107531  p[4] = (i>>24)&0xFF;
107532  p[5] = (i>>16)&0xFF;
107533  p[6] = (i>> 8)&0xFF;
107534  p[7] = (i>> 0)&0xFF;
107535  return 8;
107536}
107537
107538/*
107539** Increment the reference count of node p.
107540*/
107541static void nodeReference(RtreeNode *p){
107542  if( p ){
107543    p->nRef++;
107544  }
107545}
107546
107547/*
107548** Clear the content of node p (set all bytes to 0x00).
107549*/
107550static void nodeZero(Rtree *pRtree, RtreeNode *p){
107551  if( p ){
107552    memset(&p->zData[2], 0, pRtree->iNodeSize-2);
107553    p->isDirty = 1;
107554  }
107555}
107556
107557/*
107558** Given a node number iNode, return the corresponding key to use
107559** in the Rtree.aHash table.
107560*/
107561static int nodeHash(i64 iNode){
107562  return (
107563    (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
107564    (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
107565  ) % HASHSIZE;
107566}
107567
107568/*
107569** Search the node hash table for node iNode. If found, return a pointer
107570** to it. Otherwise, return 0.
107571*/
107572static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
107573  RtreeNode *p;
107574  assert( iNode!=0 );
107575  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
107576  return p;
107577}
107578
107579/*
107580** Add node pNode to the node hash table.
107581*/
107582static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
107583  if( pNode ){
107584    int iHash;
107585    assert( pNode->pNext==0 );
107586    iHash = nodeHash(pNode->iNode);
107587    pNode->pNext = pRtree->aHash[iHash];
107588    pRtree->aHash[iHash] = pNode;
107589  }
107590}
107591
107592/*
107593** Remove node pNode from the node hash table.
107594*/
107595static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
107596  RtreeNode **pp;
107597  if( pNode->iNode!=0 ){
107598    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
107599    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
107600    *pp = pNode->pNext;
107601    pNode->pNext = 0;
107602  }
107603}
107604
107605/*
107606** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
107607** indicating that node has not yet been assigned a node number. It is
107608** assigned a node number when nodeWrite() is called to write the
107609** node contents out to the database.
107610*/
107611static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
107612  RtreeNode *pNode;
107613  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
107614  if( pNode ){
107615    memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
107616    pNode->zData = (u8 *)&pNode[1];
107617    pNode->nRef = 1;
107618    pNode->pParent = pParent;
107619    pNode->isDirty = 1;
107620    nodeReference(pParent);
107621  }
107622  return pNode;
107623}
107624
107625/*
107626** Obtain a reference to an r-tree node.
107627*/
107628static int
107629nodeAcquire(
107630  Rtree *pRtree,             /* R-tree structure */
107631  i64 iNode,                 /* Node number to load */
107632  RtreeNode *pParent,        /* Either the parent node or NULL */
107633  RtreeNode **ppNode         /* OUT: Acquired node */
107634){
107635  int rc;
107636  RtreeNode *pNode;
107637
107638  /* Check if the requested node is already in the hash table. If so,
107639  ** increase its reference count and return it.
107640  */
107641  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
107642    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
107643    if( pParent && !pNode->pParent ){
107644      nodeReference(pParent);
107645      pNode->pParent = pParent;
107646    }
107647    pNode->nRef++;
107648    *ppNode = pNode;
107649    return SQLITE_OK;
107650  }
107651
107652  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
107653  if( !pNode ){
107654    *ppNode = 0;
107655    return SQLITE_NOMEM;
107656  }
107657  pNode->pParent = pParent;
107658  pNode->zData = (u8 *)&pNode[1];
107659  pNode->nRef = 1;
107660  pNode->iNode = iNode;
107661  pNode->isDirty = 0;
107662  pNode->pNext = 0;
107663
107664  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
107665  rc = sqlite3_step(pRtree->pReadNode);
107666  if( rc==SQLITE_ROW ){
107667    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
107668    memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
107669    nodeReference(pParent);
107670  }else{
107671    sqlite3_free(pNode);
107672    pNode = 0;
107673  }
107674
107675  *ppNode = pNode;
107676  rc = sqlite3_reset(pRtree->pReadNode);
107677
107678  if( rc==SQLITE_OK && iNode==1 ){
107679    pRtree->iDepth = readInt16(pNode->zData);
107680  }
107681
107682  assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
107683  nodeHashInsert(pRtree, pNode);
107684
107685  return rc;
107686}
107687
107688/*
107689** Overwrite cell iCell of node pNode with the contents of pCell.
107690*/
107691static void nodeOverwriteCell(
107692  Rtree *pRtree,
107693  RtreeNode *pNode,
107694  RtreeCell *pCell,
107695  int iCell
107696){
107697  int ii;
107698  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
107699  p += writeInt64(p, pCell->iRowid);
107700  for(ii=0; ii<(pRtree->nDim*2); ii++){
107701    p += writeCoord(p, &pCell->aCoord[ii]);
107702  }
107703  pNode->isDirty = 1;
107704}
107705
107706/*
107707** Remove cell the cell with index iCell from node pNode.
107708*/
107709static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
107710  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
107711  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
107712  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
107713  memmove(pDst, pSrc, nByte);
107714  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
107715  pNode->isDirty = 1;
107716}
107717
107718/*
107719** Insert the contents of cell pCell into node pNode. If the insert
107720** is successful, return SQLITE_OK.
107721**
107722** If there is not enough free space in pNode, return SQLITE_FULL.
107723*/
107724static int
107725nodeInsertCell(
107726  Rtree *pRtree,
107727  RtreeNode *pNode,
107728  RtreeCell *pCell
107729){
107730  int nCell;                    /* Current number of cells in pNode */
107731  int nMaxCell;                 /* Maximum number of cells for pNode */
107732
107733  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
107734  nCell = NCELL(pNode);
107735
107736  assert(nCell<=nMaxCell);
107737
107738  if( nCell<nMaxCell ){
107739    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
107740    writeInt16(&pNode->zData[2], nCell+1);
107741    pNode->isDirty = 1;
107742  }
107743
107744  return (nCell==nMaxCell);
107745}
107746
107747/*
107748** If the node is dirty, write it out to the database.
107749*/
107750static int
107751nodeWrite(Rtree *pRtree, RtreeNode *pNode){
107752  int rc = SQLITE_OK;
107753  if( pNode->isDirty ){
107754    sqlite3_stmt *p = pRtree->pWriteNode;
107755    if( pNode->iNode ){
107756      sqlite3_bind_int64(p, 1, pNode->iNode);
107757    }else{
107758      sqlite3_bind_null(p, 1);
107759    }
107760    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
107761    sqlite3_step(p);
107762    pNode->isDirty = 0;
107763    rc = sqlite3_reset(p);
107764    if( pNode->iNode==0 && rc==SQLITE_OK ){
107765      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
107766      nodeHashInsert(pRtree, pNode);
107767    }
107768  }
107769  return rc;
107770}
107771
107772/*
107773** Release a reference to a node. If the node is dirty and the reference
107774** count drops to zero, the node data is written to the database.
107775*/
107776static int
107777nodeRelease(Rtree *pRtree, RtreeNode *pNode){
107778  int rc = SQLITE_OK;
107779  if( pNode ){
107780    assert( pNode->nRef>0 );
107781    pNode->nRef--;
107782    if( pNode->nRef==0 ){
107783      if( pNode->iNode==1 ){
107784        pRtree->iDepth = -1;
107785      }
107786      if( pNode->pParent ){
107787        rc = nodeRelease(pRtree, pNode->pParent);
107788      }
107789      if( rc==SQLITE_OK ){
107790        rc = nodeWrite(pRtree, pNode);
107791      }
107792      nodeHashDelete(pRtree, pNode);
107793      sqlite3_free(pNode);
107794    }
107795  }
107796  return rc;
107797}
107798
107799/*
107800** Return the 64-bit integer value associated with cell iCell of
107801** node pNode. If pNode is a leaf node, this is a rowid. If it is
107802** an internal node, then the 64-bit integer is a child page number.
107803*/
107804static i64 nodeGetRowid(
107805  Rtree *pRtree,
107806  RtreeNode *pNode,
107807  int iCell
107808){
107809  assert( iCell<NCELL(pNode) );
107810  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
107811}
107812
107813/*
107814** Return coordinate iCoord from cell iCell in node pNode.
107815*/
107816static void nodeGetCoord(
107817  Rtree *pRtree,
107818  RtreeNode *pNode,
107819  int iCell,
107820  int iCoord,
107821  RtreeCoord *pCoord           /* Space to write result to */
107822){
107823  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
107824}
107825
107826/*
107827** Deserialize cell iCell of node pNode. Populate the structure pointed
107828** to by pCell with the results.
107829*/
107830static void nodeGetCell(
107831  Rtree *pRtree,
107832  RtreeNode *pNode,
107833  int iCell,
107834  RtreeCell *pCell
107835){
107836  int ii;
107837  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
107838  for(ii=0; ii<pRtree->nDim*2; ii++){
107839    nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
107840  }
107841}
107842
107843
107844/* Forward declaration for the function that does the work of
107845** the virtual table module xCreate() and xConnect() methods.
107846*/
107847static int rtreeInit(
107848  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
107849);
107850
107851/*
107852** Rtree virtual table module xCreate method.
107853*/
107854static int rtreeCreate(
107855  sqlite3 *db,
107856  void *pAux,
107857  int argc, const char *const*argv,
107858  sqlite3_vtab **ppVtab,
107859  char **pzErr
107860){
107861  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
107862}
107863
107864/*
107865** Rtree virtual table module xConnect method.
107866*/
107867static int rtreeConnect(
107868  sqlite3 *db,
107869  void *pAux,
107870  int argc, const char *const*argv,
107871  sqlite3_vtab **ppVtab,
107872  char **pzErr
107873){
107874  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
107875}
107876
107877/*
107878** Increment the r-tree reference count.
107879*/
107880static void rtreeReference(Rtree *pRtree){
107881  pRtree->nBusy++;
107882}
107883
107884/*
107885** Decrement the r-tree reference count. When the reference count reaches
107886** zero the structure is deleted.
107887*/
107888static void rtreeRelease(Rtree *pRtree){
107889  pRtree->nBusy--;
107890  if( pRtree->nBusy==0 ){
107891    sqlite3_finalize(pRtree->pReadNode);
107892    sqlite3_finalize(pRtree->pWriteNode);
107893    sqlite3_finalize(pRtree->pDeleteNode);
107894    sqlite3_finalize(pRtree->pReadRowid);
107895    sqlite3_finalize(pRtree->pWriteRowid);
107896    sqlite3_finalize(pRtree->pDeleteRowid);
107897    sqlite3_finalize(pRtree->pReadParent);
107898    sqlite3_finalize(pRtree->pWriteParent);
107899    sqlite3_finalize(pRtree->pDeleteParent);
107900    sqlite3_free(pRtree);
107901  }
107902}
107903
107904/*
107905** Rtree virtual table module xDisconnect method.
107906*/
107907static int rtreeDisconnect(sqlite3_vtab *pVtab){
107908  rtreeRelease((Rtree *)pVtab);
107909  return SQLITE_OK;
107910}
107911
107912/*
107913** Rtree virtual table module xDestroy method.
107914*/
107915static int rtreeDestroy(sqlite3_vtab *pVtab){
107916  Rtree *pRtree = (Rtree *)pVtab;
107917  int rc;
107918  char *zCreate = sqlite3_mprintf(
107919    "DROP TABLE '%q'.'%q_node';"
107920    "DROP TABLE '%q'.'%q_rowid';"
107921    "DROP TABLE '%q'.'%q_parent';",
107922    pRtree->zDb, pRtree->zName,
107923    pRtree->zDb, pRtree->zName,
107924    pRtree->zDb, pRtree->zName
107925  );
107926  if( !zCreate ){
107927    rc = SQLITE_NOMEM;
107928  }else{
107929    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
107930    sqlite3_free(zCreate);
107931  }
107932  if( rc==SQLITE_OK ){
107933    rtreeRelease(pRtree);
107934  }
107935
107936  return rc;
107937}
107938
107939/*
107940** Rtree virtual table module xOpen method.
107941*/
107942static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
107943  int rc = SQLITE_NOMEM;
107944  RtreeCursor *pCsr;
107945
107946  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
107947  if( pCsr ){
107948    memset(pCsr, 0, sizeof(RtreeCursor));
107949    pCsr->base.pVtab = pVTab;
107950    rc = SQLITE_OK;
107951  }
107952  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
107953
107954  return rc;
107955}
107956
107957/*
107958** Rtree virtual table module xClose method.
107959*/
107960static int rtreeClose(sqlite3_vtab_cursor *cur){
107961  Rtree *pRtree = (Rtree *)(cur->pVtab);
107962  int rc;
107963  RtreeCursor *pCsr = (RtreeCursor *)cur;
107964  sqlite3_free(pCsr->aConstraint);
107965  rc = nodeRelease(pRtree, pCsr->pNode);
107966  sqlite3_free(pCsr);
107967  return rc;
107968}
107969
107970/*
107971** Rtree virtual table module xEof method.
107972**
107973** Return non-zero if the cursor does not currently point to a valid
107974** record (i.e if the scan has finished), or zero otherwise.
107975*/
107976static int rtreeEof(sqlite3_vtab_cursor *cur){
107977  RtreeCursor *pCsr = (RtreeCursor *)cur;
107978  return (pCsr->pNode==0);
107979}
107980
107981/*
107982** Cursor pCursor currently points to a cell in a non-leaf page.
107983** Return true if the sub-tree headed by the cell is filtered
107984** (excluded) by the constraints in the pCursor->aConstraint[]
107985** array, or false otherwise.
107986*/
107987static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
107988  RtreeCell cell;
107989  int ii;
107990  int bRes = 0;
107991
107992  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
107993  for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
107994    RtreeConstraint *p = &pCursor->aConstraint[ii];
107995    double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
107996    double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
107997
107998    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
107999        || p->op==RTREE_GT || p->op==RTREE_EQ
108000    );
108001
108002    switch( p->op ){
108003      case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
108004      case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
108005      case RTREE_EQ:
108006        bRes = (p->rValue>cell_max || p->rValue<cell_min);
108007        break;
108008    }
108009  }
108010
108011  return bRes;
108012}
108013
108014/*
108015** Return true if the cell that cursor pCursor currently points to
108016** would be filtered (excluded) by the constraints in the
108017** pCursor->aConstraint[] array, or false otherwise.
108018**
108019** This function assumes that the cell is part of a leaf node.
108020*/
108021static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
108022  RtreeCell cell;
108023  int ii;
108024
108025  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
108026  for(ii=0; ii<pCursor->nConstraint; ii++){
108027    RtreeConstraint *p = &pCursor->aConstraint[ii];
108028    double coord = DCOORD(cell.aCoord[p->iCoord]);
108029    int res;
108030    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
108031        || p->op==RTREE_GT || p->op==RTREE_EQ
108032    );
108033    switch( p->op ){
108034      case RTREE_LE: res = (coord<=p->rValue); break;
108035      case RTREE_LT: res = (coord<p->rValue);  break;
108036      case RTREE_GE: res = (coord>=p->rValue); break;
108037      case RTREE_GT: res = (coord>p->rValue);  break;
108038      case RTREE_EQ: res = (coord==p->rValue); break;
108039    }
108040
108041    if( !res ) return 1;
108042  }
108043
108044  return 0;
108045}
108046
108047/*
108048** Cursor pCursor currently points at a node that heads a sub-tree of
108049** height iHeight (if iHeight==0, then the node is a leaf). Descend
108050** to point to the left-most cell of the sub-tree that matches the
108051** configured constraints.
108052*/
108053static int descendToCell(
108054  Rtree *pRtree,
108055  RtreeCursor *pCursor,
108056  int iHeight,
108057  int *pEof                 /* OUT: Set to true if cannot descend */
108058){
108059  int isEof;
108060  int rc;
108061  int ii;
108062  RtreeNode *pChild;
108063  sqlite3_int64 iRowid;
108064
108065  RtreeNode *pSavedNode = pCursor->pNode;
108066  int iSavedCell = pCursor->iCell;
108067
108068  assert( iHeight>=0 );
108069
108070  if( iHeight==0 ){
108071    isEof = testRtreeEntry(pRtree, pCursor);
108072  }else{
108073    isEof = testRtreeCell(pRtree, pCursor);
108074  }
108075  if( isEof || iHeight==0 ){
108076    *pEof = isEof;
108077    return SQLITE_OK;
108078  }
108079
108080  iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
108081  rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
108082  if( rc!=SQLITE_OK ){
108083    return rc;
108084  }
108085
108086  nodeRelease(pRtree, pCursor->pNode);
108087  pCursor->pNode = pChild;
108088  isEof = 1;
108089  for(ii=0; isEof && ii<NCELL(pChild); ii++){
108090    pCursor->iCell = ii;
108091    rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
108092    if( rc!=SQLITE_OK ){
108093      return rc;
108094    }
108095  }
108096
108097  if( isEof ){
108098    assert( pCursor->pNode==pChild );
108099    nodeReference(pSavedNode);
108100    nodeRelease(pRtree, pChild);
108101    pCursor->pNode = pSavedNode;
108102    pCursor->iCell = iSavedCell;
108103  }
108104
108105  *pEof = isEof;
108106  return SQLITE_OK;
108107}
108108
108109/*
108110** One of the cells in node pNode is guaranteed to have a 64-bit
108111** integer value equal to iRowid. Return the index of this cell.
108112*/
108113static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
108114  int ii;
108115  for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
108116    assert( ii<(NCELL(pNode)-1) );
108117  }
108118  return ii;
108119}
108120
108121/*
108122** Return the index of the cell containing a pointer to node pNode
108123** in its parent. If pNode is the root node, return -1.
108124*/
108125static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
108126  RtreeNode *pParent = pNode->pParent;
108127  if( pParent ){
108128    return nodeRowidIndex(pRtree, pParent, pNode->iNode);
108129  }
108130  return -1;
108131}
108132
108133/*
108134** Rtree virtual table module xNext method.
108135*/
108136static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
108137  Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
108138  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108139  int rc = SQLITE_OK;
108140
108141  if( pCsr->iStrategy==1 ){
108142    /* This "scan" is a direct lookup by rowid. There is no next entry. */
108143    nodeRelease(pRtree, pCsr->pNode);
108144    pCsr->pNode = 0;
108145  }
108146
108147  else if( pCsr->pNode ){
108148    /* Move to the next entry that matches the configured constraints. */
108149    int iHeight = 0;
108150    while( pCsr->pNode ){
108151      RtreeNode *pNode = pCsr->pNode;
108152      int nCell = NCELL(pNode);
108153      for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
108154        int isEof;
108155        rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
108156        if( rc!=SQLITE_OK || !isEof ){
108157          return rc;
108158        }
108159      }
108160      pCsr->pNode = pNode->pParent;
108161      pCsr->iCell = nodeParentIndex(pRtree, pNode);
108162      nodeReference(pCsr->pNode);
108163      nodeRelease(pRtree, pNode);
108164      iHeight++;
108165    }
108166  }
108167
108168  return rc;
108169}
108170
108171/*
108172** Rtree virtual table module xRowid method.
108173*/
108174static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
108175  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
108176  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108177
108178  assert(pCsr->pNode);
108179  *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
108180
108181  return SQLITE_OK;
108182}
108183
108184/*
108185** Rtree virtual table module xColumn method.
108186*/
108187static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
108188  Rtree *pRtree = (Rtree *)cur->pVtab;
108189  RtreeCursor *pCsr = (RtreeCursor *)cur;
108190
108191  if( i==0 ){
108192    i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
108193    sqlite3_result_int64(ctx, iRowid);
108194  }else{
108195    RtreeCoord c;
108196    nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
108197    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
108198      sqlite3_result_double(ctx, c.f);
108199    }else{
108200      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
108201      sqlite3_result_int(ctx, c.i);
108202    }
108203  }
108204
108205  return SQLITE_OK;
108206}
108207
108208/*
108209** Use nodeAcquire() to obtain the leaf node containing the record with
108210** rowid iRowid. If successful, set *ppLeaf to point to the node and
108211** return SQLITE_OK. If there is no such record in the table, set
108212** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
108213** to zero and return an SQLite error code.
108214*/
108215static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
108216  int rc;
108217  *ppLeaf = 0;
108218  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
108219  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
108220    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
108221    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
108222    sqlite3_reset(pRtree->pReadRowid);
108223  }else{
108224    rc = sqlite3_reset(pRtree->pReadRowid);
108225  }
108226  return rc;
108227}
108228
108229
108230/*
108231** Rtree virtual table module xFilter method.
108232*/
108233static int rtreeFilter(
108234  sqlite3_vtab_cursor *pVtabCursor,
108235  int idxNum, const char *idxStr,
108236  int argc, sqlite3_value **argv
108237){
108238  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
108239  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
108240
108241  RtreeNode *pRoot = 0;
108242  int ii;
108243  int rc = SQLITE_OK;
108244
108245  rtreeReference(pRtree);
108246
108247  sqlite3_free(pCsr->aConstraint);
108248  pCsr->aConstraint = 0;
108249  pCsr->iStrategy = idxNum;
108250
108251  if( idxNum==1 ){
108252    /* Special case - lookup by rowid. */
108253    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
108254    i64 iRowid = sqlite3_value_int64(argv[0]);
108255    rc = findLeafNode(pRtree, iRowid, &pLeaf);
108256    pCsr->pNode = pLeaf;
108257    if( pLeaf && rc==SQLITE_OK ){
108258      pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
108259    }
108260  }else{
108261    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
108262    ** with the configured constraints.
108263    */
108264    if( argc>0 ){
108265      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
108266      pCsr->nConstraint = argc;
108267      if( !pCsr->aConstraint ){
108268        rc = SQLITE_NOMEM;
108269      }else{
108270        assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
108271        for(ii=0; ii<argc; ii++){
108272          RtreeConstraint *p = &pCsr->aConstraint[ii];
108273          p->op = idxStr[ii*2];
108274          p->iCoord = idxStr[ii*2+1]-'a';
108275          p->rValue = sqlite3_value_double(argv[ii]);
108276        }
108277      }
108278    }
108279
108280    if( rc==SQLITE_OK ){
108281      pCsr->pNode = 0;
108282      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
108283    }
108284    if( rc==SQLITE_OK ){
108285      int isEof = 1;
108286      int nCell = NCELL(pRoot);
108287      pCsr->pNode = pRoot;
108288      for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
108289        assert( pCsr->pNode==pRoot );
108290        rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
108291        if( !isEof ){
108292          break;
108293        }
108294      }
108295      if( rc==SQLITE_OK && isEof ){
108296        assert( pCsr->pNode==pRoot );
108297        nodeRelease(pRtree, pRoot);
108298        pCsr->pNode = 0;
108299      }
108300      assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
108301    }
108302  }
108303
108304  rtreeRelease(pRtree);
108305  return rc;
108306}
108307
108308/*
108309** Rtree virtual table module xBestIndex method. There are three
108310** table scan strategies to choose from (in order from most to
108311** least desirable):
108312**
108313**   idxNum     idxStr        Strategy
108314**   ------------------------------------------------
108315**     1        Unused        Direct lookup by rowid.
108316**     2        See below     R-tree query.
108317**     3        Unused        Full table scan.
108318**   ------------------------------------------------
108319**
108320** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
108321** 2 is used, idxStr is formatted to contain 2 bytes for each
108322** constraint used. The first two bytes of idxStr correspond to
108323** the constraint in sqlite3_index_info.aConstraintUsage[] with
108324** (argvIndex==1) etc.
108325**
108326** The first of each pair of bytes in idxStr identifies the constraint
108327** operator as follows:
108328**
108329**   Operator    Byte Value
108330**   ----------------------
108331**      =        0x41 ('A')
108332**     <=        0x42 ('B')
108333**      <        0x43 ('C')
108334**     >=        0x44 ('D')
108335**      >        0x45 ('E')
108336**   ----------------------
108337**
108338** The second of each pair of bytes identifies the coordinate column
108339** to which the constraint applies. The leftmost coordinate column
108340** is 'a', the second from the left 'b' etc.
108341*/
108342static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
108343  int rc = SQLITE_OK;
108344  int ii, cCol;
108345
108346  int iIdx = 0;
108347  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
108348  memset(zIdxStr, 0, sizeof(zIdxStr));
108349
108350  assert( pIdxInfo->idxStr==0 );
108351  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
108352    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
108353
108354    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
108355      /* We have an equality constraint on the rowid. Use strategy 1. */
108356      int jj;
108357      for(jj=0; jj<ii; jj++){
108358        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
108359        pIdxInfo->aConstraintUsage[jj].omit = 0;
108360      }
108361      pIdxInfo->idxNum = 1;
108362      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
108363      pIdxInfo->aConstraintUsage[jj].omit = 1;
108364
108365      /* This strategy involves a two rowid lookups on an B-Tree structures
108366      ** and then a linear search of an R-Tree node. This should be
108367      ** considered almost as quick as a direct rowid lookup (for which
108368      ** sqlite uses an internal cost of 0.0).
108369      */
108370      pIdxInfo->estimatedCost = 10.0;
108371      return SQLITE_OK;
108372    }
108373
108374    if( p->usable && p->iColumn>0 ){
108375      u8 op = 0;
108376      switch( p->op ){
108377        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
108378        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
108379        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
108380        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
108381        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
108382      }
108383      if( op ){
108384        /* Make sure this particular constraint has not been used before.
108385        ** If it has been used before, ignore it.
108386        **
108387        ** A <= or < can be used if there is a prior >= or >.
108388        ** A >= or > can be used if there is a prior < or <=.
108389        ** A <= or < is disqualified if there is a prior <=, <, or ==.
108390        ** A >= or > is disqualified if there is a prior >=, >, or ==.
108391        ** A == is disqualifed if there is any prior constraint.
108392        */
108393        int j, opmsk;
108394        static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
108395        assert( compatible[RTREE_EQ & 7]==0 );
108396        assert( compatible[RTREE_LT & 7]==1 );
108397        assert( compatible[RTREE_LE & 7]==1 );
108398        assert( compatible[RTREE_GT & 7]==2 );
108399        assert( compatible[RTREE_GE & 7]==2 );
108400        cCol = p->iColumn - 1 + 'a';
108401        opmsk = compatible[op & 7];
108402        for(j=0; j<iIdx; j+=2){
108403          if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
108404            op = 0;
108405            break;
108406          }
108407        }
108408      }
108409      if( op ){
108410        assert( iIdx<sizeof(zIdxStr)-1 );
108411        zIdxStr[iIdx++] = op;
108412        zIdxStr[iIdx++] = cCol;
108413        pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
108414        pIdxInfo->aConstraintUsage[ii].omit = 1;
108415      }
108416    }
108417  }
108418
108419  pIdxInfo->idxNum = 2;
108420  pIdxInfo->needToFreeIdxStr = 1;
108421  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
108422    return SQLITE_NOMEM;
108423  }
108424  assert( iIdx>=0 );
108425  pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
108426  return rc;
108427}
108428
108429/*
108430** Return the N-dimensional volumn of the cell stored in *p.
108431*/
108432static float cellArea(Rtree *pRtree, RtreeCell *p){
108433  float area = 1.0;
108434  int ii;
108435  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108436    area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
108437  }
108438  return area;
108439}
108440
108441/*
108442** Return the margin length of cell p. The margin length is the sum
108443** of the objects size in each dimension.
108444*/
108445static float cellMargin(Rtree *pRtree, RtreeCell *p){
108446  float margin = 0.0;
108447  int ii;
108448  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108449    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
108450  }
108451  return margin;
108452}
108453
108454/*
108455** Store the union of cells p1 and p2 in p1.
108456*/
108457static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
108458  int ii;
108459  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
108460    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108461      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
108462      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
108463    }
108464  }else{
108465    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108466      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
108467      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
108468    }
108469  }
108470}
108471
108472/*
108473** Return true if the area covered by p2 is a subset of the area covered
108474** by p1. False otherwise.
108475*/
108476static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
108477  int ii;
108478  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
108479  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
108480    RtreeCoord *a1 = &p1->aCoord[ii];
108481    RtreeCoord *a2 = &p2->aCoord[ii];
108482    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
108483     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
108484    ){
108485      return 0;
108486    }
108487  }
108488  return 1;
108489}
108490
108491/*
108492** Return the amount cell p would grow by if it were unioned with pCell.
108493*/
108494static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
108495  float area;
108496  RtreeCell cell;
108497  memcpy(&cell, p, sizeof(RtreeCell));
108498  area = cellArea(pRtree, &cell);
108499  cellUnion(pRtree, &cell, pCell);
108500  return (cellArea(pRtree, &cell)-area);
108501}
108502
108503#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
108504static float cellOverlap(
108505  Rtree *pRtree,
108506  RtreeCell *p,
108507  RtreeCell *aCell,
108508  int nCell,
108509  int iExclude
108510){
108511  int ii;
108512  float overlap = 0.0;
108513  for(ii=0; ii<nCell; ii++){
108514    if( ii!=iExclude ){
108515      int jj;
108516      float o = 1.0;
108517      for(jj=0; jj<(pRtree->nDim*2); jj+=2){
108518        double x1;
108519        double x2;
108520
108521        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
108522        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
108523
108524        if( x2<x1 ){
108525          o = 0.0;
108526          break;
108527        }else{
108528          o = o * (x2-x1);
108529        }
108530      }
108531      overlap += o;
108532    }
108533  }
108534  return overlap;
108535}
108536#endif
108537
108538#if VARIANT_RSTARTREE_CHOOSESUBTREE
108539static float cellOverlapEnlargement(
108540  Rtree *pRtree,
108541  RtreeCell *p,
108542  RtreeCell *pInsert,
108543  RtreeCell *aCell,
108544  int nCell,
108545  int iExclude
108546){
108547  float before;
108548  float after;
108549  before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
108550  cellUnion(pRtree, p, pInsert);
108551  after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
108552  return after-before;
108553}
108554#endif
108555
108556
108557/*
108558** This function implements the ChooseLeaf algorithm from Gutman[84].
108559** ChooseSubTree in r*tree terminology.
108560*/
108561static int ChooseLeaf(
108562  Rtree *pRtree,               /* Rtree table */
108563  RtreeCell *pCell,            /* Cell to insert into rtree */
108564  int iHeight,                 /* Height of sub-tree rooted at pCell */
108565  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
108566){
108567  int rc;
108568  int ii;
108569  RtreeNode *pNode;
108570  rc = nodeAcquire(pRtree, 1, 0, &pNode);
108571
108572  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
108573    int iCell;
108574    sqlite3_int64 iBest;
108575
108576    float fMinGrowth;
108577    float fMinArea;
108578    float fMinOverlap;
108579
108580    int nCell = NCELL(pNode);
108581    RtreeCell cell;
108582    RtreeNode *pChild;
108583
108584    RtreeCell *aCell = 0;
108585
108586#if VARIANT_RSTARTREE_CHOOSESUBTREE
108587    if( ii==(pRtree->iDepth-1) ){
108588      int jj;
108589      aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
108590      if( !aCell ){
108591        rc = SQLITE_NOMEM;
108592        nodeRelease(pRtree, pNode);
108593        pNode = 0;
108594        continue;
108595      }
108596      for(jj=0; jj<nCell; jj++){
108597        nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
108598      }
108599    }
108600#endif
108601
108602    /* Select the child node which will be enlarged the least if pCell
108603    ** is inserted into it. Resolve ties by choosing the entry with
108604    ** the smallest area.
108605    */
108606    for(iCell=0; iCell<nCell; iCell++){
108607      float growth;
108608      float area;
108609      float overlap = 0.0;
108610      nodeGetCell(pRtree, pNode, iCell, &cell);
108611      growth = cellGrowth(pRtree, &cell, pCell);
108612      area = cellArea(pRtree, &cell);
108613#if VARIANT_RSTARTREE_CHOOSESUBTREE
108614      if( ii==(pRtree->iDepth-1) ){
108615        overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
108616      }
108617#endif
108618      if( (iCell==0)
108619       || (overlap<fMinOverlap)
108620       || (overlap==fMinOverlap && growth<fMinGrowth)
108621       || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
108622      ){
108623        fMinOverlap = overlap;
108624        fMinGrowth = growth;
108625        fMinArea = area;
108626        iBest = cell.iRowid;
108627      }
108628    }
108629
108630    sqlite3_free(aCell);
108631    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
108632    nodeRelease(pRtree, pNode);
108633    pNode = pChild;
108634  }
108635
108636  *ppLeaf = pNode;
108637  return rc;
108638}
108639
108640/*
108641** A cell with the same content as pCell has just been inserted into
108642** the node pNode. This function updates the bounding box cells in
108643** all ancestor elements.
108644*/
108645static void AdjustTree(
108646  Rtree *pRtree,                    /* Rtree table */
108647  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
108648  RtreeCell *pCell                  /* This cell was just inserted */
108649){
108650  RtreeNode *p = pNode;
108651  while( p->pParent ){
108652    RtreeCell cell;
108653    RtreeNode *pParent = p->pParent;
108654    int iCell = nodeParentIndex(pRtree, p);
108655
108656    nodeGetCell(pRtree, pParent, iCell, &cell);
108657    if( !cellContains(pRtree, &cell, pCell) ){
108658      cellUnion(pRtree, &cell, pCell);
108659      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
108660    }
108661
108662    p = pParent;
108663  }
108664}
108665
108666/*
108667** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
108668*/
108669static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
108670  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
108671  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
108672  sqlite3_step(pRtree->pWriteRowid);
108673  return sqlite3_reset(pRtree->pWriteRowid);
108674}
108675
108676/*
108677** Write mapping (iNode->iPar) to the <rtree>_parent table.
108678*/
108679static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
108680  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
108681  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
108682  sqlite3_step(pRtree->pWriteParent);
108683  return sqlite3_reset(pRtree->pWriteParent);
108684}
108685
108686static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
108687
108688#if VARIANT_GUTTMAN_LINEAR_SPLIT
108689/*
108690** Implementation of the linear variant of the PickNext() function from
108691** Guttman[84].
108692*/
108693static RtreeCell *LinearPickNext(
108694  Rtree *pRtree,
108695  RtreeCell *aCell,
108696  int nCell,
108697  RtreeCell *pLeftBox,
108698  RtreeCell *pRightBox,
108699  int *aiUsed
108700){
108701  int ii;
108702  for(ii=0; aiUsed[ii]; ii++);
108703  aiUsed[ii] = 1;
108704  return &aCell[ii];
108705}
108706
108707/*
108708** Implementation of the linear variant of the PickSeeds() function from
108709** Guttman[84].
108710*/
108711static void LinearPickSeeds(
108712  Rtree *pRtree,
108713  RtreeCell *aCell,
108714  int nCell,
108715  int *piLeftSeed,
108716  int *piRightSeed
108717){
108718  int i;
108719  int iLeftSeed = 0;
108720  int iRightSeed = 1;
108721  float maxNormalInnerWidth = 0.0;
108722
108723  /* Pick two "seed" cells from the array of cells. The algorithm used
108724  ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
108725  ** indices of the two seed cells in the array are stored in local
108726  ** variables iLeftSeek and iRightSeed.
108727  */
108728  for(i=0; i<pRtree->nDim; i++){
108729    float x1 = DCOORD(aCell[0].aCoord[i*2]);
108730    float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
108731    float x3 = x1;
108732    float x4 = x2;
108733    int jj;
108734
108735    int iCellLeft = 0;
108736    int iCellRight = 0;
108737
108738    for(jj=1; jj<nCell; jj++){
108739      float left = DCOORD(aCell[jj].aCoord[i*2]);
108740      float right = DCOORD(aCell[jj].aCoord[i*2+1]);
108741
108742      if( left<x1 ) x1 = left;
108743      if( right>x4 ) x4 = right;
108744      if( left>x3 ){
108745        x3 = left;
108746        iCellRight = jj;
108747      }
108748      if( right<x2 ){
108749        x2 = right;
108750        iCellLeft = jj;
108751      }
108752    }
108753
108754    if( x4!=x1 ){
108755      float normalwidth = (x3 - x2) / (x4 - x1);
108756      if( normalwidth>maxNormalInnerWidth ){
108757        iLeftSeed = iCellLeft;
108758        iRightSeed = iCellRight;
108759      }
108760    }
108761  }
108762
108763  *piLeftSeed = iLeftSeed;
108764  *piRightSeed = iRightSeed;
108765}
108766#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
108767
108768#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
108769/*
108770** Implementation of the quadratic variant of the PickNext() function from
108771** Guttman[84].
108772*/
108773static RtreeCell *QuadraticPickNext(
108774  Rtree *pRtree,
108775  RtreeCell *aCell,
108776  int nCell,
108777  RtreeCell *pLeftBox,
108778  RtreeCell *pRightBox,
108779  int *aiUsed
108780){
108781  #define FABS(a) ((a)<0.0?-1.0*(a):(a))
108782
108783  int iSelect = -1;
108784  float fDiff;
108785  int ii;
108786  for(ii=0; ii<nCell; ii++){
108787    if( aiUsed[ii]==0 ){
108788      float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
108789      float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
108790      float diff = FABS(right-left);
108791      if( iSelect<0 || diff>fDiff ){
108792        fDiff = diff;
108793        iSelect = ii;
108794      }
108795    }
108796  }
108797  aiUsed[iSelect] = 1;
108798  return &aCell[iSelect];
108799}
108800
108801/*
108802** Implementation of the quadratic variant of the PickSeeds() function from
108803** Guttman[84].
108804*/
108805static void QuadraticPickSeeds(
108806  Rtree *pRtree,
108807  RtreeCell *aCell,
108808  int nCell,
108809  int *piLeftSeed,
108810  int *piRightSeed
108811){
108812  int ii;
108813  int jj;
108814
108815  int iLeftSeed = 0;
108816  int iRightSeed = 1;
108817  float fWaste = 0.0;
108818
108819  for(ii=0; ii<nCell; ii++){
108820    for(jj=ii+1; jj<nCell; jj++){
108821      float right = cellArea(pRtree, &aCell[jj]);
108822      float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
108823      float waste = growth - right;
108824
108825      if( waste>fWaste ){
108826        iLeftSeed = ii;
108827        iRightSeed = jj;
108828        fWaste = waste;
108829      }
108830    }
108831  }
108832
108833  *piLeftSeed = iLeftSeed;
108834  *piRightSeed = iRightSeed;
108835}
108836#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
108837
108838/*
108839** Arguments aIdx, aDistance and aSpare all point to arrays of size
108840** nIdx. The aIdx array contains the set of integers from 0 to
108841** (nIdx-1) in no particular order. This function sorts the values
108842** in aIdx according to the indexed values in aDistance. For
108843** example, assuming the inputs:
108844**
108845**   aIdx      = { 0,   1,   2,   3 }
108846**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
108847**
108848** this function sets the aIdx array to contain:
108849**
108850**   aIdx      = { 0,   1,   2,   3 }
108851**
108852** The aSpare array is used as temporary working space by the
108853** sorting algorithm.
108854*/
108855static void SortByDistance(
108856  int *aIdx,
108857  int nIdx,
108858  float *aDistance,
108859  int *aSpare
108860){
108861  if( nIdx>1 ){
108862    int iLeft = 0;
108863    int iRight = 0;
108864
108865    int nLeft = nIdx/2;
108866    int nRight = nIdx-nLeft;
108867    int *aLeft = aIdx;
108868    int *aRight = &aIdx[nLeft];
108869
108870    SortByDistance(aLeft, nLeft, aDistance, aSpare);
108871    SortByDistance(aRight, nRight, aDistance, aSpare);
108872
108873    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
108874    aLeft = aSpare;
108875
108876    while( iLeft<nLeft || iRight<nRight ){
108877      if( iLeft==nLeft ){
108878        aIdx[iLeft+iRight] = aRight[iRight];
108879        iRight++;
108880      }else if( iRight==nRight ){
108881        aIdx[iLeft+iRight] = aLeft[iLeft];
108882        iLeft++;
108883      }else{
108884        float fLeft = aDistance[aLeft[iLeft]];
108885        float fRight = aDistance[aRight[iRight]];
108886        if( fLeft<fRight ){
108887          aIdx[iLeft+iRight] = aLeft[iLeft];
108888          iLeft++;
108889        }else{
108890          aIdx[iLeft+iRight] = aRight[iRight];
108891          iRight++;
108892        }
108893      }
108894    }
108895
108896#if 0
108897    /* Check that the sort worked */
108898    {
108899      int jj;
108900      for(jj=1; jj<nIdx; jj++){
108901        float left = aDistance[aIdx[jj-1]];
108902        float right = aDistance[aIdx[jj]];
108903        assert( left<=right );
108904      }
108905    }
108906#endif
108907  }
108908}
108909
108910/*
108911** Arguments aIdx, aCell and aSpare all point to arrays of size
108912** nIdx. The aIdx array contains the set of integers from 0 to
108913** (nIdx-1) in no particular order. This function sorts the values
108914** in aIdx according to dimension iDim of the cells in aCell. The
108915** minimum value of dimension iDim is considered first, the
108916** maximum used to break ties.
108917**
108918** The aSpare array is used as temporary working space by the
108919** sorting algorithm.
108920*/
108921static void SortByDimension(
108922  Rtree *pRtree,
108923  int *aIdx,
108924  int nIdx,
108925  int iDim,
108926  RtreeCell *aCell,
108927  int *aSpare
108928){
108929  if( nIdx>1 ){
108930
108931    int iLeft = 0;
108932    int iRight = 0;
108933
108934    int nLeft = nIdx/2;
108935    int nRight = nIdx-nLeft;
108936    int *aLeft = aIdx;
108937    int *aRight = &aIdx[nLeft];
108938
108939    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
108940    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
108941
108942    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
108943    aLeft = aSpare;
108944    while( iLeft<nLeft || iRight<nRight ){
108945      double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
108946      double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
108947      double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
108948      double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
108949      if( (iLeft!=nLeft) && ((iRight==nRight)
108950       || (xleft1<xright1)
108951       || (xleft1==xright1 && xleft2<xright2)
108952      )){
108953        aIdx[iLeft+iRight] = aLeft[iLeft];
108954        iLeft++;
108955      }else{
108956        aIdx[iLeft+iRight] = aRight[iRight];
108957        iRight++;
108958      }
108959    }
108960
108961#if 0
108962    /* Check that the sort worked */
108963    {
108964      int jj;
108965      for(jj=1; jj<nIdx; jj++){
108966        float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
108967        float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
108968        float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
108969        float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
108970        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
108971      }
108972    }
108973#endif
108974  }
108975}
108976
108977#if VARIANT_RSTARTREE_SPLIT
108978/*
108979** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
108980*/
108981static int splitNodeStartree(
108982  Rtree *pRtree,
108983  RtreeCell *aCell,
108984  int nCell,
108985  RtreeNode *pLeft,
108986  RtreeNode *pRight,
108987  RtreeCell *pBboxLeft,
108988  RtreeCell *pBboxRight
108989){
108990  int **aaSorted;
108991  int *aSpare;
108992  int ii;
108993
108994  int iBestDim;
108995  int iBestSplit;
108996  float fBestMargin;
108997
108998  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
108999
109000  aaSorted = (int **)sqlite3_malloc(nByte);
109001  if( !aaSorted ){
109002    return SQLITE_NOMEM;
109003  }
109004
109005  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
109006  memset(aaSorted, 0, nByte);
109007  for(ii=0; ii<pRtree->nDim; ii++){
109008    int jj;
109009    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
109010    for(jj=0; jj<nCell; jj++){
109011      aaSorted[ii][jj] = jj;
109012    }
109013    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
109014  }
109015
109016  for(ii=0; ii<pRtree->nDim; ii++){
109017    float margin = 0.0;
109018    float fBestOverlap;
109019    float fBestArea;
109020    int iBestLeft;
109021    int nLeft;
109022
109023    for(
109024      nLeft=RTREE_MINCELLS(pRtree);
109025      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
109026      nLeft++
109027    ){
109028      RtreeCell left;
109029      RtreeCell right;
109030      int kk;
109031      float overlap;
109032      float area;
109033
109034      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
109035      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
109036      for(kk=1; kk<(nCell-1); kk++){
109037        if( kk<nLeft ){
109038          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
109039        }else{
109040          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
109041        }
109042      }
109043      margin += cellMargin(pRtree, &left);
109044      margin += cellMargin(pRtree, &right);
109045      overlap = cellOverlap(pRtree, &left, &right, 1, -1);
109046      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
109047      if( (nLeft==RTREE_MINCELLS(pRtree))
109048       || (overlap<fBestOverlap)
109049       || (overlap==fBestOverlap && area<fBestArea)
109050      ){
109051        iBestLeft = nLeft;
109052        fBestOverlap = overlap;
109053        fBestArea = area;
109054      }
109055    }
109056
109057    if( ii==0 || margin<fBestMargin ){
109058      iBestDim = ii;
109059      fBestMargin = margin;
109060      iBestSplit = iBestLeft;
109061    }
109062  }
109063
109064  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
109065  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
109066  for(ii=0; ii<nCell; ii++){
109067    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
109068    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
109069    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
109070    nodeInsertCell(pRtree, pTarget, pCell);
109071    cellUnion(pRtree, pBbox, pCell);
109072  }
109073
109074  sqlite3_free(aaSorted);
109075  return SQLITE_OK;
109076}
109077#endif
109078
109079#if VARIANT_GUTTMAN_SPLIT
109080/*
109081** Implementation of the regular R-tree SplitNode from Guttman[1984].
109082*/
109083static int splitNodeGuttman(
109084  Rtree *pRtree,
109085  RtreeCell *aCell,
109086  int nCell,
109087  RtreeNode *pLeft,
109088  RtreeNode *pRight,
109089  RtreeCell *pBboxLeft,
109090  RtreeCell *pBboxRight
109091){
109092  int iLeftSeed = 0;
109093  int iRightSeed = 1;
109094  int *aiUsed;
109095  int i;
109096
109097  aiUsed = sqlite3_malloc(sizeof(int)*nCell);
109098  if( !aiUsed ){
109099    return SQLITE_NOMEM;
109100  }
109101  memset(aiUsed, 0, sizeof(int)*nCell);
109102
109103  PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
109104
109105  memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
109106  memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
109107  nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
109108  nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
109109  aiUsed[iLeftSeed] = 1;
109110  aiUsed[iRightSeed] = 1;
109111
109112  for(i=nCell-2; i>0; i--){
109113    RtreeCell *pNext;
109114    pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
109115    float diff =
109116      cellGrowth(pRtree, pBboxLeft, pNext) -
109117      cellGrowth(pRtree, pBboxRight, pNext)
109118    ;
109119    if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
109120     || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
109121    ){
109122      nodeInsertCell(pRtree, pRight, pNext);
109123      cellUnion(pRtree, pBboxRight, pNext);
109124    }else{
109125      nodeInsertCell(pRtree, pLeft, pNext);
109126      cellUnion(pRtree, pBboxLeft, pNext);
109127    }
109128  }
109129
109130  sqlite3_free(aiUsed);
109131  return SQLITE_OK;
109132}
109133#endif
109134
109135static int updateMapping(
109136  Rtree *pRtree,
109137  i64 iRowid,
109138  RtreeNode *pNode,
109139  int iHeight
109140){
109141  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
109142  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
109143  if( iHeight>0 ){
109144    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
109145    if( pChild ){
109146      nodeRelease(pRtree, pChild->pParent);
109147      nodeReference(pNode);
109148      pChild->pParent = pNode;
109149    }
109150  }
109151  return xSetMapping(pRtree, iRowid, pNode->iNode);
109152}
109153
109154static int SplitNode(
109155  Rtree *pRtree,
109156  RtreeNode *pNode,
109157  RtreeCell *pCell,
109158  int iHeight
109159){
109160  int i;
109161  int newCellIsRight = 0;
109162
109163  int rc = SQLITE_OK;
109164  int nCell = NCELL(pNode);
109165  RtreeCell *aCell;
109166  int *aiUsed;
109167
109168  RtreeNode *pLeft = 0;
109169  RtreeNode *pRight = 0;
109170
109171  RtreeCell leftbbox;
109172  RtreeCell rightbbox;
109173
109174  /* Allocate an array and populate it with a copy of pCell and
109175  ** all cells from node pLeft. Then zero the original node.
109176  */
109177  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
109178  if( !aCell ){
109179    rc = SQLITE_NOMEM;
109180    goto splitnode_out;
109181  }
109182  aiUsed = (int *)&aCell[nCell+1];
109183  memset(aiUsed, 0, sizeof(int)*(nCell+1));
109184  for(i=0; i<nCell; i++){
109185    nodeGetCell(pRtree, pNode, i, &aCell[i]);
109186  }
109187  nodeZero(pRtree, pNode);
109188  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
109189  nCell++;
109190
109191  if( pNode->iNode==1 ){
109192    pRight = nodeNew(pRtree, pNode, 1);
109193    pLeft = nodeNew(pRtree, pNode, 1);
109194    pRtree->iDepth++;
109195    pNode->isDirty = 1;
109196    writeInt16(pNode->zData, pRtree->iDepth);
109197  }else{
109198    pLeft = pNode;
109199    pRight = nodeNew(pRtree, pLeft->pParent, 1);
109200    nodeReference(pLeft);
109201  }
109202
109203  if( !pLeft || !pRight ){
109204    rc = SQLITE_NOMEM;
109205    goto splitnode_out;
109206  }
109207
109208  memset(pLeft->zData, 0, pRtree->iNodeSize);
109209  memset(pRight->zData, 0, pRtree->iNodeSize);
109210
109211  rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
109212  if( rc!=SQLITE_OK ){
109213    goto splitnode_out;
109214  }
109215
109216  /* Ensure both child nodes have node numbers assigned to them. */
109217  if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
109218   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
109219  ){
109220    goto splitnode_out;
109221  }
109222
109223  rightbbox.iRowid = pRight->iNode;
109224  leftbbox.iRowid = pLeft->iNode;
109225
109226  if( pNode->iNode==1 ){
109227    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
109228    if( rc!=SQLITE_OK ){
109229      goto splitnode_out;
109230    }
109231  }else{
109232    RtreeNode *pParent = pLeft->pParent;
109233    int iCell = nodeParentIndex(pRtree, pLeft);
109234    nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
109235    AdjustTree(pRtree, pParent, &leftbbox);
109236  }
109237  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
109238    goto splitnode_out;
109239  }
109240
109241  for(i=0; i<NCELL(pRight); i++){
109242    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
109243    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
109244    if( iRowid==pCell->iRowid ){
109245      newCellIsRight = 1;
109246    }
109247    if( rc!=SQLITE_OK ){
109248      goto splitnode_out;
109249    }
109250  }
109251  if( pNode->iNode==1 ){
109252    for(i=0; i<NCELL(pLeft); i++){
109253      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
109254      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
109255      if( rc!=SQLITE_OK ){
109256        goto splitnode_out;
109257      }
109258    }
109259  }else if( newCellIsRight==0 ){
109260    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
109261  }
109262
109263  if( rc==SQLITE_OK ){
109264    rc = nodeRelease(pRtree, pRight);
109265    pRight = 0;
109266  }
109267  if( rc==SQLITE_OK ){
109268    rc = nodeRelease(pRtree, pLeft);
109269    pLeft = 0;
109270  }
109271
109272splitnode_out:
109273  nodeRelease(pRtree, pRight);
109274  nodeRelease(pRtree, pLeft);
109275  sqlite3_free(aCell);
109276  return rc;
109277}
109278
109279static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
109280  int rc = SQLITE_OK;
109281  if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
109282    sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
109283    if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
109284      i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
109285      rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
109286    }else{
109287      rc = SQLITE_ERROR;
109288    }
109289    sqlite3_reset(pRtree->pReadParent);
109290    if( rc==SQLITE_OK ){
109291      rc = fixLeafParent(pRtree, pLeaf->pParent);
109292    }
109293  }
109294  return rc;
109295}
109296
109297static int deleteCell(Rtree *, RtreeNode *, int, int);
109298
109299static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
109300  int rc;
109301  RtreeNode *pParent;
109302  int iCell;
109303
109304  assert( pNode->nRef==1 );
109305
109306  /* Remove the entry in the parent cell. */
109307  iCell = nodeParentIndex(pRtree, pNode);
109308  pParent = pNode->pParent;
109309  pNode->pParent = 0;
109310  if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1))
109311   || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
109312  ){
109313    return rc;
109314  }
109315
109316  /* Remove the xxx_node entry. */
109317  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
109318  sqlite3_step(pRtree->pDeleteNode);
109319  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
109320    return rc;
109321  }
109322
109323  /* Remove the xxx_parent entry. */
109324  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
109325  sqlite3_step(pRtree->pDeleteParent);
109326  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
109327    return rc;
109328  }
109329
109330  /* Remove the node from the in-memory hash table and link it into
109331  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
109332  */
109333  nodeHashDelete(pRtree, pNode);
109334  pNode->iNode = iHeight;
109335  pNode->pNext = pRtree->pDeleted;
109336  pNode->nRef++;
109337  pRtree->pDeleted = pNode;
109338
109339  return SQLITE_OK;
109340}
109341
109342static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
109343  RtreeNode *pParent = pNode->pParent;
109344  if( pParent ){
109345    int ii;
109346    int nCell = NCELL(pNode);
109347    RtreeCell box;                            /* Bounding box for pNode */
109348    nodeGetCell(pRtree, pNode, 0, &box);
109349    for(ii=1; ii<nCell; ii++){
109350      RtreeCell cell;
109351      nodeGetCell(pRtree, pNode, ii, &cell);
109352      cellUnion(pRtree, &box, &cell);
109353    }
109354    box.iRowid = pNode->iNode;
109355    ii = nodeParentIndex(pRtree, pNode);
109356    nodeOverwriteCell(pRtree, pParent, &box, ii);
109357    fixBoundingBox(pRtree, pParent);
109358  }
109359}
109360
109361/*
109362** Delete the cell at index iCell of node pNode. After removing the
109363** cell, adjust the r-tree data structure if required.
109364*/
109365static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
109366  int rc;
109367
109368  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
109369    return rc;
109370  }
109371
109372  /* Remove the cell from the node. This call just moves bytes around
109373  ** the in-memory node image, so it cannot fail.
109374  */
109375  nodeDeleteCell(pRtree, pNode, iCell);
109376
109377  /* If the node is not the tree root and now has less than the minimum
109378  ** number of cells, remove it from the tree. Otherwise, update the
109379  ** cell in the parent node so that it tightly contains the updated
109380  ** node.
109381  */
109382  if( pNode->iNode!=1 ){
109383    RtreeNode *pParent = pNode->pParent;
109384    if( (pParent->iNode!=1 || NCELL(pParent)!=1)
109385     && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
109386    ){
109387      rc = removeNode(pRtree, pNode, iHeight);
109388    }else{
109389      fixBoundingBox(pRtree, pNode);
109390    }
109391  }
109392
109393  return rc;
109394}
109395
109396static int Reinsert(
109397  Rtree *pRtree,
109398  RtreeNode *pNode,
109399  RtreeCell *pCell,
109400  int iHeight
109401){
109402  int *aOrder;
109403  int *aSpare;
109404  RtreeCell *aCell;
109405  float *aDistance;
109406  int nCell;
109407  float aCenterCoord[RTREE_MAX_DIMENSIONS];
109408  int iDim;
109409  int ii;
109410  int rc = SQLITE_OK;
109411
109412  memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
109413
109414  nCell = NCELL(pNode)+1;
109415
109416  /* Allocate the buffers used by this operation. The allocation is
109417  ** relinquished before this function returns.
109418  */
109419  aCell = (RtreeCell *)sqlite3_malloc(nCell * (
109420    sizeof(RtreeCell) +         /* aCell array */
109421    sizeof(int)       +         /* aOrder array */
109422    sizeof(int)       +         /* aSpare array */
109423    sizeof(float)               /* aDistance array */
109424  ));
109425  if( !aCell ){
109426    return SQLITE_NOMEM;
109427  }
109428  aOrder    = (int *)&aCell[nCell];
109429  aSpare    = (int *)&aOrder[nCell];
109430  aDistance = (float *)&aSpare[nCell];
109431
109432  for(ii=0; ii<nCell; ii++){
109433    if( ii==(nCell-1) ){
109434      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
109435    }else{
109436      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
109437    }
109438    aOrder[ii] = ii;
109439    for(iDim=0; iDim<pRtree->nDim; iDim++){
109440      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
109441      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
109442    }
109443  }
109444  for(iDim=0; iDim<pRtree->nDim; iDim++){
109445    aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
109446  }
109447
109448  for(ii=0; ii<nCell; ii++){
109449    aDistance[ii] = 0.0;
109450    for(iDim=0; iDim<pRtree->nDim; iDim++){
109451      float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) -
109452          DCOORD(aCell[ii].aCoord[iDim*2]);
109453      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
109454    }
109455  }
109456
109457  SortByDistance(aOrder, nCell, aDistance, aSpare);
109458  nodeZero(pRtree, pNode);
109459
109460  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
109461    RtreeCell *p = &aCell[aOrder[ii]];
109462    nodeInsertCell(pRtree, pNode, p);
109463    if( p->iRowid==pCell->iRowid ){
109464      if( iHeight==0 ){
109465        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
109466      }else{
109467        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
109468      }
109469    }
109470  }
109471  if( rc==SQLITE_OK ){
109472    fixBoundingBox(pRtree, pNode);
109473  }
109474  for(; rc==SQLITE_OK && ii<nCell; ii++){
109475    /* Find a node to store this cell in. pNode->iNode currently contains
109476    ** the height of the sub-tree headed by the cell.
109477    */
109478    RtreeNode *pInsert;
109479    RtreeCell *p = &aCell[aOrder[ii]];
109480    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
109481    if( rc==SQLITE_OK ){
109482      int rc2;
109483      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
109484      rc2 = nodeRelease(pRtree, pInsert);
109485      if( rc==SQLITE_OK ){
109486        rc = rc2;
109487      }
109488    }
109489  }
109490
109491  sqlite3_free(aCell);
109492  return rc;
109493}
109494
109495/*
109496** Insert cell pCell into node pNode. Node pNode is the head of a
109497** subtree iHeight high (leaf nodes have iHeight==0).
109498*/
109499static int rtreeInsertCell(
109500  Rtree *pRtree,
109501  RtreeNode *pNode,
109502  RtreeCell *pCell,
109503  int iHeight
109504){
109505  int rc = SQLITE_OK;
109506  if( iHeight>0 ){
109507    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
109508    if( pChild ){
109509      nodeRelease(pRtree, pChild->pParent);
109510      nodeReference(pNode);
109511      pChild->pParent = pNode;
109512    }
109513  }
109514  if( nodeInsertCell(pRtree, pNode, pCell) ){
109515#if VARIANT_RSTARTREE_REINSERT
109516    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
109517      rc = SplitNode(pRtree, pNode, pCell, iHeight);
109518    }else{
109519      pRtree->iReinsertHeight = iHeight;
109520      rc = Reinsert(pRtree, pNode, pCell, iHeight);
109521    }
109522#else
109523    rc = SplitNode(pRtree, pNode, pCell, iHeight);
109524#endif
109525  }else{
109526    AdjustTree(pRtree, pNode, pCell);
109527    if( iHeight==0 ){
109528      rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
109529    }else{
109530      rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
109531    }
109532  }
109533  return rc;
109534}
109535
109536static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
109537  int ii;
109538  int rc = SQLITE_OK;
109539  int nCell = NCELL(pNode);
109540
109541  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
109542    RtreeNode *pInsert;
109543    RtreeCell cell;
109544    nodeGetCell(pRtree, pNode, ii, &cell);
109545
109546    /* Find a node to store this cell in. pNode->iNode currently contains
109547    ** the height of the sub-tree headed by the cell.
109548    */
109549    rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
109550    if( rc==SQLITE_OK ){
109551      int rc2;
109552      rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
109553      rc2 = nodeRelease(pRtree, pInsert);
109554      if( rc==SQLITE_OK ){
109555        rc = rc2;
109556      }
109557    }
109558  }
109559  return rc;
109560}
109561
109562/*
109563** Select a currently unused rowid for a new r-tree record.
109564*/
109565static int newRowid(Rtree *pRtree, i64 *piRowid){
109566  int rc;
109567  sqlite3_bind_null(pRtree->pWriteRowid, 1);
109568  sqlite3_bind_null(pRtree->pWriteRowid, 2);
109569  sqlite3_step(pRtree->pWriteRowid);
109570  rc = sqlite3_reset(pRtree->pWriteRowid);
109571  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
109572  return rc;
109573}
109574
109575#ifndef NDEBUG
109576static int hashIsEmpty(Rtree *pRtree){
109577  int ii;
109578  for(ii=0; ii<HASHSIZE; ii++){
109579    assert( !pRtree->aHash[ii] );
109580  }
109581  return 1;
109582}
109583#endif
109584
109585/*
109586** The xUpdate method for rtree module virtual tables.
109587*/
109588static int rtreeUpdate(
109589  sqlite3_vtab *pVtab,
109590  int nData,
109591  sqlite3_value **azData,
109592  sqlite_int64 *pRowid
109593){
109594  Rtree *pRtree = (Rtree *)pVtab;
109595  int rc = SQLITE_OK;
109596
109597  rtreeReference(pRtree);
109598
109599  assert(nData>=1);
109600  assert(hashIsEmpty(pRtree));
109601
109602  /* If azData[0] is not an SQL NULL value, it is the rowid of a
109603  ** record to delete from the r-tree table. The following block does
109604  ** just that.
109605  */
109606  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
109607    i64 iDelete;                /* The rowid to delete */
109608    RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
109609    int iCell;                  /* Index of iDelete cell in pLeaf */
109610    RtreeNode *pRoot;
109611
109612    /* Obtain a reference to the root node to initialise Rtree.iDepth */
109613    rc = nodeAcquire(pRtree, 1, 0, &pRoot);
109614
109615    /* Obtain a reference to the leaf node that contains the entry
109616    ** about to be deleted.
109617    */
109618    if( rc==SQLITE_OK ){
109619      iDelete = sqlite3_value_int64(azData[0]);
109620      rc = findLeafNode(pRtree, iDelete, &pLeaf);
109621    }
109622
109623    /* Delete the cell in question from the leaf node. */
109624    if( rc==SQLITE_OK ){
109625      int rc2;
109626      iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
109627      rc = deleteCell(pRtree, pLeaf, iCell, 0);
109628      rc2 = nodeRelease(pRtree, pLeaf);
109629      if( rc==SQLITE_OK ){
109630        rc = rc2;
109631      }
109632    }
109633
109634    /* Delete the corresponding entry in the <rtree>_rowid table. */
109635    if( rc==SQLITE_OK ){
109636      sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
109637      sqlite3_step(pRtree->pDeleteRowid);
109638      rc = sqlite3_reset(pRtree->pDeleteRowid);
109639    }
109640
109641    /* Check if the root node now has exactly one child. If so, remove
109642    ** it, schedule the contents of the child for reinsertion and
109643    ** reduce the tree height by one.
109644    **
109645    ** This is equivalent to copying the contents of the child into
109646    ** the root node (the operation that Gutman's paper says to perform
109647    ** in this scenario).
109648    */
109649    if( rc==SQLITE_OK && pRtree->iDepth>0 ){
109650      if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
109651        RtreeNode *pChild;
109652        i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
109653        rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
109654        if( rc==SQLITE_OK ){
109655          rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
109656        }
109657        if( rc==SQLITE_OK ){
109658          pRtree->iDepth--;
109659          writeInt16(pRoot->zData, pRtree->iDepth);
109660          pRoot->isDirty = 1;
109661        }
109662      }
109663    }
109664
109665    /* Re-insert the contents of any underfull nodes removed from the tree. */
109666    for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
109667      if( rc==SQLITE_OK ){
109668        rc = reinsertNodeContent(pRtree, pLeaf);
109669      }
109670      pRtree->pDeleted = pLeaf->pNext;
109671      sqlite3_free(pLeaf);
109672    }
109673
109674    /* Release the reference to the root node. */
109675    if( rc==SQLITE_OK ){
109676      rc = nodeRelease(pRtree, pRoot);
109677    }else{
109678      nodeRelease(pRtree, pRoot);
109679    }
109680  }
109681
109682  /* If the azData[] array contains more than one element, elements
109683  ** (azData[2]..azData[argc-1]) contain a new record to insert into
109684  ** the r-tree structure.
109685  */
109686  if( rc==SQLITE_OK && nData>1 ){
109687    /* Insert a new record into the r-tree */
109688    RtreeCell cell;
109689    int ii;
109690    RtreeNode *pLeaf;
109691
109692    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
109693    assert( nData==(pRtree->nDim*2 + 3) );
109694    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
109695      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
109696        cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
109697        cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
109698        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
109699          rc = SQLITE_CONSTRAINT;
109700          goto constraint;
109701        }
109702      }
109703    }else{
109704      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
109705        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
109706        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
109707        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
109708          rc = SQLITE_CONSTRAINT;
109709          goto constraint;
109710        }
109711      }
109712    }
109713
109714    /* Figure out the rowid of the new row. */
109715    if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
109716      rc = newRowid(pRtree, &cell.iRowid);
109717    }else{
109718      cell.iRowid = sqlite3_value_int64(azData[2]);
109719      sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
109720      if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
109721        sqlite3_reset(pRtree->pReadRowid);
109722        rc = SQLITE_CONSTRAINT;
109723        goto constraint;
109724      }
109725      rc = sqlite3_reset(pRtree->pReadRowid);
109726    }
109727
109728    if( rc==SQLITE_OK ){
109729      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
109730    }
109731    if( rc==SQLITE_OK ){
109732      int rc2;
109733      pRtree->iReinsertHeight = -1;
109734      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
109735      rc2 = nodeRelease(pRtree, pLeaf);
109736      if( rc==SQLITE_OK ){
109737        rc = rc2;
109738      }
109739    }
109740  }
109741
109742constraint:
109743  rtreeRelease(pRtree);
109744  return rc;
109745}
109746
109747/*
109748** The xRename method for rtree module virtual tables.
109749*/
109750static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
109751  Rtree *pRtree = (Rtree *)pVtab;
109752  int rc = SQLITE_NOMEM;
109753  char *zSql = sqlite3_mprintf(
109754    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
109755    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
109756    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
109757    , pRtree->zDb, pRtree->zName, zNewName
109758    , pRtree->zDb, pRtree->zName, zNewName
109759    , pRtree->zDb, pRtree->zName, zNewName
109760  );
109761  if( zSql ){
109762    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
109763    sqlite3_free(zSql);
109764  }
109765  return rc;
109766}
109767
109768static sqlite3_module rtreeModule = {
109769  0,                         /* iVersion */
109770  rtreeCreate,                /* xCreate - create a table */
109771  rtreeConnect,               /* xConnect - connect to an existing table */
109772  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
109773  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
109774  rtreeDestroy,               /* xDestroy - Drop a table */
109775  rtreeOpen,                  /* xOpen - open a cursor */
109776  rtreeClose,                 /* xClose - close a cursor */
109777  rtreeFilter,                /* xFilter - configure scan constraints */
109778  rtreeNext,                  /* xNext - advance a cursor */
109779  rtreeEof,                   /* xEof */
109780  rtreeColumn,                /* xColumn - read data */
109781  rtreeRowid,                 /* xRowid - read data */
109782  rtreeUpdate,                /* xUpdate - write data */
109783  0,                          /* xBegin - begin transaction */
109784  0,                          /* xSync - sync transaction */
109785  0,                          /* xCommit - commit transaction */
109786  0,                          /* xRollback - rollback transaction */
109787  0,                          /* xFindFunction - function overloading */
109788  rtreeRename                 /* xRename - rename the table */
109789};
109790
109791static int rtreeSqlInit(
109792  Rtree *pRtree,
109793  sqlite3 *db,
109794  const char *zDb,
109795  const char *zPrefix,
109796  int isCreate
109797){
109798  int rc = SQLITE_OK;
109799
109800  #define N_STATEMENT 9
109801  static const char *azSql[N_STATEMENT] = {
109802    /* Read and write the xxx_node table */
109803    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
109804    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
109805    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
109806
109807    /* Read and write the xxx_rowid table */
109808    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
109809    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
109810    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
109811
109812    /* Read and write the xxx_parent table */
109813    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
109814    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
109815    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
109816  };
109817  sqlite3_stmt **appStmt[N_STATEMENT];
109818  int i;
109819
109820  pRtree->db = db;
109821
109822  if( isCreate ){
109823    char *zCreate = sqlite3_mprintf(
109824"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
109825"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
109826"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
109827"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
109828      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
109829    );
109830    if( !zCreate ){
109831      return SQLITE_NOMEM;
109832    }
109833    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
109834    sqlite3_free(zCreate);
109835    if( rc!=SQLITE_OK ){
109836      return rc;
109837    }
109838  }
109839
109840  appStmt[0] = &pRtree->pReadNode;
109841  appStmt[1] = &pRtree->pWriteNode;
109842  appStmt[2] = &pRtree->pDeleteNode;
109843  appStmt[3] = &pRtree->pReadRowid;
109844  appStmt[4] = &pRtree->pWriteRowid;
109845  appStmt[5] = &pRtree->pDeleteRowid;
109846  appStmt[6] = &pRtree->pReadParent;
109847  appStmt[7] = &pRtree->pWriteParent;
109848  appStmt[8] = &pRtree->pDeleteParent;
109849
109850  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
109851    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
109852    if( zSql ){
109853      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
109854    }else{
109855      rc = SQLITE_NOMEM;
109856    }
109857    sqlite3_free(zSql);
109858  }
109859
109860  return rc;
109861}
109862
109863/*
109864** This routine queries database handle db for the page-size used by
109865** database zDb. If successful, the page-size in bytes is written to
109866** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error
109867** code is returned.
109868*/
109869static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){
109870  int rc = SQLITE_NOMEM;
109871  char *zSql;
109872  sqlite3_stmt *pStmt = 0;
109873
109874  zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb);
109875  if( !zSql ){
109876    return SQLITE_NOMEM;
109877  }
109878
109879  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
109880  sqlite3_free(zSql);
109881  if( rc!=SQLITE_OK ){
109882    return rc;
109883  }
109884
109885  if( SQLITE_ROW==sqlite3_step(pStmt) ){
109886    *piPageSize = sqlite3_column_int(pStmt, 0);
109887  }
109888  return sqlite3_finalize(pStmt);
109889}
109890
109891/*
109892** This function is the implementation of both the xConnect and xCreate
109893** methods of the r-tree virtual table.
109894**
109895**   argv[0]   -> module name
109896**   argv[1]   -> database name
109897**   argv[2]   -> table name
109898**   argv[...] -> column names...
109899*/
109900static int rtreeInit(
109901  sqlite3 *db,                        /* Database connection */
109902  void *pAux,                         /* One of the RTREE_COORD_* constants */
109903  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
109904  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
109905  char **pzErr,                       /* OUT: Error message, if any */
109906  int isCreate                        /* True for xCreate, false for xConnect */
109907){
109908  int rc = SQLITE_OK;
109909  int iPageSize = 0;
109910  Rtree *pRtree;
109911  int nDb;              /* Length of string argv[1] */
109912  int nName;            /* Length of string argv[2] */
109913  int eCoordType = (int)pAux;
109914
109915  const char *aErrMsg[] = {
109916    0,                                                    /* 0 */
109917    "Wrong number of columns for an rtree table",         /* 1 */
109918    "Too few columns for an rtree table",                 /* 2 */
109919    "Too many columns for an rtree table"                 /* 3 */
109920  };
109921
109922  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
109923  if( aErrMsg[iErr] ){
109924    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
109925    return SQLITE_ERROR;
109926  }
109927
109928  rc = getPageSize(db, argv[1], &iPageSize);
109929  if( rc!=SQLITE_OK ){
109930    return rc;
109931  }
109932
109933  /* Allocate the sqlite3_vtab structure */
109934  nDb = strlen(argv[1]);
109935  nName = strlen(argv[2]);
109936  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
109937  if( !pRtree ){
109938    return SQLITE_NOMEM;
109939  }
109940  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
109941  pRtree->nBusy = 1;
109942  pRtree->base.pModule = &rtreeModule;
109943  pRtree->zDb = (char *)&pRtree[1];
109944  pRtree->zName = &pRtree->zDb[nDb+1];
109945  pRtree->nDim = (argc-4)/2;
109946  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
109947  pRtree->eCoordType = eCoordType;
109948  memcpy(pRtree->zDb, argv[1], nDb);
109949  memcpy(pRtree->zName, argv[2], nName);
109950
109951  /* Figure out the node size to use. By default, use 64 bytes less than
109952  ** the database page-size. This ensures that each node is stored on
109953  ** a single database page.
109954  **
109955  ** If the databasd page-size is so large that more than RTREE_MAXCELLS
109956  ** entries would fit in a single node, use a smaller node-size.
109957  */
109958  pRtree->iNodeSize = iPageSize-64;
109959  if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
109960    pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
109961  }
109962
109963  /* Create/Connect to the underlying relational database schema. If
109964  ** that is successful, call sqlite3_declare_vtab() to configure
109965  ** the r-tree table schema.
109966  */
109967  if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
109968    *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
109969  }else{
109970    char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
109971    char *zTmp;
109972    int ii;
109973    for(ii=4; zSql && ii<argc; ii++){
109974      zTmp = zSql;
109975      zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
109976      sqlite3_free(zTmp);
109977    }
109978    if( zSql ){
109979      zTmp = zSql;
109980      zSql = sqlite3_mprintf("%s);", zTmp);
109981      sqlite3_free(zTmp);
109982    }
109983    if( !zSql ){
109984      rc = SQLITE_NOMEM;
109985    }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
109986      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
109987    }
109988    sqlite3_free(zSql);
109989  }
109990
109991  if( rc==SQLITE_OK ){
109992    *ppVtab = (sqlite3_vtab *)pRtree;
109993  }else{
109994    rtreeRelease(pRtree);
109995  }
109996  return rc;
109997}
109998
109999
110000/*
110001** Implementation of a scalar function that decodes r-tree nodes to
110002** human readable strings. This can be used for debugging and analysis.
110003**
110004** The scalar function takes two arguments, a blob of data containing
110005** an r-tree node, and the number of dimensions the r-tree indexes.
110006** For a two-dimensional r-tree structure called "rt", to deserialize
110007** all nodes, a statement like:
110008**
110009**   SELECT rtreenode(2, data) FROM rt_node;
110010**
110011** The human readable string takes the form of a Tcl list with one
110012** entry for each cell in the r-tree node. Each entry is itself a
110013** list, containing the 8-byte rowid/pageno followed by the
110014** <num-dimension>*2 coordinates.
110015*/
110016static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
110017  char *zText = 0;
110018  RtreeNode node;
110019  Rtree tree;
110020  int ii;
110021
110022  memset(&node, 0, sizeof(RtreeNode));
110023  memset(&tree, 0, sizeof(Rtree));
110024  tree.nDim = sqlite3_value_int(apArg[0]);
110025  tree.nBytesPerCell = 8 + 8 * tree.nDim;
110026  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
110027
110028  for(ii=0; ii<NCELL(&node); ii++){
110029    char zCell[512];
110030    int nCell = 0;
110031    RtreeCell cell;
110032    int jj;
110033
110034    nodeGetCell(&tree, &node, ii, &cell);
110035    sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
110036    nCell = strlen(zCell);
110037    for(jj=0; jj<tree.nDim*2; jj++){
110038      sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
110039      nCell = strlen(zCell);
110040    }
110041
110042    if( zText ){
110043      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
110044      sqlite3_free(zText);
110045      zText = zTextNew;
110046    }else{
110047      zText = sqlite3_mprintf("{%s}", zCell);
110048    }
110049  }
110050
110051  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
110052}
110053
110054static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
110055  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
110056   || sqlite3_value_bytes(apArg[0])<2
110057  ){
110058    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
110059  }else{
110060    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
110061    sqlite3_result_int(ctx, readInt16(zBlob));
110062  }
110063}
110064
110065/*
110066** Register the r-tree module with database handle db. This creates the
110067** virtual table module "rtree" and the debugging/analysis scalar
110068** function "rtreenode".
110069*/
110070SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
110071  int rc = SQLITE_OK;
110072
110073  if( rc==SQLITE_OK ){
110074    int utf8 = SQLITE_UTF8;
110075    rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
110076  }
110077  if( rc==SQLITE_OK ){
110078    int utf8 = SQLITE_UTF8;
110079    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
110080  }
110081  if( rc==SQLITE_OK ){
110082    void *c = (void *)RTREE_COORD_REAL32;
110083    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
110084  }
110085  if( rc==SQLITE_OK ){
110086    void *c = (void *)RTREE_COORD_INT32;
110087    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
110088  }
110089
110090  return rc;
110091}
110092
110093#if !SQLITE_CORE
110094SQLITE_API int sqlite3_extension_init(
110095  sqlite3 *db,
110096  char **pzErrMsg,
110097  const sqlite3_api_routines *pApi
110098){
110099  SQLITE_EXTENSION_INIT2(pApi)
110100  return sqlite3RtreeInit(db);
110101}
110102#endif
110103
110104#endif
110105
110106/************** End of rtree.c ***********************************************/
110107/************** Begin file icu.c *********************************************/
110108/*
110109** 2007 May 6
110110**
110111** The author disclaims copyright to this source code.  In place of
110112** a legal notice, here is a blessing:
110113**
110114**    May you do good and not evil.
110115**    May you find forgiveness for yourself and forgive others.
110116**    May you share freely, never taking more than you give.
110117**
110118*************************************************************************
110119** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
110120**
110121** This file implements an integration between the ICU library
110122** ("International Components for Unicode", an open-source library
110123** for handling unicode data) and SQLite. The integration uses
110124** ICU to provide the following to SQLite:
110125**
110126**   * An implementation of the SQL regexp() function (and hence REGEXP
110127**     operator) using the ICU uregex_XX() APIs.
110128**
110129**   * Implementations of the SQL scalar upper() and lower() functions
110130**     for case mapping.
110131**
110132**   * Integration of ICU and SQLite collation seqences.
110133**
110134**   * An implementation of the LIKE operator that uses ICU to
110135**     provide case-independent matching.
110136*/
110137
110138#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
110139
110140/* Include ICU headers */
110141#include <unicode/utypes.h>
110142#include <unicode/uregex.h>
110143#include <unicode/ustring.h>
110144#include <unicode/ucol.h>
110145
110146
110147#ifndef SQLITE_CORE
110148  SQLITE_EXTENSION_INIT1
110149#else
110150#endif
110151
110152/*
110153** Maximum length (in bytes) of the pattern in a LIKE or GLOB
110154** operator.
110155*/
110156#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
110157# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
110158#endif
110159
110160/*
110161** Version of sqlite3_free() that is always a function, never a macro.
110162*/
110163static void xFree(void *p){
110164  sqlite3_free(p);
110165}
110166
110167/*
110168** Compare two UTF-8 strings for equality where the first string is
110169** a "LIKE" expression. Return true (1) if they are the same and
110170** false (0) if they are different.
110171*/
110172static int icuLikeCompare(
110173  const uint8_t *zPattern,   /* LIKE pattern */
110174  const uint8_t *zString,    /* The UTF-8 string to compare against */
110175  const UChar32 uEsc         /* The escape character */
110176){
110177  static const int MATCH_ONE = (UChar32)'_';
110178  static const int MATCH_ALL = (UChar32)'%';
110179
110180  int iPattern = 0;       /* Current byte index in zPattern */
110181  int iString = 0;        /* Current byte index in zString */
110182
110183  int prevEscape = 0;     /* True if the previous character was uEsc */
110184
110185  while( zPattern[iPattern]!=0 ){
110186
110187    /* Read (and consume) the next character from the input pattern. */
110188    UChar32 uPattern;
110189    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
110190    assert(uPattern!=0);
110191
110192    /* There are now 4 possibilities:
110193    **
110194    **     1. uPattern is an unescaped match-all character "%",
110195    **     2. uPattern is an unescaped match-one character "_",
110196    **     3. uPattern is an unescaped escape character, or
110197    **     4. uPattern is to be handled as an ordinary character
110198    */
110199    if( !prevEscape && uPattern==MATCH_ALL ){
110200      /* Case 1. */
110201      uint8_t c;
110202
110203      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
110204      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
110205      ** test string.
110206      */
110207      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
110208        if( c==MATCH_ONE ){
110209          if( zString[iString]==0 ) return 0;
110210          U8_FWD_1_UNSAFE(zString, iString);
110211        }
110212        iPattern++;
110213      }
110214
110215      if( zPattern[iPattern]==0 ) return 1;
110216
110217      while( zString[iString] ){
110218        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
110219          return 1;
110220        }
110221        U8_FWD_1_UNSAFE(zString, iString);
110222      }
110223      return 0;
110224
110225    }else if( !prevEscape && uPattern==MATCH_ONE ){
110226      /* Case 2. */
110227      if( zString[iString]==0 ) return 0;
110228      U8_FWD_1_UNSAFE(zString, iString);
110229
110230    }else if( !prevEscape && uPattern==uEsc){
110231      /* Case 3. */
110232      prevEscape = 1;
110233
110234    }else{
110235      /* Case 4. */
110236      UChar32 uString;
110237      U8_NEXT_UNSAFE(zString, iString, uString);
110238      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
110239      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
110240      if( uString!=uPattern ){
110241        return 0;
110242      }
110243      prevEscape = 0;
110244    }
110245  }
110246
110247  return zString[iString]==0;
110248}
110249
110250/*
110251** Implementation of the like() SQL function.  This function implements
110252** the build-in LIKE operator.  The first argument to the function is the
110253** pattern and the second argument is the string.  So, the SQL statements:
110254**
110255**       A LIKE B
110256**
110257** is implemented as like(B, A). If there is an escape character E,
110258**
110259**       A LIKE B ESCAPE E
110260**
110261** is mapped to like(B, A, E).
110262*/
110263static void icuLikeFunc(
110264  sqlite3_context *context,
110265  int argc,
110266  sqlite3_value **argv
110267){
110268  const unsigned char *zA = sqlite3_value_text(argv[0]);
110269  const unsigned char *zB = sqlite3_value_text(argv[1]);
110270  UChar32 uEsc = 0;
110271
110272  /* Limit the length of the LIKE or GLOB pattern to avoid problems
110273  ** of deep recursion and N*N behavior in patternCompare().
110274  */
110275  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
110276    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
110277    return;
110278  }
110279
110280
110281  if( argc==3 ){
110282    /* The escape character string must consist of a single UTF-8 character.
110283    ** Otherwise, return an error.
110284    */
110285    int nE= sqlite3_value_bytes(argv[2]);
110286    const unsigned char *zE = sqlite3_value_text(argv[2]);
110287    int i = 0;
110288    if( zE==0 ) return;
110289    U8_NEXT(zE, i, nE, uEsc);
110290    if( i!=nE){
110291      sqlite3_result_error(context,
110292          "ESCAPE expression must be a single character", -1);
110293      return;
110294    }
110295  }
110296
110297  if( zA && zB ){
110298    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
110299  }
110300}
110301
110302/*
110303** This function is called when an ICU function called from within
110304** the implementation of an SQL scalar function returns an error.
110305**
110306** The scalar function context passed as the first argument is
110307** loaded with an error message based on the following two args.
110308*/
110309static void icuFunctionError(
110310  sqlite3_context *pCtx,       /* SQLite scalar function context */
110311  const char *zName,           /* Name of ICU function that failed */
110312  UErrorCode e                 /* Error code returned by ICU function */
110313){
110314  char zBuf[128];
110315  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
110316  zBuf[127] = '\0';
110317  sqlite3_result_error(pCtx, zBuf, -1);
110318}
110319
110320/*
110321** Function to delete compiled regexp objects. Registered as
110322** a destructor function with sqlite3_set_auxdata().
110323*/
110324static void icuRegexpDelete(void *p){
110325  URegularExpression *pExpr = (URegularExpression *)p;
110326  uregex_close(pExpr);
110327}
110328
110329/*
110330** Implementation of SQLite REGEXP operator. This scalar function takes
110331** two arguments. The first is a regular expression pattern to compile
110332** the second is a string to match against that pattern. If either
110333** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
110334** is 1 if the string matches the pattern, or 0 otherwise.
110335**
110336** SQLite maps the regexp() function to the regexp() operator such
110337** that the following two are equivalent:
110338**
110339**     zString REGEXP zPattern
110340**     regexp(zPattern, zString)
110341**
110342** Uses the following ICU regexp APIs:
110343**
110344**     uregex_open()
110345**     uregex_matches()
110346**     uregex_close()
110347*/
110348static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
110349  UErrorCode status = U_ZERO_ERROR;
110350  URegularExpression *pExpr;
110351  UBool res;
110352  const UChar *zString = sqlite3_value_text16(apArg[1]);
110353
110354  /* If the left hand side of the regexp operator is NULL,
110355  ** then the result is also NULL.
110356  */
110357  if( !zString ){
110358    return;
110359  }
110360
110361  pExpr = sqlite3_get_auxdata(p, 0);
110362  if( !pExpr ){
110363    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
110364    if( !zPattern ){
110365      return;
110366    }
110367    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
110368
110369    if( U_SUCCESS(status) ){
110370      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
110371    }else{
110372      assert(!pExpr);
110373      icuFunctionError(p, "uregex_open", status);
110374      return;
110375    }
110376  }
110377
110378  /* Configure the text that the regular expression operates on. */
110379  uregex_setText(pExpr, zString, -1, &status);
110380  if( !U_SUCCESS(status) ){
110381    icuFunctionError(p, "uregex_setText", status);
110382    return;
110383  }
110384
110385  /* Attempt the match */
110386  res = uregex_matches(pExpr, 0, &status);
110387  if( !U_SUCCESS(status) ){
110388    icuFunctionError(p, "uregex_matches", status);
110389    return;
110390  }
110391
110392  /* Set the text that the regular expression operates on to a NULL
110393  ** pointer. This is not really necessary, but it is tidier than
110394  ** leaving the regular expression object configured with an invalid
110395  ** pointer after this function returns.
110396  */
110397  uregex_setText(pExpr, 0, 0, &status);
110398
110399  /* Return 1 or 0. */
110400  sqlite3_result_int(p, res ? 1 : 0);
110401}
110402
110403/*
110404** Implementations of scalar functions for case mapping - upper() and
110405** lower(). Function upper() converts its input to upper-case (ABC).
110406** Function lower() converts to lower-case (abc).
110407**
110408** ICU provides two types of case mapping, "general" case mapping and
110409** "language specific". Refer to ICU documentation for the differences
110410** between the two.
110411**
110412** To utilise "general" case mapping, the upper() or lower() scalar
110413** functions are invoked with one argument:
110414**
110415**     upper('ABC') -> 'abc'
110416**     lower('abc') -> 'ABC'
110417**
110418** To access ICU "language specific" case mapping, upper() or lower()
110419** should be invoked with two arguments. The second argument is the name
110420** of the locale to use. Passing an empty string ("") or SQL NULL value
110421** as the second argument is the same as invoking the 1 argument version
110422** of upper() or lower().
110423**
110424**     lower('I', 'en_us') -> 'i'
110425**     lower('I', 'tr_tr') -> '��' (small dotless i)
110426**
110427** http://www.icu-project.org/userguide/posix.html#case_mappings
110428*/
110429static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
110430  const UChar *zInput;
110431  UChar *zOutput;
110432  int nInput;
110433  int nOutput;
110434
110435  UErrorCode status = U_ZERO_ERROR;
110436  const char *zLocale = 0;
110437
110438  assert(nArg==1 || nArg==2);
110439  if( nArg==2 ){
110440    zLocale = (const char *)sqlite3_value_text(apArg[1]);
110441  }
110442
110443  zInput = sqlite3_value_text16(apArg[0]);
110444  if( !zInput ){
110445    return;
110446  }
110447  nInput = sqlite3_value_bytes16(apArg[0]);
110448
110449  nOutput = nInput * 2 + 2;
110450  zOutput = sqlite3_malloc(nOutput);
110451  if( !zOutput ){
110452    return;
110453  }
110454
110455  if( sqlite3_user_data(p) ){
110456    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
110457  }else{
110458    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
110459  }
110460
110461  if( !U_SUCCESS(status) ){
110462    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
110463    return;
110464  }
110465
110466  sqlite3_result_text16(p, zOutput, -1, xFree);
110467}
110468
110469/*
110470** Collation sequence destructor function. The pCtx argument points to
110471** a UCollator structure previously allocated using ucol_open().
110472*/
110473static void icuCollationDel(void *pCtx){
110474  UCollator *p = (UCollator *)pCtx;
110475  ucol_close(p);
110476}
110477
110478/*
110479** Collation sequence comparison function. The pCtx argument points to
110480** a UCollator structure previously allocated using ucol_open().
110481*/
110482static int icuCollationColl(
110483  void *pCtx,
110484  int nLeft,
110485  const void *zLeft,
110486  int nRight,
110487  const void *zRight
110488){
110489  UCollationResult res;
110490  UCollator *p = (UCollator *)pCtx;
110491  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
110492  switch( res ){
110493    case UCOL_LESS:    return -1;
110494    case UCOL_GREATER: return +1;
110495    case UCOL_EQUAL:   return 0;
110496  }
110497  assert(!"Unexpected return value from ucol_strcoll()");
110498  return 0;
110499}
110500
110501/*
110502** Implementation of the scalar function icu_load_collation().
110503**
110504** This scalar function is used to add ICU collation based collation
110505** types to an SQLite database connection. It is intended to be called
110506** as follows:
110507**
110508**     SELECT icu_load_collation(<locale>, <collation-name>);
110509**
110510** Where <locale> is a string containing an ICU locale identifier (i.e.
110511** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
110512** collation sequence to create.
110513*/
110514static void icuLoadCollation(
110515  sqlite3_context *p,
110516  int nArg,
110517  sqlite3_value **apArg
110518){
110519  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
110520  UErrorCode status = U_ZERO_ERROR;
110521  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
110522  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
110523  UCollator *pUCollator;    /* ICU library collation object */
110524  int rc;                   /* Return code from sqlite3_create_collation_x() */
110525
110526  assert(nArg==2);
110527  zLocale = (const char *)sqlite3_value_text(apArg[0]);
110528  zName = (const char *)sqlite3_value_text(apArg[1]);
110529
110530  if( !zLocale || !zName ){
110531    return;
110532  }
110533
110534  pUCollator = ucol_open(zLocale, &status);
110535  if( !U_SUCCESS(status) ){
110536    icuFunctionError(p, "ucol_open", status);
110537    return;
110538  }
110539  assert(p);
110540
110541  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
110542      icuCollationColl, icuCollationDel
110543  );
110544  if( rc!=SQLITE_OK ){
110545    ucol_close(pUCollator);
110546    sqlite3_result_error(p, "Error registering collation function", -1);
110547  }
110548}
110549
110550/*
110551** Register the ICU extension functions with database db.
110552*/
110553SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
110554  struct IcuScalar {
110555    const char *zName;                        /* Function name */
110556    int nArg;                                 /* Number of arguments */
110557    int enc;                                  /* Optimal text encoding */
110558    void *pContext;                           /* sqlite3_user_data() context */
110559    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
110560  } scalars[] = {
110561    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
110562
110563    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
110564    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
110565    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
110566    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
110567
110568    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
110569    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
110570    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
110571    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
110572
110573    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
110574    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
110575
110576    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
110577  };
110578
110579  int rc = SQLITE_OK;
110580  int i;
110581
110582  for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
110583    struct IcuScalar *p = &scalars[i];
110584    rc = sqlite3_create_function(
110585        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
110586    );
110587  }
110588
110589  return rc;
110590}
110591
110592#if !SQLITE_CORE
110593SQLITE_API int sqlite3_extension_init(
110594  sqlite3 *db,
110595  char **pzErrMsg,
110596  const sqlite3_api_routines *pApi
110597){
110598  SQLITE_EXTENSION_INIT2(pApi)
110599  return sqlite3IcuInit(db);
110600}
110601#endif
110602
110603#endif
110604
110605/************** End of icu.c *************************************************/
110606/************** Begin file fts3_icu.c ****************************************/
110607/*
110608** 2007 June 22
110609**
110610** The author disclaims copyright to this source code.  In place of
110611** a legal notice, here is a blessing:
110612**
110613**    May you do good and not evil.
110614**    May you find forgiveness for yourself and forgive others.
110615**    May you share freely, never taking more than you give.
110616**
110617*************************************************************************
110618** This file implements a tokenizer for fts3 based on the ICU library.
110619**
110620** $Id: fts3_icu.c,v 1.3 2008/09/01 18:34:20 danielk1977 Exp $
110621*/
110622
110623#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
110624#ifdef SQLITE_ENABLE_ICU
110625
110626
110627#include <unicode/ubrk.h>
110628#include <unicode/utf16.h>
110629
110630typedef struct IcuTokenizer IcuTokenizer;
110631typedef struct IcuCursor IcuCursor;
110632
110633struct IcuTokenizer {
110634  sqlite3_tokenizer base;
110635  char *zLocale;
110636};
110637
110638struct IcuCursor {
110639  sqlite3_tokenizer_cursor base;
110640
110641  UBreakIterator *pIter;      /* ICU break-iterator object */
110642  int nChar;                  /* Number of UChar elements in pInput */
110643  UChar *aChar;               /* Copy of input using utf-16 encoding */
110644  int *aOffset;               /* Offsets of each character in utf-8 input */
110645
110646  int nBuffer;
110647  char *zBuffer;
110648
110649  int iToken;
110650};
110651
110652/*
110653** Create a new tokenizer instance.
110654*/
110655static int icuCreate(
110656  int argc,                            /* Number of entries in argv[] */
110657  const char * const *argv,            /* Tokenizer creation arguments */
110658  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
110659){
110660  IcuTokenizer *p;
110661  int n = 0;
110662
110663  if( argc>0 ){
110664    n = strlen(argv[0])+1;
110665  }
110666  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
110667  if( !p ){
110668    return SQLITE_NOMEM;
110669  }
110670  memset(p, 0, sizeof(IcuTokenizer));
110671
110672  if( n ){
110673    p->zLocale = (char *)&p[1];
110674    memcpy(p->zLocale, argv[0], n);
110675  }
110676
110677  *ppTokenizer = (sqlite3_tokenizer *)p;
110678
110679  return SQLITE_OK;
110680}
110681
110682/*
110683** Destroy a tokenizer
110684*/
110685static int icuDestroy(sqlite3_tokenizer *pTokenizer){
110686  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
110687  sqlite3_free(p);
110688  return SQLITE_OK;
110689}
110690
110691/*
110692** Prepare to begin tokenizing a particular string.  The input
110693** string to be tokenized is pInput[0..nBytes-1].  A cursor
110694** used to incrementally tokenize this string is returned in
110695** *ppCursor.
110696*/
110697static int icuOpen(
110698  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
110699  const char *zInput,                    /* Input string */
110700  int nInput,                            /* Length of zInput in bytes */
110701  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
110702){
110703  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
110704  IcuCursor *pCsr;
110705
110706  const int32_t opt = U_FOLD_CASE_DEFAULT;
110707  UErrorCode status = U_ZERO_ERROR;
110708  int nChar;
110709
110710  UChar32 c;
110711  int iInput = 0;
110712  int iOut = 0;
110713
110714  *ppCursor = 0;
110715
110716  if( nInput<0 ){
110717    nInput = strlen(zInput);
110718  }
110719  nChar = nInput+1;
110720  pCsr = (IcuCursor *)sqlite3_malloc(
110721      sizeof(IcuCursor) +                /* IcuCursor */
110722      nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
110723      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
110724  );
110725  if( !pCsr ){
110726    return SQLITE_NOMEM;
110727  }
110728  memset(pCsr, 0, sizeof(IcuCursor));
110729  pCsr->aChar = (UChar *)&pCsr[1];
110730  pCsr->aOffset = (int *)&pCsr->aChar[nChar];
110731
110732  pCsr->aOffset[iOut] = iInput;
110733  U8_NEXT(zInput, iInput, nInput, c);
110734  while( c>0 ){
110735    int isError = 0;
110736    c = u_foldCase(c, opt);
110737    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
110738    if( isError ){
110739      sqlite3_free(pCsr);
110740      return SQLITE_ERROR;
110741    }
110742    pCsr->aOffset[iOut] = iInput;
110743
110744    if( iInput<nInput ){
110745      U8_NEXT(zInput, iInput, nInput, c);
110746    }else{
110747      c = 0;
110748    }
110749  }
110750
110751  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
110752  if( !U_SUCCESS(status) ){
110753    sqlite3_free(pCsr);
110754    return SQLITE_ERROR;
110755  }
110756  pCsr->nChar = iOut;
110757
110758  ubrk_first(pCsr->pIter);
110759  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
110760  return SQLITE_OK;
110761}
110762
110763/*
110764** Close a tokenization cursor previously opened by a call to icuOpen().
110765*/
110766static int icuClose(sqlite3_tokenizer_cursor *pCursor){
110767  IcuCursor *pCsr = (IcuCursor *)pCursor;
110768  ubrk_close(pCsr->pIter);
110769  sqlite3_free(pCsr->zBuffer);
110770  sqlite3_free(pCsr);
110771  return SQLITE_OK;
110772}
110773
110774/*
110775** Extract the next token from a tokenization cursor.
110776*/
110777static int icuNext(
110778  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
110779  const char **ppToken,               /* OUT: *ppToken is the token text */
110780  int *pnBytes,                       /* OUT: Number of bytes in token */
110781  int *piStartOffset,                 /* OUT: Starting offset of token */
110782  int *piEndOffset,                   /* OUT: Ending offset of token */
110783  int *piPosition                     /* OUT: Position integer of token */
110784){
110785  IcuCursor *pCsr = (IcuCursor *)pCursor;
110786
110787  int iStart = 0;
110788  int iEnd = 0;
110789  int nByte = 0;
110790
110791  while( iStart==iEnd ){
110792    UChar32 c;
110793
110794    iStart = ubrk_current(pCsr->pIter);
110795    iEnd = ubrk_next(pCsr->pIter);
110796    if( iEnd==UBRK_DONE ){
110797      return SQLITE_DONE;
110798    }
110799
110800    while( iStart<iEnd ){
110801      int iWhite = iStart;
110802      U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
110803      if( u_isspace(c) ){
110804        iStart = iWhite;
110805      }else{
110806        break;
110807      }
110808    }
110809    assert(iStart<=iEnd);
110810  }
110811
110812  do {
110813    UErrorCode status = U_ZERO_ERROR;
110814    if( nByte ){
110815      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
110816      if( !zNew ){
110817        return SQLITE_NOMEM;
110818      }
110819      pCsr->zBuffer = zNew;
110820      pCsr->nBuffer = nByte;
110821    }
110822
110823    u_strToUTF8(
110824        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
110825        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
110826        &status                                  /* Output success/failure */
110827    );
110828  } while( nByte>pCsr->nBuffer );
110829
110830  *ppToken = pCsr->zBuffer;
110831  *pnBytes = nByte;
110832  *piStartOffset = pCsr->aOffset[iStart];
110833  *piEndOffset = pCsr->aOffset[iEnd];
110834  *piPosition = pCsr->iToken++;
110835
110836  return SQLITE_OK;
110837}
110838
110839/*
110840** The set of routines that implement the simple tokenizer
110841*/
110842static const sqlite3_tokenizer_module icuTokenizerModule = {
110843  0,                           /* iVersion */
110844  icuCreate,                   /* xCreate  */
110845  icuDestroy,                  /* xCreate  */
110846  icuOpen,                     /* xOpen    */
110847  icuClose,                    /* xClose   */
110848  icuNext,                     /* xNext    */
110849};
110850
110851/*
110852** Set *ppModule to point at the implementation of the ICU tokenizer.
110853*/
110854SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
110855  sqlite3_tokenizer_module const**ppModule
110856){
110857  *ppModule = &icuTokenizerModule;
110858}
110859
110860#endif /* defined(SQLITE_ENABLE_ICU) */
110861#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
110862
110863/************** End of fts3_icu.c ********************************************/
110864